diff --git a/src/dr/app/beast/development_parsers.properties b/src/dr/app/beast/development_parsers.properties index 021e964cfa..4fd127b04c 100644 --- a/src/dr/app/beast/development_parsers.properties +++ b/src/dr/app/beast/development_parsers.properties @@ -165,9 +165,6 @@ dr.inference.model.SVDStatistic dr.inferencexml.operators.factorAnalysis.IntegratedFactorsParser dr.evomodelxml.continuous.hmc.TaxonEffectGradientParser -# SEQUENCE SIMULATOR -dr.app.seqgen.RecomboGen - # POPULATION MODELS dr.evomodel.epidemiology.LogisticGrowthN0ModelParser dr.evomodelxml.coalescent.demographicmodel.ExponentialConstantModelParser diff --git a/src/dr/app/beast/release_parsers.properties b/src/dr/app/beast/release_parsers.properties index 9e1a9ec59f..470860af53 100644 --- a/src/dr/app/beast/release_parsers.properties +++ b/src/dr/app/beast/release_parsers.properties @@ -45,10 +45,6 @@ dr.evoxml.GeneralDataTypeParser dr.evoxml.CompositeDataTypeParser dr.evoxml.DateParser dr.evoxml.LocationParser -dr.evoxml.OldHiddenNucleotideParser -dr.evoxml.MicrosatelliteParser -dr.evoxml.MicrosatellitePatternParser -dr.evoxml.MicrosatelliteSimulatorParser dr.evoxml.KStateDataTypeParser dr.evoxml.MutationDeathTypeParser dr.evoxml.MetagenomeDataParser @@ -286,7 +282,6 @@ dr.evoxml.MultiLociDistanceParser # TREE MODELS dr.evomodelxml.tree.TreeModelParser -dr.evomodelxml.tree.MicrosatelliteSamplerTreeModelParser dr.evomodelxml.tree.TipHeightLikelihoodParser dr.evomodelxml.tree.TreeMetricStatisticParser dr.evomodelxml.tree.TreeLengthStatisticParser @@ -327,14 +322,8 @@ dr.evomodelxml.operators.GibbsPruneAndRegraftParser dr.evomodelxml.operators.RateExchangeOperatorParser dr.evomodelxml.operators.TreeBitMoveOperatorParser dr.evomodelxml.operators.TreeBitRandomWalkOperatorParser -dr.evomodelxml.operators.TreeNodeSlideParser dr.evomodel.continuous.GibbsIndependentCoalescentOperator dr.evomodel.continuous.CoalescentTreeRejectionSampler -dr.evomodelxml.operators.MicrosatelliteUpDownOperatorParser -dr.evomodelxml.operators.MicrosatelliteBitFlipOperatorParser -dr.evomodelxml.operators.MicrosatelliteModelSelectOperatorParser -dr.evomodelxml.operators.MicrosatelliteFullAncestryImportanceSamplingOperatorParser -dr.evomodelxml.operators.MicrosatelliteSingleAncestralStateGibbsOperatorParser dr.evomodelxml.operators.RandomWalkIntegerNodeHeightWeightedOperatorParser dr.evomodelxml.operators.RandomWalkIntegerSetSizeWeightedOperatorParser @@ -350,7 +339,7 @@ dr.evomodelxml.tree.CTMCScalePriorParser # RATE OPERATORS dr.evomodelxml.operators.RateScaleOperatorParser dr.evomodelxml.operators.RateVarianceScaleOperatorParser -dr.evomodelxml.operators.RateSampleOperatorParser +#dr.evomodelxml.operators.RateSampleOperatorParser # LIKELIHOODS dr.inferencexml.model.CompoundLikelihoodParser @@ -546,19 +535,16 @@ dr.inferencexml.model.DiagonalMatrixParser dr.inferencexml.model.CompoundSymmetricMatrixParser dr.inferencexml.model.CorrelationSymmetricMatrixParser dr.inferencexml.model.MarkovRandomFieldMatrixParser -dr.inferencexml.distribution.MultivariateOUModelParser +#dr.inferencexml.distribution.MultivariateOUModelParser dr.inferencexml.model.CachedMatrixInverseParser -dr.oldevomodelxml.substmodel.PositiveDefiniteSubstitutionModelParser +dr.evomodelxml.substmodel.PositiveDefiniteSubstitutionModelParser # STOCHASTIC VARIABLE SELECTION dr.evomodel.operators.BitFlipInSubstitutionModelOperator dr.inference.operators.RateBitExchangeOperator dr.inferencexml.distribution.CachedDistributionLikelihoodParser -# SEQUENCE SIMULATOR -dr.app.seqgen.SequenceSimulator - # SPECIAL STATISTICS dr.inference.model.MonotonicStatistic dr.inference.model.MatrixInverseStatistic @@ -580,34 +566,32 @@ dr.inferencexml.model.LikelihoodBenchmarkerParser dr.inferencexml.distribution.EmpiricalDistributionLikelihoodParser # ANCESTRAL RECOMBINATION GRAPHS -dr.evomodel.arg.coalescent.ARGCoalescentLikelihood -dr.evomodel.arg.coalescent.ARGUniformPrior -dr.evomodel.arg.likelihood.ARGLikelihood -dr.evomodel.arg.operators.SlidingPatternsOperator -dr.evomodel.arg.branchratemodel.ARGDiscretizedBranchRates -dr.evomodel.arg.ARGModel -dr.evomodel.arg.UniformPartitionLikelihood -dr.evomodel.arg.operators.ARGSubtreeSlideOperator -dr.evomodel.arg.operators.ARGExchangeOperator -dr.evomodel.arg.operators.ObsoleteARGAddRemoveEventOperator -dr.evomodel.arg.operators.ARGPartitioningOperator -dr.evomodel.arg.operators.ObsoleteARGNewEventOperator -dr.evomodel.arg.operators.ARGAddRemoveEventOperator -dr.evomodel.arg.operators.ARGSwapOperator -dr.evomodel.arg.ARGReassortmentNodeCountStatistic -dr.evomodel.arg.ARGTraceAnalysisParser -dr.evomodel.arg.ARGReassortmentTimingStatistic -dr.evomodel.arg.PoissonPartitionLikelihood -dr.evomodel.arg.RecombinationPartitionStatistic -dr.evomodel.arg.ARGTotalLengthStatistic -dr.evomodel.arg.ARGDistinctTreeCountStatistic -dr.evomodel.arg.HierarchicalPartitionLikelihood -dr.evomodel.arg.ARGRelaxedClock -dr.evomodel.arg.ARGRatePrior -dr.evomodel.arg.ARGTreeLogger -dr.evomodel.arg.ARGLogger - -dr.evoxml.MicrosatellitePatternStatisticParser +#dr.evomodel.arg.coalescent.ARGCoalescentLikelihood +#dr.evomodel.arg.coalescent.ARGUniformPrior +#dr.evomodel.arg.likelihood.ARGLikelihood +#dr.evomodel.arg.operators.SlidingPatternsOperator +#dr.evomodel.arg.branchratemodel.ARGDiscretizedBranchRates +#dr.evomodel.arg.ARGModel +#dr.evomodel.arg.UniformPartitionLikelihood +#dr.evomodel.arg.operators.ARGSubtreeSlideOperator +#dr.evomodel.arg.operators.ARGExchangeOperator +#dr.evomodel.arg.operators.ObsoleteARGAddRemoveEventOperator +#dr.evomodel.arg.operators.ARGPartitioningOperator +#dr.evomodel.arg.operators.ObsoleteARGNewEventOperator +#dr.evomodel.arg.operators.ARGAddRemoveEventOperator +#dr.evomodel.arg.operators.ARGSwapOperator +#dr.evomodel.arg.ARGReassortmentNodeCountStatistic +#dr.evomodel.arg.ARGTraceAnalysisParser +#dr.evomodel.arg.ARGReassortmentTimingStatistic +#dr.evomodel.arg.PoissonPartitionLikelihood +#dr.evomodel.arg.RecombinationPartitionStatistic +#dr.evomodel.arg.ARGTotalLengthStatistic +#dr.evomodel.arg.ARGDistinctTreeCountStatistic +#dr.evomodel.arg.HierarchicalPartitionLikelihood +#dr.evomodel.arg.ARGRelaxedClock +#dr.evomodel.arg.ARGRatePrior +#dr.evomodel.arg.ARGTreeLogger +#dr.evomodel.arg.ARGLogger # N & S counting dr.evomodel.trace.DnDsPerSiteAnalysis @@ -728,34 +712,3 @@ dr.evomodel.antigenic.NPAntigenicLikelihood # NEW ANTIGENIC EVOLUTION/EVOLUTIONARY CARTOGRAPHY dr.evomodelxml.antigenic.AntigenicLikelihoodParser dr.evomodelxml.antigenic.AntigenicLikelihoodGradientParser - -## AlloppNet by Graham Jones -# ALLOPOLYPLOID NETWORKS -dr.evomodel.alloppnet.parsers.AlloppMSCoalescentParser -dr.evomodel.alloppnet.parsers.AlloppNetworkPriorModelParser -dr.evomodel.alloppnet.parsers.AlloppNetworkPriorParser -dr.evomodel.alloppnet.parsers.AlloppSpeciesBindingsApSpInfoParser -dr.evomodel.alloppnet.parsers.AlloppSpeciesBindingsIndividualParser -dr.evomodel.alloppnet.parsers.AlloppSpeciesBindingsParser -dr.evomodel.alloppnet.parsers.AlloppSpeciesNetworkModelParser -dr.evomodel.alloppnet.parsers.AlloppNumHybsStatisticParser - -# MULTIPLY LABELLED TREES -dr.evomodel.alloppnet.parsers.MulMSCoalescentParser -dr.evomodel.alloppnet.parsers.MulSpeciesBindingsParser -dr.evomodel.alloppnet.parsers.MulSpeciesTreeModelParser -dr.evomodel.alloppnet.parsers.MulSpeciesTreePriorParser - -# OPERATORS -dr.evomodel.alloppnet.parsers.AlloppNetworkNodeSlideParser -dr.evomodel.alloppnet.parsers.AlloppSequenceReassignmentParser -dr.evomodel.alloppnet.parsers.AlloppMoveLegsParser -dr.evomodel.alloppnet.parsers.AlloppChangeNumHybridizationsParser -dr.evomodel.alloppnet.parsers.AlloppHybPopSizesScaleParser -dr.evomodel.alloppnet.parsers.MulTreeNodeSlideParser -dr.evomodel.alloppnet.parsers.MulTreeSequenceReassignmentParser - -## DISSECT by Graham Jones -# SPECIES DELIMITATION -dr.evomodel.alloppnet.parsers.BirthDeathCollapseModelParser -dr.evomodel.alloppnet.parsers.BirthDeathCollapseNClustersStatisticParser diff --git a/src/dr/app/beauti/components/ancestralstates/AncestralStatesComponentGenerator.java b/src/dr/app/beauti/components/ancestralstates/AncestralStatesComponentGenerator.java index 20b28be377..45e9d0e3e4 100644 --- a/src/dr/app/beauti/components/ancestralstates/AncestralStatesComponentGenerator.java +++ b/src/dr/app/beauti/components/ancestralstates/AncestralStatesComponentGenerator.java @@ -38,8 +38,8 @@ import dr.evomodel.coalescent.basta.StructuredCoalescentLikelihoodParser; import dr.evomodel.tree.DefaultTreeModel; import dr.evomodelxml.tree.TreeLoggerParser; +import dr.evomodelxml.treelikelihood.AncestralStateTreeLikelihoodParser; import dr.evomodelxml.treelikelihood.MarkovJumpsTreeLikelihoodParser; -import dr.oldevomodelxml.treelikelihood.AncestralStateTreeLikelihoodParser; import dr.util.Attribute; import java.util.ArrayList; diff --git a/src/dr/app/beauti/components/dollo/DolloComponentGenerator.java b/src/dr/app/beauti/components/dollo/DolloComponentGenerator.java index 092624f373..c7a0a42401 100644 --- a/src/dr/app/beauti/components/dollo/DolloComponentGenerator.java +++ b/src/dr/app/beauti/components/dollo/DolloComponentGenerator.java @@ -33,16 +33,11 @@ import dr.evolution.datatype.DataType; import dr.evomodel.branchratemodel.BranchRateModel; import dr.evomodel.tree.DefaultTreeModel; -import dr.oldevomodel.sitemodel.GammaSiteModel; -import dr.oldevomodel.sitemodel.SiteModel; -import dr.oldevomodelxml.MSSD.ALSSiteModelParser; -import dr.oldevomodelxml.MSSD.ALSTreeLikelihoodParser; import dr.evomodelxml.branchratemodel.DiscretizedBranchRatesParser; import dr.evomodelxml.branchratemodel.RandomLocalClockModelParser; import dr.evomodelxml.branchratemodel.StrictClockBranchRatesParser; -import dr.oldevomodelxml.sitemodel.GammaSiteModelParser; -import dr.oldevomodelxml.substmodel.MutationDeathModelParser; -import dr.oldevomodelxml.treelikelihood.TreeLikelihoodParser; +import dr.evomodelxml.substmodel.MutationDeathModelParser; +import dr.evomodelxml.treelikelihood.ALSTreeLikelihoodParser; import dr.evoxml.AlignmentParser; import dr.evoxml.MutationDeathTypeParser; import dr.evoxml.SitePatternsParser; @@ -50,6 +45,11 @@ import dr.util.Attribute; import dr.xml.XMLParser; +import static dr.evomodelxml.siteratemodel.SiteModelParser.*; +import static dr.evomodelxml.substmodel.MutationDeathModelParser.MD_MODEL; +import static dr.evomodelxml.treelikelihood.BeagleTreeLikelihoodParser.TREE_LIKELIHOOD; +import static dr.evomodelxml.treelikelihood.BeagleTreeLikelihoodParser.USE_AMBIGUITIES; + /** * @author Marc Suchard */ @@ -195,7 +195,7 @@ private void writeDolloSubstitutionModels(XMLWriter writer, DolloComponentOption if (model.isDolloModel()) { writeDolloSubstitutionModel(partition, writer, component); writeDolloSiteModel(partition, writer, component); - writeDolloTreeLikelihood(TreeLikelihoodParser.TREE_LIKELIHOOD, -1, partition, writer); + writeDolloTreeLikelihood(TREE_LIKELIHOOD, -1, partition, writer); } } } @@ -203,42 +203,42 @@ private void writeDolloSubstitutionModels(XMLWriter writer, DolloComponentOption private void writeDolloSubstitutionModel(AbstractPartitionData partition, XMLWriter writer, DolloComponentOptions component) { String prefix = partition.getName() + "."; // String prefix = partition.getPrefix(); // TODO Fix - writer.writeOpenTag(MutationDeathModelParser.MD_MODEL, + writer.writeOpenTag(MD_MODEL, new Attribute.Default(XMLParser.ID, prefix + DolloComponentOptions.MODEL_NAME )); writeParameter(prefix + DolloComponentOptions.DEATH_RATE, component.getOptions().getParameter(prefix + DolloComponentOptions.DEATH_RATE), writer); writer.writeTag(DataType.DATA_TYPE, new Attribute.Default(XMLParser.IDREF, DolloComponentOptions.DATA_NAME), true); - writer.writeCloseTag(MutationDeathModelParser.MD_MODEL); + writer.writeCloseTag(MD_MODEL); writer.write("\n"); } private void writeDolloSiteModel(AbstractPartitionData partition, XMLWriter writer, DolloComponentOptions components) { String prefix = partition.getName() + "."; - writer.writeOpenTag(ALSSiteModelParser.ALS_SITE_MODEL, - new Attribute[]{new Attribute.Default(XMLParser.ID, prefix + SiteModel.SITE_MODEL)}); + writer.writeOpenTag(SITE_MODEL, + new Attribute[]{new Attribute.Default(XMLParser.ID, prefix + SITE_MODEL)}); - writer.writeOpenTag(GammaSiteModelParser.SUBSTITUTION_MODEL); + writer.writeOpenTag(SUBSTITUTION_MODEL); writer.writeIDref(MutationDeathModelParser.MD_MODEL, prefix + DolloComponentOptions.MODEL_NAME); - writer.writeCloseTag(GammaSiteModelParser.SUBSTITUTION_MODEL); + writer.writeCloseTag(SUBSTITUTION_MODEL); PartitionSubstitutionModel model = partition.getPartitionSubstitutionModel(); if (model.hasCodonPartitions()) { - writeParameter(GammaSiteModelParser.RELATIVE_RATE, "mu", model, writer); + writeParameter(RELATIVE_RATE, "mu", model, writer); } if (model.isGammaHetero()) { - writer.writeOpenTag(GammaSiteModelParser.GAMMA_SHAPE, - new Attribute.Default(GammaSiteModelParser.GAMMA_CATEGORIES, "" + model.getRateCategories())); + writer.writeOpenTag(GAMMA_SHAPE, + new Attribute.Default(GAMMA_CATEGORIES, "" + model.getGammaCategories())); writeParameter(prefix + "alpha", model, writer); - writer.writeCloseTag(GammaSiteModelParser.GAMMA_SHAPE); + writer.writeCloseTag(GAMMA_SHAPE); } if (model.isInvarHetero()) { - writeParameter(GammaSiteModelParser.PROPORTION_INVARIANT, "pInv", model, writer); + writeParameter(PROPORTION_INVARIANT, "pInv", model, writer); } - writer.writeCloseTag(ALSSiteModelParser.ALS_SITE_MODEL); + writer.writeCloseTag(SITE_MODEL); } // private void writeDolloTreeLikelihoods(XMLWriter writer, DolloComponentOptions component) { @@ -266,7 +266,7 @@ private void writeDolloTreeLikelihood(String id, int num, AbstractPartitionData ALSTreeLikelihoodParser.LIKE_NAME, new Attribute[]{ new Attribute.Default(XMLParser.ID, oldPrefix + id), - new Attribute.Default(TreeLikelihoodParser.USE_AMBIGUITIES, true), + new Attribute.Default(USE_AMBIGUITIES, true), new Attribute.Default(ALSTreeLikelihoodParser.INTEGRATE_GAIN_RATE, true)} ); @@ -280,7 +280,7 @@ private void writeDolloTreeLikelihood(String id, int num, AbstractPartitionData } writer.writeIDref(DefaultTreeModel.TREE_MODEL, treeModel.getPrefix() + DefaultTreeModel.TREE_MODEL); - writer.writeIDref(GammaSiteModel.SITE_MODEL, prefix + SiteModel.SITE_MODEL); + writer.writeIDref(SITE_MODEL, prefix + SITE_MODEL); writer.writeTag(ALSTreeLikelihoodParser.OBSERVATION_PROCESS, new Attribute.Default(ALSTreeLikelihoodParser.OBSERVATION_TYPE,ALSTreeLikelihoodParser.ANY_TIP), diff --git a/src/dr/app/beauti/generator/OperatorsGenerator.java b/src/dr/app/beauti/generator/OperatorsGenerator.java index ede15bb1b4..e637323518 100644 --- a/src/dr/app/beauti/generator/OperatorsGenerator.java +++ b/src/dr/app/beauti/generator/OperatorsGenerator.java @@ -60,8 +60,6 @@ import dr.inferencexml.operators.*; import dr.inferencexml.operators.hmc.HamiltonianMonteCarloOperatorParser; import dr.inferencexml.operators.shrinkage.BayesianBridgeShrinkageOperatorParser; -import dr.oldevomodel.substmodel.AbstractSubstitutionModel; -import dr.oldevomodelxml.substmodel.GeneralSubstitutionModelParser; import dr.util.Attribute; import dr.util.Transform; import dr.util.TransformParsers; @@ -70,6 +68,8 @@ import java.util.ArrayList; import java.util.List; +import static dr.evomodel.substmodel.BaseSubstitutionModel.MODEL; +import static dr.evomodelxml.substmodel.GeneralSubstitutionModelParser.GENERAL_SUBSTITUTION_MODEL; import static dr.inferencexml.distribution.PriorParsers.GAMMA_PRIOR; /** @@ -436,7 +436,7 @@ private void writeBitFlipInSubstOperator(Operator operator, XMLWriter writer) { writeParameter1Ref(writer, operator); // writeOperatorRef(writer, operator); PartitionSubstitutionModel model = (PartitionSubstitutionModel) operator.getOptions(); - writer.writeIDref(GeneralSubstitutionModelParser.GENERAL_SUBSTITUTION_MODEL, model.getPrefix() + AbstractSubstitutionModel.MODEL); + writer.writeIDref(GENERAL_SUBSTITUTION_MODEL, model.getPrefix() + MODEL); // writer.writeCloseTag(BitFlipInSubstitutionModelOperator.BIT_FLIP_OPERATOR); } diff --git a/src/dr/app/beauti/generator/TreeLikelihoodGenerator.java b/src/dr/app/beauti/generator/TreeLikelihoodGenerator.java index eae5dda4b3..7727f37419 100644 --- a/src/dr/app/beauti/generator/TreeLikelihoodGenerator.java +++ b/src/dr/app/beauti/generator/TreeLikelihoodGenerator.java @@ -29,18 +29,15 @@ import dr.app.beauti.types.ClockType; import dr.evomodel.tree.DefaultTreeModel; +import dr.evomodelxml.siteratemodel.SiteModelParser; import dr.evomodelxml.treedatalikelihood.TreeDataLikelihoodParser; +import dr.evomodelxml.treelikelihood.AncestralStateTreeLikelihoodParser; import dr.evomodelxml.treelikelihood.MarkovJumpsTreeLikelihoodParser; import dr.app.beauti.components.ComponentFactory; import dr.app.beauti.components.ancestralstates.AncestralStatesComponentOptions; import dr.app.beauti.options.*; import dr.app.beauti.util.XMLWriter; import dr.evolution.datatype.DataType; -import dr.evomodel.branchratemodel.BranchRateModel; -import dr.oldevomodel.sitemodel.GammaSiteModel; -import dr.oldevomodel.sitemodel.SiteModel; -import dr.oldevomodelxml.treelikelihood.AncestralStateTreeLikelihoodParser; -import dr.oldevomodelxml.treelikelihood.TreeLikelihoodParser; import dr.evoxml.AlignmentParser; import dr.evoxml.SitePatternsParser; import dr.util.Attribute; @@ -48,6 +45,11 @@ import java.util.List; +import static dr.evomodelxml.siteratemodel.SiteModelParser.SITE_MODEL; +import static dr.evomodelxml.treedatalikelihood.TreeDataLikelihoodParser.USE_AMBIGUITIES; +import static dr.evomodelxml.treelikelihood.AncestralStateTreeLikelihoodParser.RECONSTRUCTING_TREE_LIKELIHOOD; +import static dr.evomodelxml.treelikelihood.BeagleTreeLikelihoodParser.TREE_LIKELIHOOD; + /** * @author Alexei Drummond * @author Andrew Rambaut @@ -92,7 +94,7 @@ public void writeTreeDataLikelihood(List partitions, XMLWriter wr Attribute[] attributes = new Attribute[]{ new Attribute.Default(XMLParser.ID, idString), - new Attribute.Default(TreeDataLikelihoodParser.USE_AMBIGUITIES, substModel.isUseAmbiguitiesTreeLikelihood()), + new Attribute.Default(USE_AMBIGUITIES, substModel.isUseAmbiguitiesTreeLikelihood()), new Attribute.Default(TreeDataLikelihoodParser.USE_PREORDER, clockModel.getClockType() == ClockType.HMC_CLOCK || clockModel.getClockType() == ClockType.SHRINKAGE_LOCAL_CLOCK) @@ -118,7 +120,7 @@ public void writeTreeDataLikelihood(List partitions, XMLWriter wr writer.writeOpenTag(TreeDataLikelihoodParser.PARTITION); writeCodonPatternsRef(prefix1, num, substModel.getCodonPartitionCount(), writer); - writer.writeIDref(GammaSiteModel.SITE_MODEL, substModel.getPrefix(num) + SiteModel.SITE_MODEL); + writer.writeIDref(SITE_MODEL, substModel.getPrefix(num) + SITE_MODEL); writer.writeCloseTag(TreeDataLikelihoodParser.PARTITION); } @@ -128,7 +130,7 @@ public void writeTreeDataLikelihood(List partitions, XMLWriter wr String prefix1 = partition.getPrefix(); writer.writeOpenTag(TreeDataLikelihoodParser.PARTITION); writer.writeIDref(SitePatternsParser.PATTERNS, prefix1 + SitePatternsParser.PATTERNS); - writer.writeIDref(GammaSiteModel.SITE_MODEL, substModel.getPrefix() + SiteModel.SITE_MODEL); + writer.writeIDref(SITE_MODEL, substModel.getPrefix() + SITE_MODEL); writer.writeCloseTag(TreeDataLikelihoodParser.PARTITION); } @@ -159,9 +161,9 @@ public void writeTreeLikelihood(PartitionData partition, XMLWriter writer) { return; // DolloComponent will add tree likelihood } - String treeLikelihoodTag = TreeLikelihoodParser.TREE_LIKELIHOOD; + String treeLikelihoodTag = TREE_LIKELIHOOD; if (ancestralStatesOptions.usingAncestralStates(partition)) { - treeLikelihoodTag = TreeLikelihoodParser.ANCESTRAL_TREE_LIKELIHOOD; + treeLikelihoodTag = RECONSTRUCTING_TREE_LIKELIHOOD; if (ancestralStatesOptions.isCountingStates(partition)) { // State change counting uses the MarkovJumpsTreeLikelihood but // dNdS robust counting doesn't as it has its own counting code... @@ -174,12 +176,12 @@ public void writeTreeLikelihood(PartitionData partition, XMLWriter writer) { if (model.getDataType().getType() == DataType.NUCLEOTIDES && model.getCodonHeteroPattern() != null) { for (int i = 1; i <= model.getCodonPartitionCount(); i++) { - writeTreeLikelihood(treeLikelihoodTag, TreeLikelihoodParser.TREE_LIKELIHOOD, i, partition, writer); + writeTreeLikelihood(treeLikelihoodTag, TREE_LIKELIHOOD, i, partition, writer); } } else { - writeTreeLikelihood(treeLikelihoodTag, TreeLikelihoodParser.TREE_LIKELIHOOD, -1, partition, writer); + writeTreeLikelihood(treeLikelihoodTag, TREE_LIKELIHOOD, -1, partition, writer); } } @@ -215,23 +217,23 @@ private void writeTreeLikelihood(String tag, String id, int num, PartitionData p boolean saveCompleteHistory = ancestralStatesOptions.isCompleteHistoryLogging(partition); attributes = new Attribute[]{ new Attribute.Default(XMLParser.ID, idString), - new Attribute.Default(TreeLikelihoodParser.USE_AMBIGUITIES, substModel.isUseAmbiguitiesTreeLikelihood()), + new Attribute.Default(USE_AMBIGUITIES, substModel.isUseAmbiguitiesTreeLikelihood()), new Attribute.Default(MarkovJumpsTreeLikelihoodParser.USE_UNIFORMIZATION, true), new Attribute.Default(MarkovJumpsTreeLikelihoodParser.NUMBER_OF_SIMULANTS, 1), new Attribute.Default(AncestralStateTreeLikelihoodParser.RECONSTRUCTION_TAG_NAME, prefix + AncestralStateTreeLikelihoodParser.RECONSTRUCTION_TAG), new Attribute.Default(MarkovJumpsTreeLikelihoodParser.SAVE_HISTORY, saveCompleteHistory ? "true" : "false"), new Attribute.Default(MarkovJumpsTreeLikelihoodParser.LOG_HISTORY, saveCompleteHistory ? "true" : "false"), }; - } else if (tag.equals(TreeLikelihoodParser.ANCESTRAL_TREE_LIKELIHOOD)) { + } else if (tag.equals(RECONSTRUCTING_TREE_LIKELIHOOD)) { attributes = new Attribute[]{ new Attribute.Default(XMLParser.ID, idString), - new Attribute.Default(TreeLikelihoodParser.USE_AMBIGUITIES, substModel.isUseAmbiguitiesTreeLikelihood()), + new Attribute.Default(USE_AMBIGUITIES, substModel.isUseAmbiguitiesTreeLikelihood()), new Attribute.Default(AncestralStateTreeLikelihoodParser.RECONSTRUCTION_TAG_NAME, prefix + AncestralStateTreeLikelihoodParser.RECONSTRUCTION_TAG), }; } else { attributes = new Attribute[]{ new Attribute.Default(XMLParser.ID, idString), - new Attribute.Default(TreeLikelihoodParser.USE_AMBIGUITIES, substModel.isUseAmbiguitiesTreeLikelihood()) + new Attribute.Default(USE_AMBIGUITIES, substModel.isUseAmbiguitiesTreeLikelihood()) }; } @@ -251,9 +253,9 @@ private void writeTreeLikelihood(String tag, String id, int num, PartitionData p writer.writeIDref(DefaultTreeModel.TREE_MODEL, treeModel.getPrefix() + DefaultTreeModel.TREE_MODEL); if (num > 0) { - writer.writeIDref(GammaSiteModel.SITE_MODEL, substModel.getPrefix(num) + SiteModel.SITE_MODEL); + writer.writeIDref(SITE_MODEL, substModel.getPrefix(num) + SITE_MODEL); } else { - writer.writeIDref(GammaSiteModel.SITE_MODEL, substModel.getPrefix() + SiteModel.SITE_MODEL); + writer.writeIDref(SITE_MODEL, substModel.getPrefix() + SITE_MODEL); } ClockModelGenerator.writeBranchRatesModelRef(clockModel, writer); @@ -296,9 +298,9 @@ public void writeTreeLikelihoodReferences(XMLWriter writer) { return; // DolloComponent will add tree likelihood } - String treeLikelihoodTag = TreeLikelihoodParser.TREE_LIKELIHOOD; + String treeLikelihoodTag = TREE_LIKELIHOOD; if (ancestralStatesOptions.usingAncestralStates(partition)) { - treeLikelihoodTag = TreeLikelihoodParser.ANCESTRAL_TREE_LIKELIHOOD; + treeLikelihoodTag = RECONSTRUCTING_TREE_LIKELIHOOD; if (ancestralStatesOptions.isCountingStates(partition)) { // State change counting uses the MarkovJumpsTreeLikelihood but // dNdS robust counting doesn't as it has its own counting code... @@ -311,11 +313,11 @@ public void writeTreeLikelihoodReferences(XMLWriter writer) { if (model.getDataType().getType() == DataType.NUCLEOTIDES && model.getCodonHeteroPattern() != null) { for (int i = 1; i <= model.getCodonPartitionCount(); i++) { - writeTreeLikelihoodRef(treeLikelihoodTag, TreeLikelihoodParser.TREE_LIKELIHOOD, i, partition, writer); + writeTreeLikelihoodRef(treeLikelihoodTag, TREE_LIKELIHOOD, i, partition, writer); } } else { - writeTreeLikelihoodRef(treeLikelihoodTag, TreeLikelihoodParser.TREE_LIKELIHOOD, -1, partition, writer); + writeTreeLikelihoodRef(treeLikelihoodTag, TREE_LIKELIHOOD, -1, partition, writer); } } } diff --git a/src/dr/app/bss/PartitionData.java b/src/dr/app/bss/PartitionData.java index 58b5008dcf..ad2ac8a840 100644 --- a/src/dr/app/bss/PartitionData.java +++ b/src/dr/app/bss/PartitionData.java @@ -56,7 +56,6 @@ import dr.evomodel.branchratemodel.StrictClockBranchRates; import dr.evomodel.substmodel.aminoacid.*; import dr.evomodel.tree.DefaultTreeModel; -import dr.oldevomodel.sitemodel.SiteModel; import dr.evomodel.tree.TreeModel; import dr.evoxml.TaxaParser; import dr.inference.distribution.ExponentialDistributionModel; @@ -68,6 +67,8 @@ import dr.inferencexml.distribution.InverseGaussianDistributionModelParser; import dr.inferencexml.distribution.LogNormalDistributionModelParser; +import static dr.evomodelxml.siteratemodel.SiteModelParser.SITE_MODEL; + /** * @author Filip Bielejec */ @@ -1042,10 +1043,10 @@ public BranchRateModel createClockRateModel() { public int siteRateModelIndex = 0; - public String siteRateModelIdref = SiteModel.SITE_MODEL; + public String siteRateModelIdref = SITE_MODEL; public void resetSiteRateModelIdref() { - this.siteRateModelIdref = SiteModel.SITE_MODEL; + this.siteRateModelIdref = SITE_MODEL; } public static String[] siteRateModels = { "No Model", // diff --git a/src/dr/app/bss/XMLGenerator.java b/src/dr/app/bss/XMLGenerator.java index 718b34af69..b5f0dc062f 100644 --- a/src/dr/app/bss/XMLGenerator.java +++ b/src/dr/app/bss/XMLGenerator.java @@ -35,7 +35,8 @@ import dr.evolution.tree.TreeUtils; import dr.evomodel.tree.DefaultTreeModel; -import dr.evomodelxml.substmodel.MG94CodonModelParser; +import dr.evomodelxml.siteratemodel.OldGammaSiteModelParser; +import dr.evomodelxml.substmodel.*; import dr.evomodel.substmodel.aminoacid.AminoAcidModelType; import dr.evomodel.substmodel.nucleotide.NucModelType; import dr.app.beagle.tools.parsers.BeagleSequenceSimulatorParser; @@ -45,20 +46,12 @@ import dr.evolution.datatype.DataType; import dr.evolution.util.Taxa; import dr.evolution.util.Taxon; -import dr.oldevomodel.sitemodel.SiteModel; import dr.evomodel.tree.TreeModel; import dr.evomodelxml.branchratemodel.DiscretizedBranchRatesParser; import dr.evomodelxml.branchratemodel.StrictClockBranchRatesParser; import dr.evomodelxml.coalescent.CoalescentSimulatorParser; import dr.evomodelxml.coalescent.demographicmodel.ConstantPopulationModelParser; import dr.evomodelxml.coalescent.demographicmodel.ExponentialGrowthModelParser; -import dr.oldevomodelxml.sitemodel.GammaSiteModelParser; -import dr.oldevomodelxml.substmodel.EmpiricalAminoAcidModelParser; -import dr.oldevomodelxml.substmodel.FrequencyModelParser; -import dr.oldevomodelxml.substmodel.GTRParser; -import dr.oldevomodelxml.substmodel.HKYParser; -import dr.oldevomodelxml.substmodel.TN93Parser; -import dr.oldevomodelxml.substmodel.YangCodonModelParser; import dr.evomodelxml.tree.TreeModelParser; import dr.evoxml.NewickParser; import dr.evoxml.SequenceParser; @@ -74,6 +67,10 @@ import dr.xml.Report; import dr.xml.XMLParser; +import static dr.app.bss.Utils.SUBSTITUTION_MODEL; +import static dr.evomodelxml.siteratemodel.SiteModelParser.SITE_MODEL; +import static dr.evomodelxml.substmodel.GY94CodonModelParser.*; + /** * @author Filip Bielejec */ @@ -526,7 +523,7 @@ private void writeBeagleSequenceSimulator(XMLWriter writer) { case 3: // Yang Codon Model - writer.writeIDref(YangCodonModelParser.YANG_CODON_MODEL, + writer.writeIDref(YANG_CODON_MODEL, data.substitutionModelIdref); break; @@ -580,7 +577,7 @@ private void writeBeagleSequenceSimulator(XMLWriter writer) { }// END: switch - writer.writeIDref(SiteModel.SITE_MODEL, data.siteRateModelIdref); + writer.writeIDref(SITE_MODEL, data.siteRateModelIdref); int clockModel = data.clockModelIndex; switch (clockModel) { @@ -1025,11 +1022,11 @@ private void writeReport(XMLWriter writer) { private void writeSiteRateModel(PartitionData data, XMLWriter writer, int suffix) { - writer.writeOpenTag(SiteModel.SITE_MODEL, + writer.writeOpenTag(SITE_MODEL, new Attribute[] { new Attribute.Default(XMLParser.ID, data.siteRateModelIdref) }); - writer.writeOpenTag(GammaSiteModelParser.SUBSTITUTION_MODEL); + writer.writeOpenTag(SUBSTITUTION_MODEL); int substitutionModelIndex = data.substitutionModelIndex; switch (substitutionModelIndex) { @@ -1053,7 +1050,7 @@ private void writeSiteRateModel(PartitionData data, XMLWriter writer, int suffix case 3: // GY94CodonModel - writer.writeIDref(YangCodonModelParser.YANG_CODON_MODEL, + writer.writeIDref(YANG_CODON_MODEL, data.substitutionModelIdref); break; @@ -1113,7 +1110,7 @@ private void writeSiteRateModel(PartitionData data, XMLWriter writer, int suffix }// END: switch - writer.writeCloseTag(GammaSiteModelParser.SUBSTITUTION_MODEL); + writer.writeCloseTag(SUBSTITUTION_MODEL); int siteRateModelIndex = data.siteRateModelIndex; switch (siteRateModelIndex) { @@ -1127,9 +1124,9 @@ private void writeSiteRateModel(PartitionData data, XMLWriter writer, int suffix case 1: // GammaSiteRateModelParser writer.writeOpenTag( - GammaSiteModelParser.GAMMA_SHAPE, + OldGammaSiteModelParser.GAMMA_SHAPE, new Attribute.Default( - GammaSiteModelParser.GAMMA_CATEGORIES, + OldGammaSiteModelParser.GAMMA_CATEGORIES, String.valueOf((int) data.siteRateModelParameterValues[0]))); //TODO @@ -1137,10 +1134,10 @@ private void writeSiteRateModel(PartitionData data, XMLWriter writer, int suffix String.valueOf(data.siteRateModelParameterValues[1]), writer); - writer.writeCloseTag(GammaSiteModelParser.GAMMA_SHAPE); + writer.writeCloseTag(OldGammaSiteModelParser.GAMMA_SHAPE); if (data.siteRateModelParameterValues[2] > 0.0) { - writeParameter(GammaSiteModelParser.PROPORTION_INVARIANT, "pInv", 1, + writeParameter(OldGammaSiteModelParser.PROPORTION_INVARIANT, "pInv", 1, String.valueOf(data.siteRateModelParameterValues[2]), writer); } @@ -1148,7 +1145,7 @@ private void writeSiteRateModel(PartitionData data, XMLWriter writer, int suffix break; }// END: switch - writer.writeCloseTag(SiteModel.SITE_MODEL); + writer.writeCloseTag(SITE_MODEL); }// END: writeSiteModel @@ -1234,23 +1231,23 @@ private void writeBranchModel(PartitionData data, XMLWriter writer, case 3: // Yang Codon Model - writer.writeOpenTag(YangCodonModelParser.YANG_CODON_MODEL, + writer.writeOpenTag(YANG_CODON_MODEL, new Attribute[] { new Attribute.Default( XMLParser.ID, data.substitutionModelIdref) }); writer.writeIDref(FrequencyModelParser.FREQUENCY_MODEL, data.frequencyModelIdref); - writeParameter(YangCodonModelParser.OMEGA, - YangCodonModelParser.OMEGA + suffix, 1, + writeParameter(OMEGA, + OMEGA + suffix, 1, String.valueOf(data.substitutionParameterValues[9]), writer); - writeParameter(YangCodonModelParser.KAPPA, - YangCodonModelParser.KAPPA + suffix, 1, + writeParameter(KAPPA, + KAPPA + suffix, 1, String.valueOf(data.substitutionParameterValues[10]), writer); - writer.writeCloseTag(YangCodonModelParser.YANG_CODON_MODEL); + writer.writeCloseTag(YANG_CODON_MODEL); break; diff --git a/src/dr/app/misc/Coevolve.java b/src/dr/app/misc/Coevolve.java deleted file mode 100644 index 9494ecbc11..0000000000 --- a/src/dr/app/misc/Coevolve.java +++ /dev/null @@ -1,412 +0,0 @@ -/* - * Coevolve.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.app.misc; - -import dr.app.util.Utils; -import dr.evolution.alignment.*; -import dr.evolution.datatype.DataType; -import dr.evolution.datatype.GeneralDataType; -import dr.evolution.io.Importer; -import dr.evolution.io.NexusImporter; -import dr.evolution.sequence.Sequence; -import dr.evolution.tree.Tree; -import dr.evolution.util.TaxonList; -import dr.evomodel.tree.DefaultTreeModel; -import dr.oldevomodel.sitemodel.GammaSiteModel; -import dr.oldevomodel.sitemodel.SiteModel; -import dr.evomodel.substmodel.*; -import dr.evomodel.tree.TreeModel; -import dr.oldevomodel.substmodel.FrequencyModel; -import dr.oldevomodel.treelikelihood.TreeLikelihood; -import dr.inference.model.Parameter; -import dr.math.*; -import dr.oldevomodel.substmodel.GeneralSubstitutionModel; -import dr.oldevomodel.substmodel.SubstitutionModel; - -import java.io.*; -import java.util.List; - -/** - * @author Alexei Drummond - * @author Andrew Rambaut - * - */ -public class Coevolve { - - public Coevolve(String fileName, String treeFileName) throws java.io.IOException { - - Alignment alignment = null; - Tree tree = null; - - try { - alignment = readNexusFile(fileName); - tree = readTreeFile(treeFileName); - - } catch (IOException ioex) { - System.err.println("File I/O Error: " + ioex); - return; - } catch (Exception ex) { - System.err.println("Fatal exception: " + ex); - return; - } - - if (alignment == null) { - System.err.println("No alignment in file: " + fileName); - return; - } - - if (tree == null) { - System.err.println("No tree in file: " + fileName); - return; - } - - System.out.println("Alignment read: " + alignment.getSequenceCount() + " taxa, " + alignment.getSiteCount() + " sites."); - System.out.println("Tree read: " + tree.getTaxonCount() + " taxa."); - - PrintWriter pw = new PrintWriter(new FileWriter(fileName + ".out")); - for (int dist = 3; dist < Math.min(alignment.getSiteCount()-200,2000); dist += 3) { - - System.out.print(dist+"\t"); - pw.write(dist+"\t"); - // create a pair alignment of only third positions - Alignment pairAlignment = makePairAlignment(alignment, dist,2,3); - SitePatterns sitePatterns = new SitePatterns(pairAlignment); - - Parameter beta = new Parameter.Default(2, 1.0); - beta.setId("betakappa"); - SubstitutionModel pairModel = makePairSubstModel(alignment, pairAlignment, beta); - runModel2(sitePatterns, pw, tree, pairModel, beta); - } - } - - private SubstitutionModel makePairSubstModel(Alignment alignment, Alignment pairAlignment, Parameter beta) { - - DataType newDataType = makePairDataType(alignment); - - double[] frequencies = pairAlignment.getStateFrequencies(); - Parameter frequencyParameter = new Parameter.Default(frequencies); - FrequencyModel freqModel = new FrequencyModel(newDataType, frequencyParameter); - - return new SitePairSubstitutionModel(newDataType, freqModel, beta); - } - - class SitePairSubstitutionModel extends GeneralSubstitutionModel { - - public SitePairSubstitutionModel(DataType dataType, FrequencyModel freqModel, Parameter beta) { - super(dataType, freqModel, beta, 0); - } - - protected void setupRelativeRates() { - - // WARNING!! Assumes nucleotides! - - int stateCount = dataType.getStateCount(); - - int k = 0; - for (int i = 0; i < stateCount; i++) { - for (int j = i+1; j < stateCount; j++) { - relativeRates[k] = 1.0; - int x1 = i % 4; - int y1 = i / 4; - int x2 = j % 4; - int y2 = j / 4; - // if both nucleotides different in the two pairs then use beta - if (x1 != x2 && y1 != y2) { - relativeRates[k] = ratesParameter.getParameterValue(0); - } - - // if transition at first position then multiply rate by kappa - if (x1 != x2 && (x1 % 2 == x2 % 2)) { - relativeRates[k] *= ratesParameter.getParameterValue(1); - } - // if transition at second position then multiply rate by kappa - if (y1 != y2 && (y1 % 2 == y2 % 2)) { - relativeRates[k] *= ratesParameter.getParameterValue(1); - } - - k += 1; - } - } - } - } - - private DataType makePairDataType(Alignment alignment) { - - DataType dataType = alignment.getDataType(); - int stateCount = dataType.getStateCount(); - - String[] stateChars = new String[stateCount*stateCount]; - for (int i = 0; i < Math.min(10, stateChars.length); i++) { stateChars[i] = String.valueOf((char)('0' + i)); } - if (stateCount > 10) { - for (int i = 10; i < stateChars.length; i++) { stateChars[i] = String.valueOf((char)('A' + i-10)); } - } - - GeneralDataType newDataType = new GeneralDataType(stateChars); -// int[] ambiguities = new int[stateChars.length]; -// for (int i = 0; i < ambiguities.length; i++) { -// ambiguities[i] = i; -// } -// -// // question mark for unknown states -// newDataType.addAmbiguity("?", ambiguities); - - return newDataType; - } - - /** - * @param alignment - * @param dist the distance |i-j| between the site pairs (j = i + dist). - * @param start the first i value considered - * @param step the distance between successive i values (i += step) - * @return an alignment of sites, where each site corresponds to a pair (i, j) in the old alignment. - */ - private Alignment makePairAlignment(Alignment alignment, int dist, int start, int step) { - - DataType dataType = alignment.getDataType(); - int stateCount = dataType.getStateCount(); - - DataType newDataType = makePairDataType(alignment); - - SimpleAlignment pairAlignment = new SimpleAlignment(); - pairAlignment.setDataType(newDataType); - for (int k = 0; k < alignment.getSequenceCount(); k++) { - StringBuffer sequence = new StringBuffer(); - for (int i = start; (i+dist) < alignment.getSiteCount(); i+= step) { - int j = i + dist; - - int state = alignment.getState(k,i) * stateCount + alignment.getState(k, j); - if (state < newDataType.getStateCount()) { - sequence.append(newDataType.getChar(state)); - } else { - sequence.append('?'); - } - } - pairAlignment.addSequence(new Sequence(alignment.getTaxon(k),sequence.toString())); - } - return pairAlignment; - } - - private void runModel2(PatternList patternList, PrintWriter pw, Tree tree, SubstitutionModel substModel, final Parameter betaParameter) { - - final Parameter muParameter = new Parameter.Default(1.0); - muParameter.setId("mu"); - - SiteModel siteModel = new GammaSiteModel(substModel, muParameter, null, 1, null); - DefaultTreeModel treeModel = new DefaultTreeModel(tree); - final TreeLikelihood treeLikelihood = new TreeLikelihood(patternList, treeModel, siteModel, null, null, false, false, true, false, false); - treeLikelihood.setId("likelihood"); - - MultivariateFunction function = new MultivariateFunction() { - - public double evaluate(double[] argument) { - betaParameter.setParameterValue(0, argument[0]); - betaParameter.setParameterValue(1, argument[1]); - muParameter.setParameterValue(0, argument[2]); - double lnL = -treeLikelihood.getLogLikelihood(); - - // System.err.println("" + argument[0] + "\t" + argument[1] + "\t" + argument[2] + "\t" + lnL); - return lnL; - } - - public int getNumArguments() { - return 3; - } - - public double getLowerBound(int n) { - return 0.0; - } - - public double getUpperBound(int n) { - return 100.0; - } - }; - - MultivariateMinimum optimizer = new ConjugateGradientSearch(); - double lnL = optimizer.findMinimum(function, new double[] { 1.0, 1.0, 1.0}, 6, 6); - pw.write(betaParameter.getParameterValue(0)+"\t"); - pw.write(betaParameter.getParameterValue(1)+"\t"); - pw.write(muParameter.getParameterValue(0)+"\t"); - pw.write(lnL+"\n"); - pw.flush(); - System.out.println("" + betaParameter.getParameterValue(0) + "\t" + betaParameter.getParameterValue(1)+"\t" + muParameter.getParameterValue(0)+"\t" + lnL); - } - - /** - * @param fileName - * @throws java.io.IOException - */ - private Alignment readNexusFile(String fileName) throws java.io.IOException { - - Alignment alignment = null; - TaxonList taxonList = null; - - try { - FileReader reader = new FileReader(fileName); - - NexusImporter importer = new NexusImporter(reader); - - boolean done = false; - - while (!done) { - try { - - NexusImporter.NexusBlock block = importer.findNextBlock(); - - if (block == NexusImporter.TAXA_BLOCK) { - - if (taxonList != null) { - throw new NexusImporter.MissingBlockException("TAXA block already defined"); - } - - taxonList = importer.parseTaxaBlock(); - - } else if (block == NexusImporter.DATA_BLOCK) { - - // A data block doesn't need a taxon block before it - // but if one exists then it will use it. - alignment = importer.parseDataBlock(taxonList); - if (taxonList == null) { - taxonList = alignment; - } - - } else if (block == NexusImporter.TREES_BLOCK) { - - // ignore tree block - } else { - // Ignore the block.. - } - - } catch (EOFException ex) { - done = true; - } - } - - } catch (Importer.ImportException ime) { - System.err.println("Error reading alignment: " + ime); - } - - return alignment; - } - - /** - * @param fileName - * @throws java.io.IOException - */ - private Tree readTreeFile(String fileName) throws java.io.IOException { - - Alignment alignment = null; - List trees = null; - TaxonList taxonList = null; - - try { - FileReader reader = new FileReader(fileName); - - NexusImporter importer = new NexusImporter(reader); - - boolean done = false; - - while (!done) { - try { - - NexusImporter.NexusBlock block = importer.findNextBlock(); - - if (block == NexusImporter.TAXA_BLOCK) { - - if (taxonList != null) { - throw new NexusImporter.MissingBlockException("TAXA block already defined"); - } - - taxonList = importer.parseTaxaBlock(); - - } else if (block == NexusImporter.DATA_BLOCK) { - - // A data block doesn't need a taxon block before it - // but if one exists then it will use it. - alignment = importer.parseDataBlock(taxonList); - if (taxonList == null) { - taxonList = alignment; - } - - } else if (block == NexusImporter.TREES_BLOCK) { - - trees = importer.parseTreesBlock(taxonList); - if (taxonList == null) { - taxonList = alignment; - } - - } else { - // Ignore the block.. - } - - } catch (EOFException ex) { - done = true; - } - } - - } catch (Importer.ImportException ime) { - System.err.println("Error reading alignment: " + ime); - } - - return trees.get(0); - } - - // Main entry point - static public void main(String[] args) throws java.io.IOException { - if (args.length > 2) { - System.err.println("Unknown option: " + args[3]); - System.err.println(); - System.out.println("Usage: misc "); - System.exit(1); - } - - String inputFileName = null; - String treeFileName = null; - - if (args.length > 0) { - inputFileName = args[0]; - } - - if (args.length > 1) { - treeFileName = args[1]; - } - - - if (inputFileName == null) { - // No input file name was given so throw up a dialog box... - inputFileName = Utils.getLoadFileName("Select NEXUS file to analyse"); - } - - if (treeFileName == null) { - // No input file name was given so throw up a dialog box... - treeFileName = Utils.getLoadFileName("Select tree file to analyse"); - } - - new Coevolve(inputFileName, treeFileName); - } - -} diff --git a/src/dr/app/seqgen/GeoDiffusionSimulator.java b/src/dr/app/seqgen/GeoDiffusionSimulator.java deleted file mode 100644 index f5fd2dca07..0000000000 --- a/src/dr/app/seqgen/GeoDiffusionSimulator.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * GeoDiffusionSimulator.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.app.seqgen; - -import dr.evolution.util.Taxa; -import dr.evolution.datatype.Microsatellite; -import dr.evolution.tree.Tree; -import dr.evolution.tree.NodeRef; -import dr.evolution.sequence.Sequence; -import dr.oldevomodel.sitemodel.SiteModel; -import dr.evomodel.branchratemodel.BranchRateModel; -import dr.math.MathUtils; -import dr.inference.model.Parameter; - -import java.util.ArrayList; - -/** - * @author Chieh-Hsi Wu - */ -public class GeoDiffusionSimulator extends SequenceSimulator{ - public static final int LATITUDE_INDEX = 0; - public static final int LONGITUDE_INDEX = 1; - private Taxa taxa; - private Microsatellite dataType; - private double maxLat; - private double minLat; - private double maxLong; - private double minLong; - - public GeoDiffusionSimulator( - Microsatellite dataType, - Taxa taxa, - Tree tree, - SiteModel siteModel, - BranchRateModel branchRateModel, - double maxLat, - double minLat, - double maxLong, - double minLong) { - - super(tree, siteModel, branchRateModel, 1); - this.dataType = dataType; - this.taxa = taxa; - this.maxLat = maxLat; - this.minLat = minLat; - this.maxLong = maxLong; - this.minLong = minLong; - - } - - /** - * Convert integer representation of microsatellite length to string. - */ - Sequence intArray2Sequence(int [] seq, NodeRef node) { - String sSeq = ""+seq[0]; - return new Sequence(m_tree.getNodeTaxon(node), sSeq); - } // intArray2Sequence - - public double[][] simulateLocations() { - NodeRef root = m_tree.getRoot(); - - //assume uniform - double[][] latLongs = new double[m_tree.getNodeCount()][2]; - double rootLat = MathUtils.nextDouble()*(maxLat-minLat)+minLat; - double rootLong = MathUtils.nextDouble()*(maxLong-minLong)+minLong; - int rootNum = root.getNumber(); - latLongs[rootNum] [LATITUDE_INDEX] = rootLat; - latLongs[rootNum] [LONGITUDE_INDEX] = rootLong; - traverse(root, latLongs[rootNum], latLongs); - - - - return latLongs; - } - - void traverse(NodeRef node, double [] parentSequence, double[][] latLongs) { - for (int iChild = 0; iChild < m_tree.getChildCount(node); iChild++) { - NodeRef child = m_tree.getChild(node, iChild); - - //find the branch length - final double branchRate = m_branchRateModel.getBranchRate(m_tree, child); - final double branchLength = branchRate * (m_tree.getNodeHeight(node) - m_tree.getNodeHeight(child)); - if (branchLength < 0.0) { - throw new RuntimeException("Negative branch length: " + branchLength); - } - - double childLat = MathUtils.nextGaussian()*Math.sqrt(branchLength)+parentSequence[LATITUDE_INDEX]; - double childLong = MathUtils.nextGaussian()*Math.sqrt(branchLength)+parentSequence[LONGITUDE_INDEX]; - int childNum = child.getNumber(); - - latLongs[childNum][LATITUDE_INDEX] = childLat; - latLongs[childNum][LONGITUDE_INDEX] = childLong; - - traverse(m_tree.getChild(node, iChild), latLongs[childNum], latLongs); - } - } - - /** - * Convert an alignment to a pattern - */ - public ArrayList simulateGeoAttr(){ - double[][] locations = simulateLocations(); - - ArrayList locationList = new ArrayList(); - for(int i = 0; i < m_tree.getExternalNodeCount(); i++){ - NodeRef node = m_tree.getNode(i); - String taxaName = m_tree.getTaxon(node.getNumber()).getId(); - Parameter location = new Parameter.Default(locations[i]); - System.out.println("taxon: "+taxaName+", lat: "+locations[i][0]+", long: "+locations[i][1]); - locationList.add(location); - } - - return locationList; - } - -} diff --git a/src/dr/app/seqgen/MicrosatelliteSimulator.java b/src/dr/app/seqgen/MicrosatelliteSimulator.java deleted file mode 100644 index b6621b92bf..0000000000 --- a/src/dr/app/seqgen/MicrosatelliteSimulator.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * MicrosatelliteSimulator.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.app.seqgen; - -import dr.evolution.tree.Tree; -import dr.evolution.tree.NodeRef; -import dr.evolution.datatype.Microsatellite; -import dr.evolution.alignment.Alignment; -import dr.evolution.alignment.Patterns; -import dr.evolution.sequence.Sequence; -import dr.evolution.util.Taxa; -import dr.oldevomodel.sitemodel.SiteModel; -import dr.oldevomodel.sitemodel.GammaSiteModel; -import dr.evomodel.branchratemodel.BranchRateModel; -import dr.oldevomodel.substmodel.MicrosatelliteModel; - -/** - * @author Chieh-Hsi Wu - * - * Simulates a pattern of microsatellites given a tree and microsatellite model - * - */ -public class MicrosatelliteSimulator extends SequenceSimulator{ - private Taxa taxa; - private Microsatellite dataType; - - public MicrosatelliteSimulator( - Microsatellite dataType, - Taxa taxa, - Tree tree, - MicrosatelliteModel msatModel, - BranchRateModel branchRateModel){ - this(dataType, taxa, tree, new GammaSiteModel(msatModel), branchRateModel); - - } - - public MicrosatelliteSimulator( - Microsatellite dataType, - Taxa taxa, - Tree tree, - SiteModel siteModel, - BranchRateModel branchRateModel) { - - super(tree, siteModel, branchRateModel, 1); - this.dataType = dataType; - this.taxa = taxa; - } - - /** - * Convert integer representation of microsatellite length to string. - */ - Sequence intArray2Sequence(int [] seq, NodeRef node) { - String sSeq = ""+seq[0]; - return new Sequence(m_tree.getNodeTaxon(node), sSeq); - } // intArray2Sequence - - /** - * Convert an alignment to a pattern - */ - public Patterns simulateMsatPattern(){ - Alignment align = simulate(); - - int[] pattern = new int[align.getTaxonCount()]; - for(int i = 0; i < pattern.length; i++){ - String taxonName = align.getSequence(i).getTaxon().getId(); - int index = taxa.getTaxonIndex(taxonName); - pattern[index] = Integer.parseInt(align.getSequence(i).getSequenceString()); - } - Patterns patterns = new Patterns(dataType,taxa); - patterns.addPattern(pattern); - for(int i = 0; i < pattern.length;i++){ - System.out.print(pattern[i]+","); - } - System.out.println(); - - return patterns; - } - -} diff --git a/src/dr/app/seqgen/RecomboGen.java b/src/dr/app/seqgen/RecomboGen.java deleted file mode 100644 index cd94f8b2b0..0000000000 --- a/src/dr/app/seqgen/RecomboGen.java +++ /dev/null @@ -1,434 +0,0 @@ -/* - * RecomboGen.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.app.seqgen; - -import dr.evolution.alignment.Alignment; -import dr.evolution.alignment.SimpleAlignment; -import dr.evolution.coalescent.*; -import dr.evolution.datatype.Nucleotides; -import dr.evolution.sequence.Sequence; -import dr.evolution.tree.*; -import dr.evolution.util.*; -import dr.evomodel.branchratemodel.*; -import dr.oldevomodel.sitemodel.GammaSiteModel; -import dr.oldevomodel.sitemodel.SiteModel; -import dr.oldevomodel.substmodel.FrequencyModel; -import dr.oldevomodel.substmodel.HKY; -import dr.inference.model.Parameter; -import dr.math.MathUtils; -import dr.xml.*; - -import java.util.*; - -/** - * @author Andrew Rambaut - */ -public class RecomboGen { - - public RecomboGen(final double recombinationRate, final int length, - final double ancestralPopulationSize, - final SiteModel siteModel, - final BranchRateModel branchRateModel, - final Taxa taxa) { - this.recombinationRate = recombinationRate; - this.length = length; - this.ancestralPopulationSize = ancestralPopulationSize; - this.siteModel = siteModel; - this.branchRateModel = branchRateModel; - this.taxa = taxa; - calculateHeights(); - } - -// public RecomboGen(final double recombinationRate, final int length, -// final double ancestralPopulationSize, -// final SiteModel siteModel, -// final BranchRateModel branchRateModel, -// final String[] taxonNames, final double[] samplingTimes) { -// this.recombinationRate = recombinationRate; -// this.length = length; -// this.ancestralPopulationSize = ancestralPopulationSize; -// this.siteModel = siteModel; -// this.branchRateModel = branchRateModel; -// this.taxonNames = taxonNames; -// this.samplingTimes = samplingTimes; -// } - - private void calculateHeights() { - - dr.evolution.util.Date mostRecent = null; - boolean usingDates = false; - - for (int i = 0; i < taxa.getTaxonCount(); i++) { - if (TaxonList.Utils.hasAttribute(taxa, i, dr.evolution.util.Date.DATE)) { - usingDates = true; - dr.evolution.util.Date date = (dr.evolution.util.Date)taxa.getTaxonAttribute(i, dr.evolution.util.Date.DATE); - if ((date != null) && (mostRecent == null || date.after(mostRecent))) { - mostRecent = date; - } - } else { - // assume contemporaneous tips - taxa.setTaxonAttribute(i, "height", 0.0); - } - } - - if (usingDates && mostRecent != null ) { - TimeScale timeScale = new TimeScale(mostRecent.getUnits(), true, mostRecent.getAbsoluteTimeValue()); - - for (int i =0; i < taxa.getTaxonCount(); i++) { - dr.evolution.util.Date date = (dr.evolution.util.Date)taxa.getTaxonAttribute(i, dr.evolution.util.Date.DATE); - - if (date == null) { - throw new IllegalArgumentException("Taxon, " + taxa.getTaxonId(i) + ", is missing its date"); - } - - taxa.setTaxonAttribute(i, "height", timeScale.convertTime(date.getTimeValue(), date)); - } - } - } - - public Alignment generate() { - List tips = new ArrayList(); - - // add all the tips - for (int i = 0; i < taxa.getTaxonCount(); i++) { - tips.add(new Node(taxa.getTaxon(i))); - } - Collections.sort(tips); - - List unusedTips = new ArrayList(tips); - - double time = 0; - List nodes = new ArrayList(); - - // Add any tips with zero sampling time. - List nodesToAdd = new ArrayList(); - for (Node tip : unusedTips) { - if (tip.getTime() == 0.0) { - nodesToAdd.add(tip); - System.out.println("Time: " + time + " adding " + tip.getTaxon()); - } - } - nodes.addAll(nodesToAdd); - unusedTips.removeAll(nodesToAdd); - - do { - - boolean tipsAdded; - - do { - tipsAdded = false; - - final int lineageCount = nodes.size(); - - // get time to next event... - final double U = MathUtils.nextDouble(); // create unit uniform random variate - final double interval = -Math.log(U)/ (lineageCount * recombinationRate); - final double nextTime = time + interval; - - // Add any tips for which we have reached their sampling time. - nodesToAdd.clear(); - for (Node tip : unusedTips) { - if (tip.getTime() <= nextTime) { - nodesToAdd.add(tip); - tipsAdded = true; - - System.out.println("Time: " + tip.getTime() + " adding " + tip.getTaxon()); - - // reset the current time (the tips are sorted in time order - // so this will be the oldest added tip). - time = tip.getTime(); - } - } - nodes.addAll(nodesToAdd); - unusedTips.removeAll(nodesToAdd); - - if (!tipsAdded) { - time = nextTime; - } - - } while(tipsAdded); // only continue when no tips are added - - int r = MathUtils.nextInt(nodes.size()); - Node node = nodes.get(r); - - // create two new parent nodes - Node parent1 = new Node(node, time); - Node parent2 = new Node(node, time); - - // select a break point in interval [1, length - 2] on - // a zero-indexed line. - int breakPoint = MathUtils.nextInt(length - 2) + 1; - - // setup child node with parents and break point - node.setParent1(parent1); - node.setParent2(parent2); - node.setBreakPoint(breakPoint); - - System.out.println("Time: " + time + " recombining " + (node.getTaxon() != null ? node.getTaxon() : r) + " at breakpoint " + breakPoint); - - nodes.add(parent1); - nodes.add(parent2); - nodes.remove(node); - - } while (unusedTips.size() > 0); - - // Construct a taxon set for coalescent simulation of deep tree - Taxa treeTaxa = new Taxa(); - int i = 0; - - Map nodeMap = new HashMap(); - - for (Node node : nodes) { - Taxon taxon = new Taxon("Taxon" + i); - treeTaxa.addTaxon(taxon); - nodeMap.put(node, taxon); - i++; - } - - CoalescentSimulator coalSim = new CoalescentSimulator(); - ConstantPopulation demo = new ConstantPopulation(Units.Type.YEARS); - demo.setN0(ancestralPopulationSize); - - Tree tree = coalSim.simulateTree(treeTaxa, demo); - - System.out.println("Tree MRCA " + tree.getNodeHeight(tree.getRoot()) + time); - - SequenceSimulator seqSim = new SequenceSimulator(tree, siteModel, branchRateModel, length); - - Alignment ancestralAlignment = seqSim.simulate(); - - SimpleAlignment alignment = new SimpleAlignment(); - - // now construct the recombinant sequences from this alignment using the previously - // generated recombinant history - for (Node tip : tips) { - String seqString = generateRecombinant(tip, nodeMap, ancestralAlignment); - Sequence sequence = new Sequence(tip.getTaxon(), seqString); -// System.out.println(">" + tip.getTaxon() + "\r" + sequence); - - alignment.addSequence(sequence); - } - - return alignment; - } - - private String generateRecombinant(final Node node, final Map nodeMap, final Alignment alignment) { - String seq = node.getSequence(); - - if (seq == null) { - // if the sequence hasn't already been cached, then construct it... - if (node.getParent1() == null && node.getParent2() == null) { - // no parents so must have a sequence - Taxon taxon = nodeMap.get(node); - int index = alignment.getTaxonIndex(taxon); - Sequence sequence = alignment.getSequence(index); - seq = sequence.getSequenceString(); - } else { - String part1 = generateRecombinant(node.getParent1(), nodeMap, alignment); - String part2 = generateRecombinant(node.getParent2(), nodeMap, alignment); - - int breakPoint = node.getBreakPoint(); - - seq = part1.substring(0, breakPoint) + part2.substring(breakPoint); - } - - // cache the sequence - node.setSequence(seq); - } - - return seq; - } - - class Node implements Comparable{ - Node(final Taxon taxon) { - this.parent1 = null; - this.parent2 = null; - this.child = null; - this.breakPoint = -1; - this.taxon = taxon; - this.time = (Double)taxon.getAttribute("height"); - } - - Node(final Node child, final double time) { - this.child = child; - this.parent1 = null; - this.parent2 = null; - this.time = time; - this.breakPoint = -1; - this.taxon = null; - } - - public Node getParent1() { - return parent1; - } - - public Node getParent2() { - return parent2; - } - - public void setParent1(final Node parent1) { - this.parent1 = parent1; - } - - public void setParent2(final Node parent2) { - this.parent2 = parent2; - } - - public Node getChild() { - return child; - } - - public double getTime() { - return time; - } - - public int getBreakPoint() { - return breakPoint; - } - - public void setBreakPoint(final int breakPoint) { - this.breakPoint = breakPoint; - } - - public Taxon getTaxon() { - return taxon; - } - - public String getSequence() { - return sequence; - } - - public void setSequence(final String sequence) { - this.sequence = sequence; - } - - public int compareTo(final Node node) { - return Double.compare(time, node.time); - } - - private Node parent1; - private Node parent2; - private final Node child; - private final double time; - private int breakPoint; - private final Taxon taxon; - private String sequence = null; - } - - /* standard xml parser stuff follows */ - public static final String RECOMBINATION_SIMULATOR = "recombinationSimulator"; - public static final String SITE_MODEL = SiteModel.SITE_MODEL; - public static final String TAXA = "taxa"; -// public static final String BRANCH_RATE_MODEL = "branchRateModel"; - public static final String RECOMBINATION_RATE = "recombinationRate"; - public static final String SUBSTITUTION_RATE = "substitutionRate"; - public static final String ANCESTRAL_POPULATION_SIZE = "ancestralPopulationSize"; - public static final String SEQUENCE_LENGTH = "sequenceLength"; - - public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { - - public String getParserName() { - return RECOMBINATION_SIMULATOR; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - double recombinationRate = xo.getDoubleAttribute(RECOMBINATION_RATE); - double ancestralPopulationSize = xo.getDoubleAttribute(ANCESTRAL_POPULATION_SIZE); - int sequenceLength = xo.getIntegerAttribute(SEQUENCE_LENGTH); - - Taxa taxa = (Taxa) xo.getChild(Taxa.class); - SiteModel siteModel = (SiteModel) xo.getChild(SiteModel.class); - BranchRateModel rateModel = (BranchRateModel)xo.getChild(BranchRateModel.class); - - if (rateModel == null) { - rateModel = new DefaultBranchRateModel(); - } - - RecomboGen s = new RecomboGen( - recombinationRate, sequenceLength, - ancestralPopulationSize, siteModel, rateModel, taxa); - return s.generate(); - } - - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - - public String getParserDescription() { - return "A SequenceSimulator that generates random sequences for a given tree, siteratemodel and branch rate model"; - } - - public Class getReturnType() { - return Alignment.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{ - new ElementRule(Taxa.class), - new ElementRule(SiteModel.class), - new ElementRule(BranchRateModel.class, true), - AttributeRule.newDoubleRule(RECOMBINATION_RATE), - AttributeRule.newDoubleRule(ANCESTRAL_POPULATION_SIZE), - AttributeRule.newIntegerRule(SEQUENCE_LENGTH) - }; - }; - - public static void main(String[] argv) { - // Simulate sequences on this tree to generate sequences at the top of the - // recombination process. - Parameter kappa = new Parameter.Default(1, 2); - Parameter freqs = new Parameter.Default(new double[]{0.25, 0.25, 0.25, 0.25}); - FrequencyModel freqModel = new FrequencyModel(Nucleotides.INSTANCE, freqs); - HKY hky = new HKY(kappa, freqModel); - - // create site model - SiteModel siteModel = new GammaSiteModel(hky); - // create branch rate model - Parameter rate = new Parameter.Default(1, 1.0E-4); - BranchRateModel branchRateModel = new StrictClockBranchRates(rate); - -// RecomboGen recomboGen = new RecomboGen(8.0E-2, 100, 1000, 1.0E-4, -// new String[] { "taxon1_0", "taxon2_0", "taxon3_10", "taxon4_10", "taxon5_20", "taxon6_20"}, -// new double[] { 0, 0, 10, 10, 20, 20} ); -// -// recomboGen.generate(); - } - - private final double recombinationRate; - private final int length; - private final double ancestralPopulationSize; - private final SiteModel siteModel; - private final BranchRateModel branchRateModel; - private final Taxa taxa; -// private final String[] taxonNames; -// private final double[] samplingTimes; -} \ No newline at end of file diff --git a/src/dr/app/seqgen/SeqGen.java b/src/dr/app/seqgen/SeqGen.java deleted file mode 100644 index 8da23f35c2..0000000000 --- a/src/dr/app/seqgen/SeqGen.java +++ /dev/null @@ -1,324 +0,0 @@ -/* - * SeqGen.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.app.seqgen; - -import dr.evolution.io.Importer; -import dr.evolution.io.NewickImporter; -import dr.evolution.io.TreeImporter; -import dr.evolution.tree.NodeRef; -import dr.evolution.tree.Tree; -import dr.oldevomodel.sitemodel.GammaSiteModel; -import dr.oldevomodel.sitemodel.SiteModel; -import dr.oldevomodel.substmodel.FrequencyModel; -import dr.oldevomodel.substmodel.HKY; -import dr.oldevomodel.substmodel.SubstitutionModel; -import jebl.evolution.alignments.Alignment; -import jebl.evolution.alignments.BasicAlignment; -import jebl.evolution.io.FastaExporter; -import jebl.evolution.sequences.*; -import jebl.evolution.taxa.Taxon; -import jebl.math.Random; - -import java.io.*; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * @author Andrew Rambaut - */ -public class SeqGen { - - public SeqGen(final int length, final double substitutionRate, final FrequencyModel freqModel, final SubstitutionModel substModel, final SiteModel siteModel, final double damageRate) { - this.length = length; - this.substitutionRate = substitutionRate; - this.freqModel = freqModel; - this.substModel = substModel; - this.siteModel = siteModel; - this.damageRate = damageRate; - } - - public Alignment simulate(Tree tree) { - - int[] initialSequence = new int[length]; - - drawSequence(initialSequence, freqModel); - - int[] siteCategories = new int[length]; - - drawSiteCategories(siteModel, siteCategories); - - double[] rates = new double[siteModel.getCategoryCount()]; - for (int i = 0; i < rates.length; i++) { - rates[i] = siteModel.getRateForCategory(i) * substitutionRate; - } - - for (int i = 0; i < tree.getChildCount(tree.getRoot()); i++) { - NodeRef child = tree.getChild(tree.getRoot(), i); - evolveSequences(initialSequence, tree, child, substModel, siteCategories, rates); - } - - Map damageMap = new HashMap(); - damageMap.put(Nucleotides.A_STATE, new State[]{Nucleotides.G_STATE}); - damageMap.put(Nucleotides.C_STATE, new State[]{Nucleotides.T_STATE}); - damageMap.put(Nucleotides.G_STATE, new State[]{Nucleotides.A_STATE}); - damageMap.put(Nucleotides.T_STATE, new State[]{Nucleotides.C_STATE}); - - Sequence[] sequences = new Sequence[tree.getExternalNodeCount()]; - - List nucs = jebl.evolution.sequences.Nucleotides.getCanonicalStates(); - for (int i = 0; i < tree.getExternalNodeCount(); i++) { - NodeRef node = tree.getExternalNode(i); - int[] seq = (int[]) tree.getNodeTaxon(node).getAttribute("seq"); - State[] states = new State[seq.length]; - for (int j = 0; j < states.length; j++) { - states[j] = nucs.get(seq[j]); - } - - if (damageRate > 0) { - damageSequence(states, damageRate, tree.getNodeHeight(node), damageMap); - } - - sequences[i] = new BasicSequence(SequenceType.NUCLEOTIDE, - Taxon.getTaxon(tree.getNodeTaxon(node).getId()), - states); - } - - BasicAlignment alignment = new BasicAlignment(sequences); - - - return alignment; - } - - void drawSiteCategories(SiteModel siteModel, int[] siteCategories) { - double[] categoryProportions = siteModel.getCategoryProportions(); - double[] cumulativeProportions = new double[categoryProportions.length]; - cumulativeProportions[0] = categoryProportions[0]; - for (int i = 1; i < cumulativeProportions.length; i++) { - cumulativeProportions[i] = cumulativeProportions[i - 1] + categoryProportions[i]; - } - - for (int i = 0; i < siteCategories.length; i++) { - siteCategories[i] = draw(cumulativeProportions); - } - } - - public void drawSequence(int[] initialSequence, FrequencyModel freqModel) { - double[] freqs = freqModel.getCumulativeFrequencies(); - for (int i = 0; i < initialSequence.length; i++) { - initialSequence[i] = draw(freqs); - } - } - - void evolveSequences(int[] sequence0, - Tree tree, NodeRef node, - SubstitutionModel substModel, - int[] siteCategories, - double[] categoryRates) { - int stateCount = substModel.getDataType().getStateCount(); - - int[] sequence1 = new int[sequence0.length]; - - double[][][] transitionProbabilities = new double[siteCategories.length][stateCount][stateCount]; - - for (int i = 0; i < categoryRates.length; i++) { - double branchLength = tree.getBranchLength(node) * categoryRates[i]; - double[] tmp = new double[stateCount * stateCount]; - substModel.getTransitionProbabilities(branchLength, tmp); - - int l = 0; - for (int j = 0; j < stateCount; j++) { - transitionProbabilities[i][j][0] = tmp[l]; - l++; - for (int k = 1; k < stateCount; k++) { - transitionProbabilities[i][j][k] = transitionProbabilities[i][j][k - 1] + tmp[l]; - l++; - } - - } - } - - evolveSequence(sequence0, siteCategories, transitionProbabilities, sequence1); - - if (!tree.isExternal(node)) { - for (int i = 0; i < tree.getChildCount(node); i++) { - NodeRef child = tree.getChild(node, i); - evolveSequences(sequence1, tree, child, substModel, siteCategories, categoryRates); - } - } else { - tree.getNodeTaxon(node).setAttribute("seq", sequence1); - } - } - - private void evolveSequence(int[] ancestralSequence, - int[] siteCategories, - double[][][] cumulativeTransitionProbabilities, - int[] descendentSequence) { - - for (int i = 0; i < ancestralSequence.length; i++) { - descendentSequence[i] = draw(cumulativeTransitionProbabilities[siteCategories[i]][ancestralSequence[i]]); - } - } - - private void damageSequence(State[] sequence, double rate, double time, Map damageMap) { - double pUndamaged = Math.exp(-rate * time); - - for (int i = 0; i < sequence.length; i++) { - double r = Random.nextDouble(); - if (r >= pUndamaged) { - State[] states = damageMap.get(sequence[i]); - if (states.length > 0) { - int index = Random.nextInt(states.length); - sequence[i] = states[index]; - } else { - sequence[i] = states[0]; - } - } - } - } - - /** - * draws a state from using a set of cumulative frequencies (last value should be 1.0) - * - * @param cumulativeFrequencies - * @return - */ - private int draw(double[] cumulativeFrequencies) { - double r = Random.nextDouble(); - - // defensive - make sure that it is actually set... - int state = -1; - - for (int j = 0; j < cumulativeFrequencies.length; j++) { - if (r < cumulativeFrequencies[j]) { - state = j; - break; - } - } - - assert (state != -1); - - return state; - } - - final int length; - final double substitutionRate; - final FrequencyModel freqModel; - final SubstitutionModel substModel; - final SiteModel siteModel; - final double damageRate; - - public static void main(String[] argv) { - - String treeFileName = argv[0]; - String outputFileStem = argv[1]; - - int length = 500; - - double[] frequencies = new double[]{0.25, 0.25, 0.25, 0.25}; - double kappa = 10.0; - double alpha = 0.5; - double substitutionRate = argv.length < 3 ? 1.0E-3 : Double.parseDouble(argv[2]); - int categoryCount = argv.length < 4 ? 8 : Integer.parseInt(argv[3]); - double damageRate = argv.length < 5 ? 0 : Double.parseDouble(argv[4]); //1.56E-6; - - System.out.println("substitutionRate = " + substitutionRate + "; categoryCount = " + categoryCount + "; damageRate = " + damageRate); - - FrequencyModel freqModel = new FrequencyModel(dr.evolution.datatype.Nucleotides.INSTANCE, frequencies); - - HKY hkyModel = new HKY(kappa, freqModel); - SiteModel siteModel = null; - - if (categoryCount > 1) { - siteModel = new GammaSiteModel(hkyModel, alpha, categoryCount); - } else { - // no rate heterogeneity - siteModel = new GammaSiteModel(hkyModel); - } - - List trees = new ArrayList(); - - FileReader reader = null; - try { - reader = new FileReader(treeFileName); -// TreeImporter importer = new NexusImporter(reader); - TreeImporter importer = new NewickImporter(reader); - - while (importer.hasTree()) { - Tree tree = importer.importNextTree(); - trees.add(tree); - System.out.println("tree height = " + tree.getNodeHeight(tree.getRoot()) + "; leave nodes = " + tree.getExternalNodeCount()); - } - - } catch (FileNotFoundException e) { - e.printStackTrace(); - return; - } catch (Importer.ImportException e) { - e.printStackTrace(); - return; - } catch (IOException e) { - e.printStackTrace(); - return; - } - - SeqGen seqGen = new SeqGen(length, - substitutionRate, freqModel, hkyModel, siteModel, - damageRate); - int i = 1; - for (Tree tree : trees) { - Alignment alignment = seqGen.simulate(tree); - - FileWriter writer = null; - try { -// writer = new FileWriter(outputFileStem + (i < 10 ? "00" : (i < 100 ? "0" : "")) + i + ".nex"); -// NexusExporter exporter = new NexusExporter(writer); -// -// exporter.exportAlignment(alignment); -// -// writer.close(); - String outputFileName = outputFileStem + "-" + substitutionRate + ".fasta"; - - writer = new FileWriter(outputFileName); - BufferedWriter bf = new BufferedWriter(writer); - FastaExporter exporter = new FastaExporter(bf); - - exporter.exportSequences(alignment.getSequenceList()); - - bf.close(); - System.out.println("Write " + i + "th sequence file : " + outputFileName); - - i++; - } catch (IOException e) { - e.printStackTrace(); - return; - } - } - - } -} diff --git a/src/dr/app/seqgen/SequenceSimulator.java b/src/dr/app/seqgen/SequenceSimulator.java index 7fde4a45e5..37a20dd0c1 100644 --- a/src/dr/app/seqgen/SequenceSimulator.java +++ b/src/dr/app/seqgen/SequenceSimulator.java @@ -1,554 +1,554 @@ - -/* - * SequenceSimulator.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.app.seqgen; - -import dr.app.bss.Utils; -import dr.evolution.alignment.Alignment; -import dr.evolution.alignment.SimpleAlignment; -import dr.evolution.datatype.DataType; -import dr.evolution.datatype.Nucleotides; -import dr.evolution.io.NewickImporter; -import dr.evolution.sequence.Sequence; -import dr.evolution.tree.NodeRef; -import dr.evolution.tree.Tree; -import dr.evomodel.branchmodel.BranchModel; -import dr.evomodel.branchratemodel.BranchRateModel; -import dr.evomodel.branchratemodel.DefaultBranchRateModel; -import dr.evomodel.siteratemodel.GammaSiteRateModel; -import dr.evomodel.substmodel.SubstitutionModel; -import dr.oldevomodel.sitemodel.GammaSiteModel; -import dr.oldevomodel.sitemodel.SiteModel; -import dr.evomodel.siteratemodel.SiteRateModel; -import dr.oldevomodel.substmodel.FrequencyModel; -import dr.oldevomodel.substmodel.HKY; -import dr.oldevomodel.substmodel.SubstitutionEpochModel; -import dr.inference.model.Parameter; -import dr.math.MathUtils; -import dr.xml.*; - -/** Class for performing random sequence generation for a given site model. - * Sequences for the leave nodes in the tree are returned as an alignment. - * - * @author remco@cs.waikato.ac.nz - * - */ - -public class SequenceSimulator { - - private static final boolean DEBUG = false; - - /** nr of samples to generate **/ - protected int m_sequenceLength; - /** tree used for generating samples **/ - protected Tree m_tree; - /** site model used for generating samples **/ -// protected SiteModel m_siteModel; - /** branch rate model used for generating samples **/ - protected BranchRateModel m_branchRateModel; - /** nr of categories in site model **/ - int m_categoryCount; - /** nr of states in site model **/ - int m_stateCount; - - private SiteRateBranchModelProvider siteRateBranchModelProvider; - - static boolean has_ancestralSequence = false; - protected Sequence ancestralSequence; - - /** - * an array used to transfer transition probabilities - */ - protected double[][] m_probabilities; - - /** - * Constructor - * @param tree - * @param siteModel - * @param branchRateModel - * @param sequenceLength: nr of sites to generate - */ - SequenceSimulator(Tree tree, SiteModel siteModel, BranchRateModel branchRateModel, int sequenceLength) { - m_tree = tree; -// m_siteModel = siteModel; - m_branchRateModel = branchRateModel; - m_sequenceLength = sequenceLength; - siteRateBranchModelProvider = new SiteRateBranchModelProvider.OLD(siteModel); - m_stateCount = siteRateBranchModelProvider.getStateCount(); - m_categoryCount = siteRateBranchModelProvider.getCategoryCount(); - m_probabilities = new double[m_categoryCount][m_stateCount * m_stateCount]; - } // c'tor - - SequenceSimulator(Tree tree, SiteRateModel siteRateModel, BranchModel branchModel, BranchRateModel branchRateModel, int sequenceLength) { - m_tree = tree; - m_branchRateModel = branchRateModel; - m_sequenceLength = sequenceLength; - siteRateBranchModelProvider = new SiteRateBranchModelProvider.BranchSpecific(branchModel, siteRateModel); - m_stateCount = siteRateBranchModelProvider.getStateCount(); - m_categoryCount = siteRateBranchModelProvider.getCategoryCount(); - m_probabilities = new double[m_categoryCount][m_stateCount * m_stateCount]; - } - - /** - * Convert integer representation of sequence into a Sequence - * @param seq integer representation of the sequence - * @param node used to determine taxon for sequence - * @return Sequence - */ - Sequence intArray2Sequence(int [] seq, NodeRef node) { - StringBuilder sSeq = new StringBuilder(); - for (int i = 0; i < m_sequenceLength; i++) { - sSeq.append(siteRateBranchModelProvider.getDataType().getCode(seq[i])); - } - return new Sequence(m_tree.getNodeTaxon(node), sSeq.toString()); - } // intArray2Sequence - - void setAncestralSequence(Sequence seq) { - ancestralSequence = seq; - has_ancestralSequence = true; - } - - int[] sequence2intArray(Sequence seq) { - - if(seq.getLength() != m_sequenceLength) { - - throw new RuntimeException("Ancestral sequence length has " - + seq.getLength() + " characters " + "expecting " - + m_sequenceLength + " characters"); - - } - - int array[] = new int[m_sequenceLength]; - for (int i = 0; i < m_sequenceLength; i++) { - array[i] = siteRateBranchModelProvider.getDataType().getState( - seq.getChar(i)); - } - return array; - }//END: sequence2intArray - - /** - * perform the actual sequence generation - * @return alignment containing randomly generated sequences for the nodes in the - * leaves of the tree - */ - public Alignment simulate() { - NodeRef root = m_tree.getRoot(); - - double[] categoryProbs = siteRateBranchModelProvider.getCategoryProportions(); - int[] category = new int[m_sequenceLength]; - for (int i = 0; i < m_sequenceLength; i++) { - category[i] = MathUtils.randomChoicePDF(categoryProbs); - } - - int[] seq = new int[m_sequenceLength]; - - if (has_ancestralSequence) { - - seq = sequence2intArray(ancestralSequence); - - } else { - - double[] frequencies = siteRateBranchModelProvider.getFrequencies(); - for (int i = 0; i < m_sequenceLength; i++) { - seq[i] = MathUtils.randomChoicePDF(frequencies); - } - - } - - if (DEBUG) { - synchronized (this) { - System.out.println(); - System.out.println("root Sequence:"); - Utils.printArray(seq); - } - } - - SimpleAlignment alignment = new SimpleAlignment(); - alignment.setReportCountStatistics(false); - alignment.setDataType(siteRateBranchModelProvider.getDataType()); - - traverse(root, seq, category, alignment); - - return alignment; - } // END: simulate - - /** - * recursively walk through the tree top down, and add sequence to alignment whenever - * a leave node is reached. - * @param node reference to the current node, for which we visit all children - * @param parentSequence randomly generated sequence of the parent node - * @param category array of categories for each of the sites - * @param alignment - */ - void traverse(NodeRef node, int [] parentSequence, int [] category, SimpleAlignment alignment) { - - if (DEBUG) { - System.out.println(); - System.out.println("I'm at: " + node.toString()); - System.out.println(); - } - - for (int iChild = 0; iChild < m_tree.getChildCount(node); iChild++) { - - NodeRef child = m_tree.getChild(node, iChild); - - for (int i = 0; i < m_categoryCount; i++) { - final double branchRate = m_branchRateModel.getBranchRate(m_tree, child); - siteRateBranchModelProvider.getTransitionProbabilities(m_tree, child, i, branchRate, m_probabilities[i]); -// getTransitionProbabilities(m_tree, child, i, m_probabilities[i]); - } - - if (DEBUG) { - System.out.println("Going to child " + iChild + ": " + child.toString()); - System.out.println("Child finite transition probs matrix:"); - Utils.print2DArray(m_probabilities, 4); - System.out.println(); - }// END: if DEBUG - - int [] seq = new int[m_sequenceLength]; - double [] cProb = new double[m_stateCount]; - - for (int i = 0; i < m_sequenceLength; i++) { - - //System.out.println("seqChar " + parentSequence[i]); - - System.arraycopy(m_probabilities[category[i]], parentSequence[i] * m_stateCount, cProb, 0, m_stateCount); - - if (DEBUG) { - System.out.println("site:" + i); - System.out.println("site probs:"); - Utils.printArray(cProb); - }// END: if DEBUG - - seq[i] = MathUtils.randomChoicePDF(cProb); - - } - - if (DEBUG) { -// seq = new int[]{1, 3, 2, 3, 0, 1, 0, 1, 0, 2, 2, 0, 1, 3, 3, 3, 0, 1, 2, 1, 3, 1, 1, 1, 1, 3, 0, 0, 3, 2, 3, 2, 3, 2, 1, 2, 1, 3, 2, 3, 3, 0, 2, 2, 3, 2, 3, 2, 3, 1, 2, 0, 2, 1, 3, 2, 3, 1, 1, 1, 1, 0, 2, 3, 1, 0, 2, 1, 2, 1, 3, 0, 0, 0, 0, 0, 2, 0, 2, 3, 1, 0, 1, 3, 0, 2, 1, 2, 1, 3, 0, 0, 3, 2, 2, 0, 1, 0, 0, 3 }; - System.out.println("Simulated sequence:"); - Utils.printArray(seq); - } - - if (m_tree.getChildCount(child) == 0) { - - if (DEBUG) { - System.out.println("Simulated sequence (translated):"); - System.out.println(intArray2Sequence(seq, child).getSequenceString()); - } - - alignment.addSequence(intArray2Sequence(seq, child)); - } - - traverse(m_tree.getChild(node, iChild), seq, category, alignment); - }//END: child nodes loop - - } // traverse - -// void getTransitionProbabilities(Tree tree, NodeRef node, int rateCategory, double[] probs) { -// -// NodeRef parent = tree.getParent(node); -// -// final double branchRate = m_branchRateModel.getBranchRate(tree, node); -// -// // Get the operational time of the branch -// final double branchTime = branchRate * (tree.getNodeHeight(parent) - tree.getNodeHeight(node)); -// -// if (branchTime < 0.0) { -// throw new RuntimeException("Negative branch length: " + branchTime); -// } -// -// double branchLength = m_siteModel.getRateForCategory(rateCategory) * branchTime; -// -// if (m_siteModel.getSubstitutionModel() instanceof SubstitutionEpochModel) { -// ((SubstitutionEpochModel)m_siteModel.getSubstitutionModel()).getTransitionProbabilities(tree.getNodeHeight(node), -// tree.getNodeHeight(parent),branchLength, probs); -// return; -// } -// m_siteModel.getSubstitutionModel().getTransitionProbabilities(branchLength, probs); -// } // getTransitionProbabilities - - - private interface SiteRateBranchModelProvider { - int getStateCount(); - int getCategoryCount(); - DataType getDataType(); - double[] getCategoryProportions(); - double[] getFrequencies(); - double getRateForCategory(int category); - void getTransitionProbabilities(Tree tree, NodeRef node, int rateCategory, double branchRate, double[] probs); - - class OLD implements SiteRateBranchModelProvider { - - private SiteModel siteModel; - - OLD(SiteModel siteModel) { - this.siteModel = siteModel; - } - - @Override - public int getStateCount() { - return siteModel.getFrequencyModel().getDataType().getStateCount(); - } - - @Override - public int getCategoryCount() { - return siteModel.getCategoryCount(); - } - - @Override - public DataType getDataType() { - return siteModel.getFrequencyModel().getDataType(); - } - - @Override - public double[] getCategoryProportions() { - return siteModel.getCategoryProportions(); - } - - @Override - public double[] getFrequencies() { - return siteModel.getFrequencyModel().getFrequencies(); - } - - @Override - public double getRateForCategory(int category) { - return siteModel.getRateForCategory(category); - } - - @Override - public void getTransitionProbabilities(Tree tree, NodeRef node, int rateCategory, double branchRate, double[] probs) { - NodeRef parent = tree.getParent(node); - final double branchTime = tree.getNodeHeight(parent) - tree.getNodeHeight(node); - if (branchTime < 0.0) { - throw new RuntimeException("Negative branch length: " + branchTime); - } - - final double branchLength = getRateForCategory(rateCategory) * branchRate * branchTime; - if (siteModel.getSubstitutionModel() instanceof SubstitutionEpochModel) { - ((SubstitutionEpochModel)siteModel.getSubstitutionModel()).getTransitionProbabilities(tree.getNodeHeight(node), - tree.getNodeHeight(parent), branchLength, probs); - return; - } - siteModel.getSubstitutionModel().getTransitionProbabilities(branchLength, probs); - } - } - - class BranchSpecific implements SiteRateBranchModelProvider { - - private BranchModel branchModel; - private SiteRateModel siteRateModel; - - BranchSpecific(BranchModel branchModel, SiteRateModel siteRateModel) { - this.branchModel = branchModel; - this.siteRateModel = siteRateModel; - } - - @Override - public int getStateCount() { - return getDataType().getStateCount(); - } - - @Override - public int getCategoryCount() { - return siteRateModel.getCategoryCount(); - } - - @Override - public DataType getDataType() { - return branchModel.getRootFrequencyModel().getDataType(); - } - - @Override - public double[] getCategoryProportions() { - return siteRateModel.getCategoryProportions(); - } - - @Override - public double[] getFrequencies() { - return branchModel.getRootFrequencyModel().getFrequencies(); - } - - @Override - public double getRateForCategory(int category) { - return siteRateModel.getRateForCategory(category); - } - - @Override - public void getTransitionProbabilities(Tree tree, NodeRef node, int rateCategory, double branchRate, double[] probs) { - int[] substitutionModelIndices = branchModel.getBranchModelMapping(node).getOrder(); - if (substitutionModelIndices.length > 1) { - throw new RuntimeException("Not yet implemented"); - } - final double branchLength = getRateForCategory(rateCategory) * branchRate * (tree.getNodeHeight(tree.getParent(node)) - tree.getNodeHeight(node)); - branchModel.getSubstitutionModels().get(substitutionModelIndices[0]).getTransitionProbabilities(branchLength, probs); - } - } - } - - - - /** helper method **/ - public static void printUsageAndExit() { - System.err.println("Usage: java " + SequenceSimulator.class.getName() + " "); - System.err.println("where is the number of instantiations to be replciated"); - System.exit(0); - } // printUsageAndExit - - /* standard xml parser stuff follows */ - public static final String SEQUENCE_SIMULATOR = "sequenceSimulator"; - public static final String SITE_MODEL = SiteModel.SITE_MODEL; - public static final String TREE = "tree"; -// public static final String BRANCH_RATE_MODEL = "branchRateModel"; - public static final String REPLICATIONS = "replications"; - - public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { - - public String getParserName() { - return SEQUENCE_SIMULATOR; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - int nReplications = xo.getIntegerAttribute(REPLICATIONS); - - Tree tree = (Tree) xo.getChild(Tree.class); - SiteModel siteModel = (SiteModel) xo.getChild(SiteModel.class); - BranchRateModel rateModel = (BranchRateModel)xo.getChild(BranchRateModel.class); - Sequence ancestralSequence = (Sequence)xo.getChild(Sequence.class); - - if (rateModel == null) - rateModel = new DefaultBranchRateModel(); - - SequenceSimulator s; - if (siteModel == null) { - BranchModel branchModel = (BranchModel) xo.getChild(BranchModel.class); - SiteRateModel siteRateModel = (GammaSiteRateModel) xo.getChild(GammaSiteRateModel.class); - s = new SequenceSimulator(tree, siteRateModel, branchModel, rateModel, nReplications); - } else { - s = new SequenceSimulator(tree, siteModel, rateModel, nReplications); - } - - if(ancestralSequence != null) { - s.setAncestralSequence(ancestralSequence); - } - - return s.simulate(); - } - - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - - public String getParserDescription() { - return "A SequenceSimulator that generates random sequences for a given tree, siteratemodel and branch rate model"; - } - - public Class getReturnType() { - return Alignment.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{ - new ElementRule(Tree.class), - new XORRule(new ElementRule(SiteModel.class), - new AndRule(new ElementRule(GammaSiteRateModel.class), new ElementRule(BranchModel.class))), - new ElementRule(BranchRateModel.class, true), - new ElementRule(Sequence.class, true), - AttributeRule.newIntegerRule(REPLICATIONS) - }; - }; - - /** generate simple site model, for testing purposes **/ - static SiteModel getDefaultSiteModel() { - Parameter kappa = new Parameter.Default(1, 2); - Parameter freqs = new Parameter.Default(new double[]{0.25, 0.25, 0.25, 0.25}); - FrequencyModel f = new FrequencyModel(Nucleotides.INSTANCE, freqs); - HKY hky = new HKY(kappa, f); - return new GammaSiteModel(hky); - } // getDefaultSiteModel - - public static void main(String [] args) { - - try { - - int nReplications = 10; - - // create tree - NewickImporter importer = new NewickImporter("((A:1.0,B:1.0)AB:1.0,(C:1.0,D:1.0)CD:1.0)ABCD;"); - Tree tree = importer.importTree(null); - - // create site model - SiteModel siteModel = getDefaultSiteModel(); - - // create branch rate model - BranchRateModel branchRateModel = new DefaultBranchRateModel(); - - // feed to sequence simulator and generate leaves - SequenceSimulator treeSimulator = new SequenceSimulator(tree, siteModel, branchRateModel, nReplications); - - Sequence ancestralSequence = new Sequence(); - ancestralSequence.appendSequenceString("TCAGGTCAAG"); - treeSimulator.setAncestralSequence(ancestralSequence); - - System.out.println(treeSimulator.simulate().toString()); - - } catch (Exception e) { - e.printStackTrace(); - }//END: try-catch block - - } // END: main - -// public static void main(String [] args) { -// try { -// if (args.length == 0) { -// printUsageAndExit(); -// } -// int nReplications = Integer.parseInt(args[0]); -// -// // create tree -// NewickImporter importer = new NewickImporter("((A:1.0,B:1.0)AB:1.0,(C:1.0,D:1.0)CD:1.0)ABCD;"); -// Tree tree = importer.importTree(null); -// // create site model -// SiteModel siteModel = getDefaultSiteModel(); -// // create branch rate model -// BranchRateModel branchRateModel = new DefaultBranchRateModel(); -// -// // feed to sequence simulator and generate leaves -// SequenceSimulator treeSimulator = new SequenceSimulator(tree, siteModel, branchRateModel, nReplications); -// System.err.println(treeSimulator.simulate().toString()); -// treeSimulator.simulate(); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } // main - -} // class SequenceSimulator + +/* + * SequenceSimulator.java + * + * Copyright © 2002-2024 the BEAST Development Team + * http://beast.community/about + * + * This file is part of BEAST. + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership and licensing. + * + * BEAST is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * BEAST is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with BEAST; if not, write to the + * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, + * Boston, MA 02110-1301 USA + * + */ + +package dr.app.seqgen; + +import dr.app.bss.Utils; +import dr.evolution.alignment.Alignment; +import dr.evolution.alignment.SimpleAlignment; +import dr.evolution.datatype.DataType; +import dr.evolution.datatype.Nucleotides; +import dr.evolution.io.NewickImporter; +import dr.evolution.sequence.Sequence; +import dr.evolution.tree.NodeRef; +import dr.evolution.tree.Tree; +import dr.evomodel.branchmodel.BranchModel; +import dr.evomodel.branchratemodel.BranchRateModel; +import dr.evomodel.branchratemodel.DefaultBranchRateModel; +import dr.evomodel.siteratemodel.GammaSiteRateModel; +import dr.evomodel.substmodel.SubstitutionModel; +import dr.oldevomodel.sitemodel.GammaSiteModel; +import dr.oldevomodel.sitemodel.SiteModel; +import dr.evomodel.siteratemodel.SiteRateModel; +import dr.oldevomodel.substmodel.FrequencyModel; +import dr.oldevomodel.substmodel.HKY; +import dr.oldevomodel.substmodel.SubstitutionEpochModel; +import dr.inference.model.Parameter; +import dr.math.MathUtils; +import dr.xml.*; + +/** Class for performing random sequence generation for a given site model. + * Sequences for the leave nodes in the tree are returned as an alignment. + * + * @author remco@cs.waikato.ac.nz + * + */ + +public class SequenceSimulator { + + private static final boolean DEBUG = false; + + /** nr of samples to generate **/ + protected int m_sequenceLength; + /** tree used for generating samples **/ + protected Tree m_tree; + /** site model used for generating samples **/ +// protected SiteModel m_siteModel; + /** branch rate model used for generating samples **/ + protected BranchRateModel m_branchRateModel; + /** nr of categories in site model **/ + int m_categoryCount; + /** nr of states in site model **/ + int m_stateCount; + + private SiteRateBranchModelProvider siteRateBranchModelProvider; + + static boolean has_ancestralSequence = false; + protected Sequence ancestralSequence; + + /** + * an array used to transfer transition probabilities + */ + protected double[][] m_probabilities; + + /** + * Constructor + * @param tree + * @param siteModel + * @param branchRateModel + * @param sequenceLength: nr of sites to generate + */ + SequenceSimulator(Tree tree, SiteModel siteModel, BranchRateModel branchRateModel, int sequenceLength) { + m_tree = tree; +// m_siteModel = siteModel; + m_branchRateModel = branchRateModel; + m_sequenceLength = sequenceLength; + siteRateBranchModelProvider = new SiteRateBranchModelProvider.OLD(siteModel); + m_stateCount = siteRateBranchModelProvider.getStateCount(); + m_categoryCount = siteRateBranchModelProvider.getCategoryCount(); + m_probabilities = new double[m_categoryCount][m_stateCount * m_stateCount]; + } // c'tor + + SequenceSimulator(Tree tree, SiteRateModel siteRateModel, BranchModel branchModel, BranchRateModel branchRateModel, int sequenceLength) { + m_tree = tree; + m_branchRateModel = branchRateModel; + m_sequenceLength = sequenceLength; + siteRateBranchModelProvider = new SiteRateBranchModelProvider.BranchSpecific(branchModel, siteRateModel); + m_stateCount = siteRateBranchModelProvider.getStateCount(); + m_categoryCount = siteRateBranchModelProvider.getCategoryCount(); + m_probabilities = new double[m_categoryCount][m_stateCount * m_stateCount]; + } + + /** + * Convert integer representation of sequence into a Sequence + * @param seq integer representation of the sequence + * @param node used to determine taxon for sequence + * @return Sequence + */ + Sequence intArray2Sequence(int [] seq, NodeRef node) { + StringBuilder sSeq = new StringBuilder(); + for (int i = 0; i < m_sequenceLength; i++) { + sSeq.append(siteRateBranchModelProvider.getDataType().getCode(seq[i])); + } + return new Sequence(m_tree.getNodeTaxon(node), sSeq.toString()); + } // intArray2Sequence + + void setAncestralSequence(Sequence seq) { + ancestralSequence = seq; + has_ancestralSequence = true; + } + + int[] sequence2intArray(Sequence seq) { + + if(seq.getLength() != m_sequenceLength) { + + throw new RuntimeException("Ancestral sequence length has " + + seq.getLength() + " characters " + "expecting " + + m_sequenceLength + " characters"); + + } + + int array[] = new int[m_sequenceLength]; + for (int i = 0; i < m_sequenceLength; i++) { + array[i] = siteRateBranchModelProvider.getDataType().getState( + seq.getChar(i)); + } + return array; + }//END: sequence2intArray + + /** + * perform the actual sequence generation + * @return alignment containing randomly generated sequences for the nodes in the + * leaves of the tree + */ + public Alignment simulate() { + NodeRef root = m_tree.getRoot(); + + double[] categoryProbs = siteRateBranchModelProvider.getCategoryProportions(); + int[] category = new int[m_sequenceLength]; + for (int i = 0; i < m_sequenceLength; i++) { + category[i] = MathUtils.randomChoicePDF(categoryProbs); + } + + int[] seq = new int[m_sequenceLength]; + + if (has_ancestralSequence) { + + seq = sequence2intArray(ancestralSequence); + + } else { + + double[] frequencies = siteRateBranchModelProvider.getFrequencies(); + for (int i = 0; i < m_sequenceLength; i++) { + seq[i] = MathUtils.randomChoicePDF(frequencies); + } + + } + + if (DEBUG) { + synchronized (this) { + System.out.println(); + System.out.println("root Sequence:"); + Utils.printArray(seq); + } + } + + SimpleAlignment alignment = new SimpleAlignment(); + alignment.setReportCountStatistics(false); + alignment.setDataType(siteRateBranchModelProvider.getDataType()); + + traverse(root, seq, category, alignment); + + return alignment; + } // END: simulate + + /** + * recursively walk through the tree top down, and add sequence to alignment whenever + * a leave node is reached. + * @param node reference to the current node, for which we visit all children + * @param parentSequence randomly generated sequence of the parent node + * @param category array of categories for each of the sites + * @param alignment + */ + void traverse(NodeRef node, int [] parentSequence, int [] category, SimpleAlignment alignment) { + + if (DEBUG) { + System.out.println(); + System.out.println("I'm at: " + node.toString()); + System.out.println(); + } + + for (int iChild = 0; iChild < m_tree.getChildCount(node); iChild++) { + + NodeRef child = m_tree.getChild(node, iChild); + + for (int i = 0; i < m_categoryCount; i++) { + final double branchRate = m_branchRateModel.getBranchRate(m_tree, child); + siteRateBranchModelProvider.getTransitionProbabilities(m_tree, child, i, branchRate, m_probabilities[i]); +// getTransitionProbabilities(m_tree, child, i, m_probabilities[i]); + } + + if (DEBUG) { + System.out.println("Going to child " + iChild + ": " + child.toString()); + System.out.println("Child finite transition probs matrix:"); + Utils.print2DArray(m_probabilities, 4); + System.out.println(); + }// END: if DEBUG + + int [] seq = new int[m_sequenceLength]; + double [] cProb = new double[m_stateCount]; + + for (int i = 0; i < m_sequenceLength; i++) { + + //System.out.println("seqChar " + parentSequence[i]); + + System.arraycopy(m_probabilities[category[i]], parentSequence[i] * m_stateCount, cProb, 0, m_stateCount); + + if (DEBUG) { + System.out.println("site:" + i); + System.out.println("site probs:"); + Utils.printArray(cProb); + }// END: if DEBUG + + seq[i] = MathUtils.randomChoicePDF(cProb); + + } + + if (DEBUG) { +// seq = new int[]{1, 3, 2, 3, 0, 1, 0, 1, 0, 2, 2, 0, 1, 3, 3, 3, 0, 1, 2, 1, 3, 1, 1, 1, 1, 3, 0, 0, 3, 2, 3, 2, 3, 2, 1, 2, 1, 3, 2, 3, 3, 0, 2, 2, 3, 2, 3, 2, 3, 1, 2, 0, 2, 1, 3, 2, 3, 1, 1, 1, 1, 0, 2, 3, 1, 0, 2, 1, 2, 1, 3, 0, 0, 0, 0, 0, 2, 0, 2, 3, 1, 0, 1, 3, 0, 2, 1, 2, 1, 3, 0, 0, 3, 2, 2, 0, 1, 0, 0, 3 }; + System.out.println("Simulated sequence:"); + Utils.printArray(seq); + } + + if (m_tree.getChildCount(child) == 0) { + + if (DEBUG) { + System.out.println("Simulated sequence (translated):"); + System.out.println(intArray2Sequence(seq, child).getSequenceString()); + } + + alignment.addSequence(intArray2Sequence(seq, child)); + } + + traverse(m_tree.getChild(node, iChild), seq, category, alignment); + }//END: child nodes loop + + } // traverse + +// void getTransitionProbabilities(Tree tree, NodeRef node, int rateCategory, double[] probs) { +// +// NodeRef parent = tree.getParent(node); +// +// final double branchRate = m_branchRateModel.getBranchRate(tree, node); +// +// // Get the operational time of the branch +// final double branchTime = branchRate * (tree.getNodeHeight(parent) - tree.getNodeHeight(node)); +// +// if (branchTime < 0.0) { +// throw new RuntimeException("Negative branch length: " + branchTime); +// } +// +// double branchLength = m_siteModel.getRateForCategory(rateCategory) * branchTime; +// +// if (m_siteModel.getSubstitutionModel() instanceof SubstitutionEpochModel) { +// ((SubstitutionEpochModel)m_siteModel.getSubstitutionModel()).getTransitionProbabilities(tree.getNodeHeight(node), +// tree.getNodeHeight(parent),branchLength, probs); +// return; +// } +// m_siteModel.getSubstitutionModel().getTransitionProbabilities(branchLength, probs); +// } // getTransitionProbabilities + + + private interface SiteRateBranchModelProvider { + int getStateCount(); + int getCategoryCount(); + DataType getDataType(); + double[] getCategoryProportions(); + double[] getFrequencies(); + double getRateForCategory(int category); + void getTransitionProbabilities(Tree tree, NodeRef node, int rateCategory, double branchRate, double[] probs); + + class OLD implements SiteRateBranchModelProvider { + + private SiteModel siteModel; + + OLD(SiteModel siteModel) { + this.siteModel = siteModel; + } + + @Override + public int getStateCount() { + return siteModel.getFrequencyModel().getDataType().getStateCount(); + } + + @Override + public int getCategoryCount() { + return siteModel.getCategoryCount(); + } + + @Override + public DataType getDataType() { + return siteModel.getFrequencyModel().getDataType(); + } + + @Override + public double[] getCategoryProportions() { + return siteModel.getCategoryProportions(); + } + + @Override + public double[] getFrequencies() { + return siteModel.getFrequencyModel().getFrequencies(); + } + + @Override + public double getRateForCategory(int category) { + return siteModel.getRateForCategory(category); + } + + @Override + public void getTransitionProbabilities(Tree tree, NodeRef node, int rateCategory, double branchRate, double[] probs) { + NodeRef parent = tree.getParent(node); + final double branchTime = tree.getNodeHeight(parent) - tree.getNodeHeight(node); + if (branchTime < 0.0) { + throw new RuntimeException("Negative branch length: " + branchTime); + } + + final double branchLength = getRateForCategory(rateCategory) * branchRate * branchTime; + if (siteModel.getSubstitutionModel() instanceof SubstitutionEpochModel) { + ((SubstitutionEpochModel)siteModel.getSubstitutionModel()).getTransitionProbabilities(tree.getNodeHeight(node), + tree.getNodeHeight(parent), branchLength, probs); + return; + } + siteModel.getSubstitutionModel().getTransitionProbabilities(branchLength, probs); + } + } + + class BranchSpecific implements SiteRateBranchModelProvider { + + private BranchModel branchModel; + private SiteRateModel siteRateModel; + + BranchSpecific(BranchModel branchModel, SiteRateModel siteRateModel) { + this.branchModel = branchModel; + this.siteRateModel = siteRateModel; + } + + @Override + public int getStateCount() { + return getDataType().getStateCount(); + } + + @Override + public int getCategoryCount() { + return siteRateModel.getCategoryCount(); + } + + @Override + public DataType getDataType() { + return branchModel.getRootFrequencyModel().getDataType(); + } + + @Override + public double[] getCategoryProportions() { + return siteRateModel.getCategoryProportions(); + } + + @Override + public double[] getFrequencies() { + return branchModel.getRootFrequencyModel().getFrequencies(); + } + + @Override + public double getRateForCategory(int category) { + return siteRateModel.getRateForCategory(category); + } + + @Override + public void getTransitionProbabilities(Tree tree, NodeRef node, int rateCategory, double branchRate, double[] probs) { + int[] substitutionModelIndices = branchModel.getBranchModelMapping(node).getOrder(); + if (substitutionModelIndices.length > 1) { + throw new RuntimeException("Not yet implemented"); + } + final double branchLength = getRateForCategory(rateCategory) * branchRate * (tree.getNodeHeight(tree.getParent(node)) - tree.getNodeHeight(node)); + branchModel.getSubstitutionModels().get(substitutionModelIndices[0]).getTransitionProbabilities(branchLength, probs); + } + } + } + + + + /** helper method **/ + public static void printUsageAndExit() { + System.err.println("Usage: java " + SequenceSimulator.class.getName() + " "); + System.err.println("where is the number of instantiations to be replciated"); + System.exit(0); + } // printUsageAndExit + + /* standard xml parser stuff follows */ + public static final String SEQUENCE_SIMULATOR = "sequenceSimulator"; + public static final String SITE_MODEL = SiteModel.SITE_MODEL; + public static final String TREE = "tree"; +// public static final String BRANCH_RATE_MODEL = "branchRateModel"; + public static final String REPLICATIONS = "replications"; + + public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { + + public String getParserName() { + return SEQUENCE_SIMULATOR; + } + + public Object parseXMLObject(XMLObject xo) throws XMLParseException { + + int nReplications = xo.getIntegerAttribute(REPLICATIONS); + + Tree tree = (Tree) xo.getChild(Tree.class); + SiteModel siteModel = (SiteModel) xo.getChild(SiteModel.class); + BranchRateModel rateModel = (BranchRateModel)xo.getChild(BranchRateModel.class); + Sequence ancestralSequence = (Sequence)xo.getChild(Sequence.class); + + if (rateModel == null) + rateModel = new DefaultBranchRateModel(); + + SequenceSimulator s; + if (siteModel == null) { + BranchModel branchModel = (BranchModel) xo.getChild(BranchModel.class); + SiteRateModel siteRateModel = (GammaSiteRateModel) xo.getChild(GammaSiteRateModel.class); + s = new SequenceSimulator(tree, siteRateModel, branchModel, rateModel, nReplications); + } else { + s = new SequenceSimulator(tree, siteModel, rateModel, nReplications); + } + + if(ancestralSequence != null) { + s.setAncestralSequence(ancestralSequence); + } + + return s.simulate(); + } + + //************************************************************************ + // AbstractXMLObjectParser implementation + //************************************************************************ + + public String getParserDescription() { + return "A SequenceSimulator that generates random sequences for a given tree, siteratemodel and branch rate model"; + } + + public Class getReturnType() { + return Alignment.class; + } + + public XMLSyntaxRule[] getSyntaxRules() { + return rules; + } + + private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{ + new ElementRule(Tree.class), + new XORRule(new ElementRule(SiteModel.class), + new AndRule(new ElementRule(GammaSiteRateModel.class), new ElementRule(BranchModel.class))), + new ElementRule(BranchRateModel.class, true), + new ElementRule(Sequence.class, true), + AttributeRule.newIntegerRule(REPLICATIONS) + }; + }; + + /** generate simple site model, for testing purposes **/ + static SiteModel getDefaultSiteModel() { + Parameter kappa = new Parameter.Default(1, 2); + Parameter freqs = new Parameter.Default(new double[]{0.25, 0.25, 0.25, 0.25}); + FrequencyModel f = new FrequencyModel(Nucleotides.INSTANCE, freqs); + HKY hky = new HKY(kappa, f); + return new GammaSiteModel(hky); + } // getDefaultSiteModel + + public static void main(String [] args) { + + try { + + int nReplications = 10; + + // create tree + NewickImporter importer = new NewickImporter("((A:1.0,B:1.0)AB:1.0,(C:1.0,D:1.0)CD:1.0)ABCD;"); + Tree tree = importer.importTree(null); + + // create site model + SiteModel siteModel = getDefaultSiteModel(); + + // create branch rate model + BranchRateModel branchRateModel = new DefaultBranchRateModel(); + + // feed to sequence simulator and generate leaves + SequenceSimulator treeSimulator = new SequenceSimulator(tree, siteModel, branchRateModel, nReplications); + + Sequence ancestralSequence = new Sequence(); + ancestralSequence.appendSequenceString("TCAGGTCAAG"); + treeSimulator.setAncestralSequence(ancestralSequence); + + System.out.println(treeSimulator.simulate().toString()); + + } catch (Exception e) { + e.printStackTrace(); + }//END: try-catch block + + } // END: main + +// public static void main(String [] args) { +// try { +// if (args.length == 0) { +// printUsageAndExit(); +// } +// int nReplications = Integer.parseInt(args[0]); +// +// // create tree +// NewickImporter importer = new NewickImporter("((A:1.0,B:1.0)AB:1.0,(C:1.0,D:1.0)CD:1.0)ABCD;"); +// Tree tree = importer.importTree(null); +// // create site model +// SiteModel siteModel = getDefaultSiteModel(); +// // create branch rate model +// BranchRateModel branchRateModel = new DefaultBranchRateModel(); +// +// // feed to sequence simulator and generate leaves +// SequenceSimulator treeSimulator = new SequenceSimulator(tree, siteModel, branchRateModel, nReplications); +// System.err.println(treeSimulator.simulate().toString()); +// treeSimulator.simulate(); +// } catch (Exception e) { +// e.printStackTrace(); +// } +// } // main + +} // class SequenceSimulator diff --git a/src/dr/app/tools/AncestralSequenceAnnotator.java b/src/dr/app/tools/AncestralSequenceAnnotator.java index e313827358..42089fe5b5 100644 --- a/src/dr/app/tools/AncestralSequenceAnnotator.java +++ b/src/dr/app/tools/AncestralSequenceAnnotator.java @@ -47,8 +47,6 @@ import dr.evolution.alignment.ConvertAlignment; import dr.evolution.alignment.PatternList; import dr.evolution.alignment.SimpleAlignment; -//import dr.evolution.datatype.AminoAcids; -//import dr.evolution.datatype.GeneralDataType; import dr.evolution.datatype.*; import dr.evolution.io.*; import dr.evolution.sequence.Sequence; @@ -59,7 +57,6 @@ import dr.evomodel.branchratemodel.StrictClockBranchRates; import dr.evomodel.substmodel.SubstitutionModel; import dr.evomodel.tree.TreeModel; -import dr.oldevomodelxml.substmodel.GeneralSubstitutionModelParser; import dr.inference.model.Parameter; import dr.stats.DiscreteStatistics; import dr.util.HeapSort; @@ -74,6 +71,8 @@ import java.util.*; import java.util.logging.Logger; +import static dr.evomodelxml.substmodel.GeneralSubstitutionModelParser.GENERAL_SUBSTITUTION_MODEL; + /* * @author Marc A. Suchard * @author Wai Lok Sibon Li @@ -463,7 +462,7 @@ protected void modelSpecifics(Tree tree, String modelType) { } System.out.println("Number of site transition rate categories (debuggin): " + rates.length); //substModel = new GeneralSubstitutionModel(freqModel.getDataType(), freqModel, new Parameter.Default(rates), 1); - substModel = new GeneralSubstitutionModel(GeneralSubstitutionModelParser.GENERAL_SUBSTITUTION_MODEL, freqModel.getDataType(), freqModel, new Parameter.Default(rates), 1, null); + substModel = new GeneralSubstitutionModel(GENERAL_SUBSTITUTION_MODEL, freqModel.getDataType(), freqModel, new Parameter.Default(rates), 1, null); } } public DataType getDataType() { diff --git a/src/dr/app/tools/SpeciesDelimitationAnalyser.java b/src/dr/app/tools/SpeciesDelimitationAnalyser.java index 01667ccb0d..a681ef5699 100644 --- a/src/dr/app/tools/SpeciesDelimitationAnalyser.java +++ b/src/dr/app/tools/SpeciesDelimitationAnalyser.java @@ -1,385 +1,385 @@ -/* - * SpeciesDelimitationAnalyser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.app.tools; - -import dr.app.beast.BeastVersion; -import dr.app.util.Arguments; -import dr.evolution.io.Importer; -import dr.evolution.io.NexusImporter; -import dr.evolution.tree.NodeRef; -import dr.evolution.tree.Tree; -import dr.evolution.util.TaxonList; -import dr.evomodel.alloppnet.speciation.BirthDeathCollapseModel; -import dr.util.Version; - -import java.io.*; -import java.util.*; - -/** - * @author Graham Jones - * Date: 01/09/2013 - */ -public class SpeciesDelimitationAnalyser { - - private final static Version version = new BeastVersion(); - private ArrayList clusters; - private TaxonList taxonList; - - private int burnin; - double collapseheight; - private double similaritycutoff; - private String inputFileName; - private String outputFileName; - - private class Cluster { - private int count; - private int [] partition; - private double totalsimilarity; - private boolean deleted; - - public Cluster(TaxonList taxonList, Tree tree, double collapseheight) { - int nshort = 0; - count = 1; - partition = new int[taxonList.getTaxonCount()]; - totalsimilarity = 1.0; - deleted = false; - - int nnodes = tree.getNodeCount(); - for (int n = 0; n < nnodes; n++) { - NodeRef nr = tree.getNode(n); - boolean collapse; - if (tree.isRoot(nr)) { - collapse = BirthDeathCollapseModel.belowCollapseHeight(tree.getNodeHeight(nr), collapseheight); - } else { - NodeRef anc = tree.getParent(nr); - collapse = (BirthDeathCollapseModel.belowCollapseHeight(tree.getNodeHeight(nr), collapseheight) - && !BirthDeathCollapseModel.belowCollapseHeight(tree.getNodeHeight(anc), collapseheight)); - } - if (collapse) { - nshort++; - nodeToClade(taxonList, tree, nr, nshort); - } - } - } - - - double distance(Cluster sd) { - double d = 0.0; - for (int i = 0; i < partition.length; i++) { - for (int j = 0; j < i; j ++) { - boolean pair = partition[i] == partition[j]; - boolean sdpair = sd.partition[i] == sd.partition[j]; - if (pair != sdpair) { - d += 1.0; - } - } - } - return d / (partition.length * (partition.length-1.0) / 2.0); - } - - - double similarity(Cluster sd) { - return 1.0 - distance(sd); - } - - - - private void nodeToClade(TaxonList taxonlist, Tree tree, NodeRef nr, int idx) { - if (tree.isExternal(nr)) { - String id = tree.getNodeTaxon(nr).getId(); - int i = taxonIdToInt(taxonlist, id); - partition[i] = idx; - } else { - assert 2 == tree.getChildCount(nr); - nodeToClade(taxonlist, tree, tree.getChild(nr, 0), idx); - nodeToClade(taxonlist, tree, tree.getChild(nr, 1), idx); - } - } - - int taxonIdToInt(TaxonList taxonList, String id) { - int j = -1; - for (int i = 0; i < taxonList.getTaxonCount(); i++) { - String tid = taxonList.getTaxonId(i); - if (id.compareTo(tid) == 0) { - assert j < 0; - j = i; - } - } - assert j >= 0; - return j; - } - } - - - SpeciesDelimitationAnalyser(int burnin, double collapseheight, double similaritycutoff, String inputFileName, String outputFileName) { - this.burnin = burnin; - this.collapseheight = collapseheight; - this.similaritycutoff = similaritycutoff; - this.inputFileName = inputFileName; - this.outputFileName = outputFileName; - } - - void readtrees() throws IOException { - clusters = new ArrayList(0); - int totalTrees; - FileReader fileReader = new FileReader(inputFileName); - NexusImporter importer = new NexusImporter(fileReader); - System.out.println("Reading trees..."); - try { - taxonList = importer.parseTaxaBlock(); - totalTrees = 0; - while (importer.hasTree()) { - Tree tree = importer.importNextTree(); - - if (totalTrees >= burnin) { - Cluster sd = new Cluster(taxonList, tree, collapseheight); - clusters.add(sd); - } - - if (totalTrees > 0 && (totalTrees % 100 == 0)) { - System.out.print("*"); - System.out.flush(); - } - if (totalTrees > 0 && (totalTrees % 5000 == 0)) { - System.out.println(" " + totalTrees); - System.out.flush(); - } - totalTrees++; - } - System.out.println(""); - } catch (Importer.ImportException e) { - System.err.println("Error Parsing Input Tree: " + e.getMessage()); - return; - } - fileReader.close(); - if (totalTrees < 1) { - System.err.println("No trees"); - return; - } - System.out.println("Total trees read: " + totalTrees); - } - - - - void countclusterings() { - if (burnin > 0) { - System.out.println("Ignoring first " + burnin + " trees."); - } - System.out.println("Counting clusterings... "); - for (int i = 0; i < clusters.size(); i++) { - if (i > 0 && (i % 100 == 0)) { - System.out.print("*"); - System.out.flush(); - } - if (i > 0 && (i % 5000 == 0)) { - System.out.println(" " + i); - System.out.flush(); - } - - for (int j = i+1; j < clusters.size(); j++) { - if (clusters.get(j).count > 0) { - double simij = clusters.get(i).similarity(clusters.get(j)); - if (simij == 1.0) { - clusters.get(i).count += 1; - clusters.get(j).count = 0; - clusters.get(j).deleted = true; - } - if (simij >= similaritycutoff || simij == 1.0) { - clusters.get(i).totalsimilarity += simij; - } - } - } - } - Collections.sort(clusters, CLUSTER_COMPARATOR); - } - - - - void writeresults() throws IOException { - FileWriter fileWriter = new FileWriter(outputFileName); - - fileWriter.write("count fraction similarity nclusters "); - for (int i = 0; i < taxonList.getTaxonCount(); i++) { - String tstr = taxonList.getTaxonId(i); - while (tstr.length() < 4) tstr += " "; - fileWriter.write(tstr + " "); - } - fileWriter.write("\n"); - for (int i = 0; i < clusters.size(); i++) { - Cluster sd = clusters.get(i); - if (sd.count > 0) { - String countstr = "" + sd.count; - while (countstr.length() < 10) countstr += " "; - String fracstr = "" + (double)sd.count / (double) clusters.size(); - while (fracstr.length() < 22) fracstr += " "; - String simstr = "" + sd.totalsimilarity; - while (simstr.length() < 22) simstr += " "; - int clustercount = 0; - for (int j = 0; j < sd.partition.length; j ++) { - if (sd.partition[j] > clustercount) { - clustercount = sd.partition[j]; - } - } - String ccstr = "" + clustercount; - while (ccstr.length() < 10) ccstr += " "; - fileWriter.write(countstr + " " + fracstr + " " + simstr + " " + ccstr + " "); - for (int j = 0; j < sd.partition.length; j ++) { - String pjstr = "" + sd.partition[j]; - while (pjstr.length() < 4) { pjstr += " "; } - fileWriter.write(pjstr + " "); - } - fileWriter.write("\n"); - } - } - fileWriter.write("\n"); - fileWriter.close(); - - } - - - - public static void printTitle() { - System.out.println(); - centreLine("SpeciesDelimitationAnalyser " + version.getVersionString() + ", " + version.getDateString(), 60); - centreLine("Finds clusterings of individuals into clusters", 60); - centreLine("(ie possible species) from MCMC tree samples", 60); - centreLine("by", 60); - centreLine("Graham Jones", 60); - centreLine("www.indriid.com", 60); - System.out.println(); - System.out.println(); - } - - - - public static void centreLine(String line, int pageWidth) { - int n = pageWidth - line.length(); - int n1 = n / 2; - for (int i = 0; i < n1; i++) { - System.out.print(" "); - } - System.out.println(line); - } - - - public static void printUsage(Arguments arguments) { - - arguments.printUsage("SpeciesDelimitationAnalyser", " "); - System.out.println(); - System.out.println(" Example: SpeciesDelimitationAnalyser treesamples.txt out.txt"); - System.out.println(); - } - - - static final Comparator CLUSTER_COMPARATOR = new Comparator() { - public int compare(Cluster a, Cluster b) { - if (a.deleted != b.deleted) { - return a.deleted ? 1 : -1; - } - if (b.totalsimilarity != a.totalsimilarity) { - return (b.totalsimilarity > a.totalsimilarity) ? 1 : -1; - } - return 0; - } - }; - - - - - public static void main(String[] args) throws java.io.IOException { - - Locale.setDefault(Locale.US); - - printTitle(); - - Arguments arguments = new Arguments( - new Arguments.Option[]{ - new Arguments.IntegerOption("burnin", "b", "the number of states to be considered as 'burn-in' [default = none]"), - new Arguments.RealOption("collapseheight", "c", "the height below which nodes get collapsed [default = .001]"), - new Arguments.RealOption("simcutoff", "s", "the value above which two clusters are regarded as similar enough to support one another's credibility [default = .9]"), - new Arguments.Option("help", "h", "option to print this message") - }); - - try { - arguments.parseArguments(args); - } catch (Arguments.ArgumentException ae) { - System.out.println(ae); - printUsage(arguments); - System.exit(1); - } - - if (arguments.hasOption("help")) { - printUsage(arguments); - System.exit(0); - } - - int burnin = -1; - if (arguments.hasOption("burnin")) { - burnin = arguments.getIntegerOption("burnin"); - } - System.out.println(); - - double collapseheight = 0.001; - if (arguments.hasOption("collapseheight")) { - collapseheight = arguments.getRealOption("collapseheight"); - } - - double similaritycutoff = 0.9; - if (arguments.hasOption("simcutoff")) { - similaritycutoff = arguments.getRealOption("simcutoff"); - } - - System.out.println("burnin " + burnin + " collapseheight " + collapseheight + " simcutoff "+ similaritycutoff); - - String[] args2 = arguments.getLeftoverArguments(); - if (args2.length > 2) { - System.err.println("Unknown option: " + args2[2]); - System.err.println(); - printUsage(arguments); - System.exit(1); - } - if (args2.length < 2) { - System.err.println("Input filename and outputfilename required"); - System.err.println(); - printUsage(arguments); - System.exit(1); - } - - String inputFileName = args2[0]; - String outputFileName = args2[1]; - - SpeciesDelimitationAnalyser spDA = - new SpeciesDelimitationAnalyser(burnin, collapseheight, similaritycutoff, inputFileName, outputFileName); - spDA.readtrees(); - spDA.countclusterings(); - spDA.writeresults(); - - System.exit(0); - - } -} +/* + * SpeciesDelimitationAnalyser.java + * + * Copyright © 2002-2024 the BEAST Development Team + * http://beast.community/about + * + * This file is part of BEAST. + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership and licensing. + * + * BEAST is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * BEAST is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with BEAST; if not, write to the + * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, + * Boston, MA 02110-1301 USA + * + */ + +package dr.app.tools; + +import dr.app.beast.BeastVersion; +import dr.app.util.Arguments; +import dr.evolution.io.Importer; +import dr.evolution.io.NexusImporter; +import dr.evolution.tree.NodeRef; +import dr.evolution.tree.Tree; +import dr.evolution.util.TaxonList; +import dr.evomodel.alloppnet.speciation.BirthDeathCollapseModel; +import dr.util.Version; + +import java.io.*; +import java.util.*; + +/** + * @author Graham Jones + * Date: 01/09/2013 + */ +public class SpeciesDelimitationAnalyser { + + private final static Version version = new BeastVersion(); + private ArrayList clusters; + private TaxonList taxonList; + + private int burnin; + double collapseheight; + private double similaritycutoff; + private String inputFileName; + private String outputFileName; + + private class Cluster { + private int count; + private int [] partition; + private double totalsimilarity; + private boolean deleted; + + public Cluster(TaxonList taxonList, Tree tree, double collapseheight) { + int nshort = 0; + count = 1; + partition = new int[taxonList.getTaxonCount()]; + totalsimilarity = 1.0; + deleted = false; + + int nnodes = tree.getNodeCount(); + for (int n = 0; n < nnodes; n++) { + NodeRef nr = tree.getNode(n); + boolean collapse; + if (tree.isRoot(nr)) { + collapse = BirthDeathCollapseModel.belowCollapseHeight(tree.getNodeHeight(nr), collapseheight); + } else { + NodeRef anc = tree.getParent(nr); + collapse = (BirthDeathCollapseModel.belowCollapseHeight(tree.getNodeHeight(nr), collapseheight) + && !BirthDeathCollapseModel.belowCollapseHeight(tree.getNodeHeight(anc), collapseheight)); + } + if (collapse) { + nshort++; + nodeToClade(taxonList, tree, nr, nshort); + } + } + } + + + double distance(Cluster sd) { + double d = 0.0; + for (int i = 0; i < partition.length; i++) { + for (int j = 0; j < i; j ++) { + boolean pair = partition[i] == partition[j]; + boolean sdpair = sd.partition[i] == sd.partition[j]; + if (pair != sdpair) { + d += 1.0; + } + } + } + return d / (partition.length * (partition.length-1.0) / 2.0); + } + + + double similarity(Cluster sd) { + return 1.0 - distance(sd); + } + + + + private void nodeToClade(TaxonList taxonlist, Tree tree, NodeRef nr, int idx) { + if (tree.isExternal(nr)) { + String id = tree.getNodeTaxon(nr).getId(); + int i = taxonIdToInt(taxonlist, id); + partition[i] = idx; + } else { + assert 2 == tree.getChildCount(nr); + nodeToClade(taxonlist, tree, tree.getChild(nr, 0), idx); + nodeToClade(taxonlist, tree, tree.getChild(nr, 1), idx); + } + } + + int taxonIdToInt(TaxonList taxonList, String id) { + int j = -1; + for (int i = 0; i < taxonList.getTaxonCount(); i++) { + String tid = taxonList.getTaxonId(i); + if (id.compareTo(tid) == 0) { + assert j < 0; + j = i; + } + } + assert j >= 0; + return j; + } + } + + + SpeciesDelimitationAnalyser(int burnin, double collapseheight, double similaritycutoff, String inputFileName, String outputFileName) { + this.burnin = burnin; + this.collapseheight = collapseheight; + this.similaritycutoff = similaritycutoff; + this.inputFileName = inputFileName; + this.outputFileName = outputFileName; + } + + void readtrees() throws IOException { + clusters = new ArrayList(0); + int totalTrees; + FileReader fileReader = new FileReader(inputFileName); + NexusImporter importer = new NexusImporter(fileReader); + System.out.println("Reading trees..."); + try { + taxonList = importer.parseTaxaBlock(); + totalTrees = 0; + while (importer.hasTree()) { + Tree tree = importer.importNextTree(); + + if (totalTrees >= burnin) { + Cluster sd = new Cluster(taxonList, tree, collapseheight); + clusters.add(sd); + } + + if (totalTrees > 0 && (totalTrees % 100 == 0)) { + System.out.print("*"); + System.out.flush(); + } + if (totalTrees > 0 && (totalTrees % 5000 == 0)) { + System.out.println(" " + totalTrees); + System.out.flush(); + } + totalTrees++; + } + System.out.println(""); + } catch (Importer.ImportException e) { + System.err.println("Error Parsing Input Tree: " + e.getMessage()); + return; + } + fileReader.close(); + if (totalTrees < 1) { + System.err.println("No trees"); + return; + } + System.out.println("Total trees read: " + totalTrees); + } + + + + void countclusterings() { + if (burnin > 0) { + System.out.println("Ignoring first " + burnin + " trees."); + } + System.out.println("Counting clusterings... "); + for (int i = 0; i < clusters.size(); i++) { + if (i > 0 && (i % 100 == 0)) { + System.out.print("*"); + System.out.flush(); + } + if (i > 0 && (i % 5000 == 0)) { + System.out.println(" " + i); + System.out.flush(); + } + + for (int j = i+1; j < clusters.size(); j++) { + if (clusters.get(j).count > 0) { + double simij = clusters.get(i).similarity(clusters.get(j)); + if (simij == 1.0) { + clusters.get(i).count += 1; + clusters.get(j).count = 0; + clusters.get(j).deleted = true; + } + if (simij >= similaritycutoff || simij == 1.0) { + clusters.get(i).totalsimilarity += simij; + } + } + } + } + Collections.sort(clusters, CLUSTER_COMPARATOR); + } + + + + void writeresults() throws IOException { + FileWriter fileWriter = new FileWriter(outputFileName); + + fileWriter.write("count fraction similarity nclusters "); + for (int i = 0; i < taxonList.getTaxonCount(); i++) { + String tstr = taxonList.getTaxonId(i); + while (tstr.length() < 4) tstr += " "; + fileWriter.write(tstr + " "); + } + fileWriter.write("\n"); + for (int i = 0; i < clusters.size(); i++) { + Cluster sd = clusters.get(i); + if (sd.count > 0) { + String countstr = "" + sd.count; + while (countstr.length() < 10) countstr += " "; + String fracstr = "" + (double)sd.count / (double) clusters.size(); + while (fracstr.length() < 22) fracstr += " "; + String simstr = "" + sd.totalsimilarity; + while (simstr.length() < 22) simstr += " "; + int clustercount = 0; + for (int j = 0; j < sd.partition.length; j ++) { + if (sd.partition[j] > clustercount) { + clustercount = sd.partition[j]; + } + } + String ccstr = "" + clustercount; + while (ccstr.length() < 10) ccstr += " "; + fileWriter.write(countstr + " " + fracstr + " " + simstr + " " + ccstr + " "); + for (int j = 0; j < sd.partition.length; j ++) { + String pjstr = "" + sd.partition[j]; + while (pjstr.length() < 4) { pjstr += " "; } + fileWriter.write(pjstr + " "); + } + fileWriter.write("\n"); + } + } + fileWriter.write("\n"); + fileWriter.close(); + + } + + + + public static void printTitle() { + System.out.println(); + centreLine("SpeciesDelimitationAnalyser " + version.getVersionString() + ", " + version.getDateString(), 60); + centreLine("Finds clusterings of individuals into clusters", 60); + centreLine("(ie possible species) from MCMC tree samples", 60); + centreLine("by", 60); + centreLine("Graham Jones", 60); + centreLine("www.indriid.com", 60); + System.out.println(); + System.out.println(); + } + + + + public static void centreLine(String line, int pageWidth) { + int n = pageWidth - line.length(); + int n1 = n / 2; + for (int i = 0; i < n1; i++) { + System.out.print(" "); + } + System.out.println(line); + } + + + public static void printUsage(Arguments arguments) { + + arguments.printUsage("SpeciesDelimitationAnalyser", " "); + System.out.println(); + System.out.println(" Example: SpeciesDelimitationAnalyser treesamples.txt out.txt"); + System.out.println(); + } + + + static final Comparator CLUSTER_COMPARATOR = new Comparator() { + public int compare(Cluster a, Cluster b) { + if (a.deleted != b.deleted) { + return a.deleted ? 1 : -1; + } + if (b.totalsimilarity != a.totalsimilarity) { + return (b.totalsimilarity > a.totalsimilarity) ? 1 : -1; + } + return 0; + } + }; + + + + + public static void main(String[] args) throws java.io.IOException { + + Locale.setDefault(Locale.US); + + printTitle(); + + Arguments arguments = new Arguments( + new Arguments.Option[]{ + new Arguments.IntegerOption("burnin", "b", "the number of states to be considered as 'burn-in' [default = none]"), + new Arguments.RealOption("collapseheight", "c", "the height below which nodes get collapsed [default = .001]"), + new Arguments.RealOption("simcutoff", "s", "the value above which two clusters are regarded as similar enough to support one another's credibility [default = .9]"), + new Arguments.Option("help", "h", "option to print this message") + }); + + try { + arguments.parseArguments(args); + } catch (Arguments.ArgumentException ae) { + System.out.println(ae); + printUsage(arguments); + System.exit(1); + } + + if (arguments.hasOption("help")) { + printUsage(arguments); + System.exit(0); + } + + int burnin = -1; + if (arguments.hasOption("burnin")) { + burnin = arguments.getIntegerOption("burnin"); + } + System.out.println(); + + double collapseheight = 0.001; + if (arguments.hasOption("collapseheight")) { + collapseheight = arguments.getRealOption("collapseheight"); + } + + double similaritycutoff = 0.9; + if (arguments.hasOption("simcutoff")) { + similaritycutoff = arguments.getRealOption("simcutoff"); + } + + System.out.println("burnin " + burnin + " collapseheight " + collapseheight + " simcutoff "+ similaritycutoff); + + String[] args2 = arguments.getLeftoverArguments(); + if (args2.length > 2) { + System.err.println("Unknown option: " + args2[2]); + System.err.println(); + printUsage(arguments); + System.exit(1); + } + if (args2.length < 2) { + System.err.println("Input filename and outputfilename required"); + System.err.println(); + printUsage(arguments); + System.exit(1); + } + + String inputFileName = args2[0]; + String outputFileName = args2[1]; + + SpeciesDelimitationAnalyser spDA = + new SpeciesDelimitationAnalyser(burnin, collapseheight, similaritycutoff, inputFileName, outputFileName); + spDA.readtrees(); + spDA.countclusterings(); + spDA.writeresults(); + + System.exit(0); + + } +} diff --git a/src/dr/app/tools/TaxaPicker.java b/src/dr/app/tools/TaxaPicker.java index 4cd0979b29..9cc54222aa 100644 --- a/src/dr/app/tools/TaxaPicker.java +++ b/src/dr/app/tools/TaxaPicker.java @@ -37,7 +37,6 @@ import dr.evolution.tree.NodeRef; import dr.evolution.tree.Tree; import dr.evolution.util.Taxon; -import dr.evomodel.arg.ARGModel; import dr.util.Version; import java.io.*; diff --git a/src/dr/evolution/datatype/DataType.java b/src/dr/evolution/datatype/DataType.java index c629aad9a9..ab004d3c8f 100644 --- a/src/dr/evolution/datatype/DataType.java +++ b/src/dr/evolution/datatype/DataType.java @@ -91,7 +91,6 @@ private static void lazyRegisterDataTypes() { registerDataType(Codons.DESCRIPTION + "-" + GeneticCode.BLEPHARISMA_NUC.getName(), Codons.BLEPHARISMA_NUC); registerDataType(Codons.DESCRIPTION + "-" + GeneticCode.NO_STOPS.getName(), Codons.NO_STOPS); registerDataType(TwoStates.DESCRIPTION, TwoStates.INSTANCE); - registerDataType(OldHiddenNucleotides.DESCRIPTION, OldHiddenNucleotides.INSTANCE); registerDataType(TwoStateCovarion.DESCRIPTION, TwoStateCovarion.INSTANCE); registerDataType(HiddenCodons.DESCRIPTION + "2-" + GeneticCode.UNIVERSAL.getName(), HiddenCodons.UNIVERSAL_HIDDEN_2); registerDataType(HiddenCodons.DESCRIPTION + "3-" + GeneticCode.UNIVERSAL.getName(), HiddenCodons.UNIVERSAL_HIDDEN_3); diff --git a/src/dr/evolution/datatype/OldHiddenNucleotides.java b/src/dr/evolution/datatype/OldHiddenNucleotides.java deleted file mode 100644 index b8519c2456..0000000000 --- a/src/dr/evolution/datatype/OldHiddenNucleotides.java +++ /dev/null @@ -1,248 +0,0 @@ -/* - * OldHiddenNucleotides.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evolution.datatype; - -/** - * implements DataType for nucleotides with hidden state(s) - * - * @author Alexei Drummond - */ -@Deprecated -public class OldHiddenNucleotides extends DataType { - - public static final String DESCRIPTION = "hiddenNucleotide"; - public static final OldHiddenNucleotides INSTANCE = new OldHiddenNucleotides(2); - - public OldHiddenNucleotides(int numHiddenStates) { - hiddenClassCount = numHiddenStates; - - stateCount = 4 * hiddenClassCount; - ambiguousStateCount = stateCount + 6; - } - - @Override - public char[] getValidChars() { - return null; - } - - /** - * Get state corresponding to a character - * - * @param c character - * @return state - */ - public int getState(char c) { - - switch (c) { - case'A': - case'a': - return stateCount; - case'C': - case'c': - return stateCount + 1; - case'G': - case'g': - return stateCount + 2; - case'T': - case't': - case'U': - case'u': - return stateCount + 3; - case'-': - case'?': - return getGapState(); - default: { - int state = (int) c - '0'; - if (c > '?') state -= 1; - if (c > 'A') state -= 1; - if (c > 'C') state -= 1; - if (c > 'G') state -= 1; - if (c > 'T') state -= 1; - if (c > 'U') state -= 1; - if (c > 'a') state -= 1; - if (c > 'g') state -= 1; - if (c > 'c') state -= 1; - if (c > 't') state -= 1; - if (c > 'u') state -= 1; - return state; - } - } - - } - - /** - * Get character corresponding to a given state - * - * @param state state - *

- * return corresponding character - */ - public char getChar(int state) { - - if (state >= stateCount) { - switch (state - stateCount) { - case 0: - return 'A'; - case 1: - return 'C'; - case 2: - return 'G'; - case 3: - return 'T'; - default: - return '-'; - } - } else { - char c = (char) (state + '0'); - if (c >= '?') c += 1; - if (c >= 'A') c += 1; - if (c >= 'C') c += 1; - if (c >= 'G') c += 1; - if (c >= 'T') c += 1; - if (c >= 'U') c += 1; - if (c >= 'a') c += 1; - if (c >= 'g') c += 1; - if (c >= 'c') c += 1; - if (c >= 't') c += 1; - if (c >= 'u') c += 1; - return c; - } - } - - public int[] getStates(int state) { - - if (state >= stateCount && state <= stateCount + 3) { - int[] states = new int[hiddenClassCount]; - for (int i = 0; i < hiddenClassCount; i++) { - states[i] = state % 4 + (i * 4); - } - return states; - } else throw new IllegalArgumentException(); - } - - /** - * returns an array containing the non-ambiguous states that this state represents. - */ - public boolean[] getStateSet(int state) { - - boolean[] stateSet = new boolean[stateCount]; - for (int i = 0; i < stateCount; i++) { - stateSet[i] = false; - } - if (!isAmbiguousState(state)) { - stateSet[state] = true; - } else if (state < (stateCount + 4)) { - for (int i = 0; i < stateCount; i++) { - if ((i % 4) == (state % 4)) { - stateSet[i] = true; - } - - } - } else { - for (int i = 0; i < stateCount; i++) { - stateSet[i] = true; - } - } - - return stateSet; - } - - /** - * Get state corresponding to an unknown - * - * @return state - */ - public int getUnknownState() { - return stateCount + 4; - } - - /** - * Get state corresponding to a gap - * - * @return state - */ - public int getGapState() { - return stateCount + 5; - } - - /** - * @return true if this character is an ambiguous state - */ - public boolean isAmbiguousChar(char c) { - return isAmbiguousState(getState(c)); - } - - /** - * @return true if this character is a gap - */ - public boolean isUnknownChar(char c) { - return isUnknownState(getState(c)); - } - - /** - * @return true if this character is a gap - */ - public boolean isGapChar(char c) { - return isGapState(getState(c)); - } - - /** - * returns true if this state is an ambiguous state. - */ - public boolean isAmbiguousState(int state) { - return (state >= stateCount); - } - - /** - * @return true if this state is an unknown state - */ - public boolean isUnknownState(int state) { - return (state == getUnknownState()); - } - - /** - * @return true if this state is a gap - */ - public boolean isGapState(int state) { - return (state == getGapState()); - } - - public int getType() { - return 999; - } - - public String getDescription() { - return "Hidden-state Nucleotides"; - } - - private int hiddenClassCount; - - public int getHiddenClassCount() { - return hiddenClassCount; - } -} diff --git a/src/dr/evomodel/alloppnet/operators/AlloppChangeNumHybridizations.java b/src/dr/evomodel/alloppnet/operators/AlloppChangeNumHybridizations.java deleted file mode 100644 index 54d099d2cb..0000000000 --- a/src/dr/evomodel/alloppnet/operators/AlloppChangeNumHybridizations.java +++ /dev/null @@ -1,324 +0,0 @@ - -/* - * AlloppChangeNumHybridizations.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.alloppnet.operators; - -import java.util.ArrayList; - - -import dr.evomodel.alloppnet.speciation.*; -import dr.evomodel.alloppnet.parsers.AlloppChangeNumHybridizationsParser; -import dr.inference.operators.SimpleMCMCOperator; - -import dr.math.MathUtils; -import jebl.util.FixedBitSet; - -/** - * @author Graham Jones - * Date: 22/07/2012 - */ - - - -public class AlloppChangeNumHybridizations extends SimpleMCMCOperator { - - private final AlloppSpeciesNetworkModel apspnet; - private final AlloppSpeciesBindings apsp; - static private final int footdistribution = 2; - - - public AlloppChangeNumHybridizations(AlloppSpeciesNetworkModel apspnet, AlloppSpeciesBindings apsp, double weight) { - this.apspnet = apspnet; - this.apsp = apsp; - setWeight(weight); - } - - - public String getPerformanceSuggestion() { - return "None"; - } - - @Override - public String getOperatorName() { - return AlloppChangeNumHybridizationsParser.CHANGE_NUM_HYBRIDIZATIONS + "(" + apspnet.getId() + - "," + apsp.getId() + ")"; - } - - @Override - public double doOperation() { - if (apspnet.getOneHybridization()) { - throw new RuntimeException("oneHybridization is true but changeNumHybridizations() called"); - } - apspnet.beginNetworkEdit(); - double hr = 0.0; - if (MathUtils.nextBoolean()) { - hr = doMergeMove(); - } else { - hr = doSplitMove(); - } - apspnet.endNetworkEdit(); - assert apspnet.netAndGTreesAreCompatible(); - return hr; - } - - private class MergeCandidate { - public int i; - public int j; - - MergeCandidate(int i, int j) { - this.i = i; - this.j = j; - } - } - - - private class SplitCandidate { - public int i; - public AlloppNode root1; - public AlloppNode root2; - - SplitCandidate(int i, AlloppNode root1, AlloppNode root2) { - this.i = i; - this.root1 = root1; - this.root2 = root2; - } - } - - - private double doMergeMove() { - double hr = 0.0; - ArrayList mcands = findCandidateMerges(); - int nmerges = mcands.size(); - if (nmerges > 0) { - int mpair = MathUtils.nextInt(nmerges); - MergeCandidate mcand = mcands.get(mpair); - hr += Math.log(nmerges); - hr += mergeTettreePair(mcand.i, mcand.j); - hr -= Math.log(countCandidateSplits()); - double logpdfoldval = apspnet.removeHybPopParam(); - hr += logpdfoldval; - } - return hr; - } - - - private double doSplitMove() { - double hr = 0.0; - ArrayList scands = findCandidateSplits(); - int nsplits = scands.size(); - if (nsplits > 0) { - int stt = MathUtils.nextInt(nsplits); - SplitCandidate scand = scands.get(stt); - hr += Math.log(nsplits); - hr += splitTettree(scand.i, scand.root1, scand.root2); - hr -= Math.log(countCandidateMerges()); - double logpdfnewval = apspnet.addHybPopParam(); - hr -= logpdfnewval; - } - return hr; - } - - - private ArrayList findCandidateMerges() { - ArrayList mcands = new ArrayList(); - int numttrees = apspnet.getNumberOfTetraTrees(); - for (int i = 0; i < numttrees; i++) { - for (int j = 0; j < numttrees; j++) { - if (i != j && pairAreMergeable(i, j)) { - mcands.add(new MergeCandidate(i, j)); - } - } - } - return mcands; - } - - - private int countCandidateMerges() { - return findCandidateMerges().size(); - } - - - - private ArrayList findCandidateSplits() { - ArrayList scands = new ArrayList(); - int numttrees = apspnet.getNumberOfTetraTrees(); - for (int i = 0; i < numttrees; i++) { - AlloppLeggedTree ttree = apspnet.getTetraploidTree(i); - if (ttree.getSlidableNodeCount() > 1) { - AlloppNode lft = ((AlloppNode)ttree.getSlidableRoot()).getChild(0); - AlloppNode rgt = ((AlloppNode)ttree.getSlidableRoot()).getChild(1); - scands.add(new SplitCandidate(i, lft, rgt)); - scands.add(new SplitCandidate(i, rgt, lft)); - } - } - return scands; - } - - private int countCandidateSplits() { - return findCandidateSplits().size(); - } - - - - private boolean pairAreMergeable(int tt1, int tt2) { - boolean mergeable = true; - AlloppLeggedTree ttree1 = apspnet.getTetraploidTree(tt1); - AlloppLeggedTree ttree2 = apspnet.getTetraploidTree(tt2); - AlloppDiploidHistory adhist = apspnet.getDiploidHistory(); - // check legs agree and meet as produced by a split move. - mergeable = mergeable && adhist.tettreesShareLegs(ttree1, ttree2); - return mergeable; - } - - - private double mergeTettreePair(int tt1, int tt2) { - double hr = 0.0; - AlloppLeggedTree ttree1 = apspnet.getTetraploidTree(tt1); - AlloppLeggedTree ttree2 = apspnet.getTetraploidTree(tt2); - AlloppDiploidHistory adhist = apspnet.getDiploidHistory(); - // collect height info - AlloppDiploidHistory.FootAncHeights lftleg2 = - adhist.intervalOfFootAncestor(ttree2, AlloppDiploidHistory.LegLorR.left); - AlloppDiploidHistory.FootAncHeights rgtleg2 = - adhist.intervalOfFootAncestor(ttree2, AlloppDiploidHistory.LegLorR.right); - // Choose most recent footanc height as root height of merged tree. - // Account for loss of the other footanc height. - // Use gene limit on the lost footanc height for hr calculation. - // grjtodo-soon test the gene limit calculation somehow - double rooth; - if (lftleg2.anchgt < rgtleg2.anchgt) { - rooth = lftleg2.anchgt; - FixedBitSet tt1leg1 = apspnet.unionOfWholeTetTree(tt1, 1); - FixedBitSet tt2leg1 = apspnet.unionOfWholeTetTree(tt2, 1); - double genelimit = apsp.spseqUpperBound(tt1leg1, tt2leg1); - double maxfootanchgt = Math.min(genelimit, rgtleg2.ancanchgt); - hr += Math.log(uniformpdf(rooth, maxfootanchgt)); - } else { - rooth = rgtleg2.anchgt; - FixedBitSet tt1leg0 = apspnet.unionOfWholeTetTree(tt1, 0); - FixedBitSet tt2leg0 = apspnet.unionOfWholeTetTree(tt2, 0); - double genelimit = apsp.spseqUpperBound(tt1leg0, tt2leg0); - double maxfootanchgt = Math.min(genelimit, lftleg2.ancanchgt); - hr += Math.log(uniformpdf(rooth, maxfootanchgt)); - } - // account for loss of two old hybhgts - hr += Math.log(uniformpdf(ttree1.getRootHeight(), rooth)); - hr += Math.log(uniformpdf(ttree2.getRootHeight(), rooth)); - // merge the trees and replace tt2 with result - AlloppLeggedTree merged = new AlloppLeggedTree(ttree1, ttree2, rooth); - apspnet.setTetTree(tt2, merged); - apspnet.removeTetree(tt1); - // Fix up the links from diploid history. - // Get rid of old links first, to enable later assertions - adhist.clearAllNodeTettree(); - for (int i = 0; i < apspnet.getNumberOfTetraTrees(); i++) { - AlloppLeggedTree ttree = apspnet.getTetraploidTree(i); - int dhlftleg = ttree.getDiphistLftLeg(); - assert adhist.getNodeTettree(dhlftleg) == -1; - adhist.setNodeTettree(dhlftleg, i); - int dhrgtleg = ttree.getDiphistRgtLeg(); - assert adhist.getNodeTettree(dhrgtleg) == -1; - adhist.setNodeTettree(dhrgtleg, i); - } - // new hybhgt for merged tree - double maxhybhgt = Math.min(lftleg2.ancanchgt, rgtleg2.ancanchgt); - double hybght = MathUtils.uniform(rooth, maxhybhgt); - adhist.setHybridHeight(merged, hybght); - hr -= Math.log(uniformpdf(rooth, maxhybhgt)); - adhist.removeFeet(apspnet, ttree1); - return hr; - } - - - private double uniformpdf(double min, double max) { - double density = 1.0 / (max-min); - return density; - } - - private double splitTettree(int tt, AlloppNode root1, AlloppNode root2) { - double hr = 0.0; - // collect info from old TetraTree - AlloppLeggedTree tetTree = apspnet.getTetraploidTree(tt); - AlloppDiploidHistory adhist = apspnet.getDiploidHistory(); - double rooth = tetTree.getRootHeight(); - int lftleg = tetTree.getDiphistLftLeg(); - int rgtleg = tetTree.getDiphistRgtLeg(); - double lftanchgt = adhist.getAncHeight(lftleg); - double rgtanchgt = adhist.getAncHeight(rgtleg); - // account for the hybhgt that will be lost - hr += Math.log(uniformpdf(rooth, Math.min(lftanchgt, rgtanchgt))); - // make two new trees - AlloppLeggedTree tetTree1 = new AlloppLeggedTree(tetTree, root1); - AlloppLeggedTree tetTree2 = new AlloppLeggedTree(tetTree, root2); - // tetree2 gets old one's legs, with new height - tetTree2.setDiphistLftLeg(lftleg); - tetTree2.setDiphistRgtLeg(rgtleg); - double hybhgt2 = MathUtils.uniform(tetTree2.getRootHeight(), rooth); - hr -= Math.log(uniformpdf(tetTree2.getRootHeight(), rooth)); - adhist.setHybridHeight(tetTree2, hybhgt2); - // remove old and add new ones to list. - // tetTree2 replaces tetTree, that is, same index, so dip tips stay consistent - apspnet.setTetTree(tt, tetTree2); - int tt2 = tt; - int tt1 = apspnet.addTetTree(tetTree1); - // new hybhgt for tree1 - double hybhgt1 = MathUtils.uniform(tetTree1.getRootHeight(), rooth); - hr -= Math.log(uniformpdf(tetTree1.getRootHeight(), rooth)); - // new hgt for a foot anc (other height is rooth) - // it is constrained by gene trees and existing node height - if (MathUtils.nextBoolean()) { - FixedBitSet tt1leg0 = apspnet.unionOfWholeTetTree(tt1, 0); - FixedBitSet tt2leg0 = apspnet.unionOfWholeTetTree(tt2, 0); - double genelimit = apsp.spseqUpperBound(tt1leg0, tt2leg0); - double maxfootanchgt = Math.min(genelimit, lftanchgt); - double footanchgt = MathUtils.uniform(rooth, maxfootanchgt); - hr -= Math.log(uniformpdf(rooth, maxfootanchgt)); - adhist.addTwoDipTips(apspnet, tt1, tt2, footanchgt, rooth, hybhgt1); - } else { - FixedBitSet tt1leg1 = apspnet.unionOfWholeTetTree(tt1, 1); - FixedBitSet tt2leg1 = apspnet.unionOfWholeTetTree(tt2, 1); - double genelimit = apsp.spseqUpperBound(tt1leg1, tt2leg1); - double maxfootanchgt = Math.min(genelimit, rgtanchgt); - double footanchgt = MathUtils.uniform(rooth, maxfootanchgt); - hr -= Math.log(uniformpdf(rooth, maxfootanchgt)); - adhist.addTwoDipTips(apspnet, tt1, tt2, rooth, footanchgt, hybhgt1); - } - // grjtodo-soon The only difference between the two states is the time-order of the nodes. - // Should topologies or histories be counted? - // Account for left/right choice. This says histories - hr += Math.log(2.0); - return hr; - } - - - -} - - - - diff --git a/src/dr/evomodel/alloppnet/operators/AlloppHybPopSizesScale.java b/src/dr/evomodel/alloppnet/operators/AlloppHybPopSizesScale.java deleted file mode 100644 index 0581e5f92d..0000000000 --- a/src/dr/evomodel/alloppnet/operators/AlloppHybPopSizesScale.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * AlloppHybPopSizesScale.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.alloppnet.operators; - -import dr.evomodel.alloppnet.speciation.AlloppSpeciesBindings; -import dr.evomodel.alloppnet.speciation.AlloppSpeciesNetworkModel; -import dr.evomodel.alloppnet.parsers.AlloppHybPopSizesScaleParser; -import dr.inference.operators.SimpleMCMCOperator; -import dr.math.MathUtils; - -/** - * @author Graham Jones - * Date: 03/08/12 - */ -public class AlloppHybPopSizesScale extends SimpleMCMCOperator { - - private final AlloppSpeciesNetworkModel apspnet; - private final AlloppSpeciesBindings apsp; - private final double scalingFactor; - - public AlloppHybPopSizesScale(AlloppSpeciesNetworkModel apspnet, AlloppSpeciesBindings apsp, double scalingFactor, double weight) { - this.apspnet = apspnet; - this.apsp = apsp; - this.scalingFactor = scalingFactor; - setWeight(weight); - } - - - public String getPerformanceSuggestion() { - return "None"; - } - - @Override - public String getOperatorName() { - return AlloppHybPopSizesScaleParser.HYB_POP_SIZES_SCALE + "(" + apspnet.getId() + - "," + apsp.getId() + ")"; - } - - @Override - public double doOperation() { - apspnet.beginNetworkEdit(); - double b = (1.0-scalingFactor) * (1.0-scalingFactor) / scalingFactor; - double c = scalingFactor / (1.0-scalingFactor); - double y = MathUtils.nextDouble(); - double s = b * (y+c) * (y+c); - int i = MathUtils.nextInt(apspnet.getNumberOfTetraTrees()); - apspnet.setOneHybPopValue(i, s * apspnet.getOneHybPopValue(i)); - apspnet.endNetworkEdit(); - return 0.0; // this way of scaling, with proposal proportional to x^-(1/2) has hastings ratio 1 - } - -} diff --git a/src/dr/evomodel/alloppnet/operators/AlloppMoveLegs.java b/src/dr/evomodel/alloppnet/operators/AlloppMoveLegs.java deleted file mode 100644 index 4694bf94e7..0000000000 --- a/src/dr/evomodel/alloppnet/operators/AlloppMoveLegs.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * AlloppMoveLegs.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.alloppnet.operators; - -import dr.evomodel.alloppnet.speciation.AlloppSpeciesBindings; -import dr.evomodel.alloppnet.speciation.AlloppSpeciesNetworkModel; -import dr.evomodel.alloppnet.parsers.AlloppMoveLegsParser; -import dr.inference.operators.SimpleMCMCOperator; - - -/** - * - * @author Graham Jones - * Date: 31/08/2011 - */ - - -// 2012-07 ood -public class AlloppMoveLegs extends SimpleMCMCOperator { - - private final AlloppSpeciesNetworkModel apspnet; - private final AlloppSpeciesBindings apsp; - - public AlloppMoveLegs(AlloppSpeciesNetworkModel apspnet, AlloppSpeciesBindings apsp, double weight) { - this.apspnet = apspnet; - this.apsp = apsp; - setWeight(weight); - } - - - public String getPerformanceSuggestion() { - return "None"; - } - - @Override - public String getOperatorName() { - return AlloppMoveLegsParser.MOVE_LEGS + "(" + apspnet.getId() + - "," + apsp.getId() + ")"; - } - - @Override - public double doOperation() { - apspnet.beginNetworkEdit(); - apspnet.moveLegs(); - apspnet.endNetworkEdit(); - return 0; - } - -} diff --git a/src/dr/evomodel/alloppnet/operators/AlloppNetworkNodeSlide.java b/src/dr/evomodel/alloppnet/operators/AlloppNetworkNodeSlide.java deleted file mode 100644 index 22f9488033..0000000000 --- a/src/dr/evomodel/alloppnet/operators/AlloppNetworkNodeSlide.java +++ /dev/null @@ -1,346 +0,0 @@ -/* - * AlloppNetworkNodeSlide.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.alloppnet.operators; - -import dr.evolution.tree.NodeRef; -import dr.evomodel.alloppnet.tree.SlidableTree; -import dr.evomodel.alloppnet.speciation.AlloppDiploidHistory; -import dr.evomodel.alloppnet.speciation.AlloppLeggedTree; -import dr.evomodel.alloppnet.speciation.AlloppSpeciesBindings; -import dr.evomodel.alloppnet.speciation.AlloppSpeciesNetworkModel; -import dr.evomodel.alloppnet.parsers.AlloppNetworkNodeSlideParser; -import dr.inference.operators.SimpleMCMCOperator; -import dr.math.MathUtils; -import jebl.util.FixedBitSet; - -import java.util.ArrayList; - - -/** - * - * @author Graham Jones - * Date: 01/07/2011 - */ - - -/* - * An operator for with allopolyploid networks. Uses mnlCanonical() and mnlReconstruct() - * in SlidableTree.Utils to do some of the work. These are called to change one node in - * diploid history or one node in a tetratree. There is also a move to change hyb height. - * - * - */ -public class AlloppNetworkNodeSlide extends SimpleMCMCOperator { - - private final AlloppSpeciesNetworkModel apspnet; - private final AlloppSpeciesBindings apsp; - - public AlloppNetworkNodeSlide(AlloppSpeciesNetworkModel apspnet, AlloppSpeciesBindings apsp, double weight) { - this.apspnet = apspnet; - this.apsp = apsp; - setWeight(weight); - } - - public String getPerformanceSuggestion() { - return "None"; - } - - @Override - public String getOperatorName() { - return AlloppNetworkNodeSlideParser.NETWORK_NODE_REHEIGHT + "(" + apspnet.getId() + - "," + apsp.getId() + ")"; - } - - @Override - public double doOperation() { - operateOneNodeInNet(0.0); - return 0; - } - - - - - private class NodeHeightInNetIndex { - public int ploidy; // 2 for diphist, 4 for a tetra tree - public int tree; // indexes tettree - public int index; // internal node in diphist or tettree, or foot index for hyb height - public boolean doHybheight; - - public NodeHeightInNetIndex(int ploidy, int tree, int index, boolean doHybheight) { - this.ploidy = ploidy; - this.tree = tree; - this.index = index; - this.doHybheight = doHybheight; - } - } - - - private NodeHeightInNetIndex randomnode() { - int noftettrees = apspnet.getNumberOfTetraTrees(); - int dhcount; - int hybhcount; - int count = 0; - - dhcount = apspnet.getNumberOfInternalNodesInDipHist(); - count += dhcount; - hybhcount = noftettrees; - count += hybhcount; - // For each tetratree, the internal/root heights - for (int i = 0; i < noftettrees; i++) { - int n = apspnet.getNumberOfInternalNodesInTetTree(i); - count += n; - } - int which = MathUtils.nextInt(count); - if (which < dhcount) { - return new NodeHeightInNetIndex(2, 0, which, false); - } else { - which -= dhcount; - if (which < hybhcount) { - // twice as many feet as hybridizations - int w = which + (MathUtils.nextBoolean() ? 0 : hybhcount); - return new NodeHeightInNetIndex(2, 0, w, true); - } else { - which -= hybhcount; - for (int i = 0; i < noftettrees; i++) { - int n = apspnet.getNumberOfInternalNodesInTetTree(i); - if (which < n) { - return new NodeHeightInNetIndex(4, i, which, false); - } else { - which -= n; - } - } - } - } - assert false; - return new NodeHeightInNetIndex(-1, -1, -1, false); - } - - - - - private void operateOneNodeInNet(double factor) { - assert apspnet.getDiploidHistory().diphistOK(apspnet.getDiploidRootIsRoot()); - NodeHeightInNetIndex nhi = randomnode(); - if (nhi.doHybheight) { - operateHybridHeight(nhi.index); - } else { - if (nhi.ploidy == 2) { - operateOneNodeInDiploidHistory(nhi.index, factor); - } else { - assert nhi.ploidy == 4; - AlloppLeggedTree altree = apspnet.getTetraploidTree(nhi.tree); - operateOneNodeInTetraTree(altree, nhi.index, factor); - } - } - } - - - - private void operateHybridHeight(int footindex) { - AlloppDiploidHistory diphist = apspnet.getDiploidHistory(); - ArrayList feet = diphist.collectFeet(); - - assert footindex < feet.size(); - int foot = feet.get(footindex); - int tt = diphist.getNodeTettree(foot); - AlloppLeggedTree tettree = apspnet.getTetraploidTree(tt); - double minh = tettree.getRootHeight(); - int f1 = tettree.getDiphistLftLeg(); - int f2 = tettree.getDiphistRgtLeg(); - assert (foot == f1) || (foot == f2); - apspnet.beginNetworkEdit(); - diphist.moveHybridHeight(f1, f2, minh); - apspnet.endNetworkEdit(); - } - - - private void operateOneNodeInTetraTree(AlloppLeggedTree tettree, int which, double factor) { - - // As TreeNodeSlide(). Randomly flip children at each node, - // keeping track of node order (in-order order, left to right). - - NodeRef[] order = SlidableTree.Utils.mnlCanonical(tettree); - - // Find the time of the most recent gene coalescence which - // has (species,sequence)'s to left and right of this node. - FixedBitSet left = apsp.speciesseqEmptyUnion(); - FixedBitSet right = apsp.speciesseqEmptyUnion(); - for (int k = 0; k < 2 * which + 1; k += 2) { - FixedBitSet left0 = apsp.taxonseqToTipUnion(tettree.getSlidableNodeTaxon(order[k]), 0); - FixedBitSet left1 = apsp.taxonseqToTipUnion(tettree.getSlidableNodeTaxon(order[k]), 1); - left.union(left0); - left.union(left1); - } - for (int k = 2 * (which + 1); k < order.length; k += 2) { - FixedBitSet right0 = apsp.taxonseqToTipUnion(tettree.getSlidableNodeTaxon(order[k]), 0); - FixedBitSet right1 = apsp.taxonseqToTipUnion(tettree.getSlidableNodeTaxon(order[k]), 1); - right.union(right0); - right.union(right1); - } - double genelimit = apsp.spseqUpperBound(left, right); - - // also keep this node more recent than the hybridization event that led to this tree. - AlloppDiploidHistory diphist = apspnet.getDiploidHistory(); - double hybridheight = diphist.getHybHeight(tettree); - - final double limit = Math.min(genelimit, hybridheight); - - // On direct call, factor==0.0 and use limit. Else use passed in scaling factor - double newHeight = -1.0; - if( factor > 0 ) { - newHeight = tettree.getSlidableNodeHeight(order[2*which+1]) * factor; - } else { - newHeight = MathUtils.nextDouble() * limit; - } - - apspnet.beginNetworkEdit(); - final NodeRef node = order[2 * which + 1]; - tettree.setSlidableNodeHeight(node, newHeight); - SlidableTree.Utils.mnlReconstruct(tettree, order); - apspnet.endNetworkEdit(); - } - - - - private class RootHeightRange { - public double lowerlimit; - public double upperlimit; - RootHeightRange(double lowerlimit, double upperlimit) { - this.lowerlimit = lowerlimit; - this.upperlimit = upperlimit; - } - } - - - - // find limit to keep root a diploid - // 1. If node to slide is the root, and the second highest node is to left or - // right of all diploids, then the root must stay the root: lowerlimit = second highest. - // 2. If node to slide is not the root, and is to left or right of all diploids, - // then it must not become the root: upperlimit = root height. - RootHeightRange findRootRangeForDiploidRootIsRoot(AlloppDiploidHistory diphist, NodeRef[] order, int slidingn) { - RootHeightRange rootrange = new RootHeightRange(0.0, Double.MAX_VALUE); - int rootn = -1; - double maxhgt = 0.0; - for (int k = 1; k < order.length; k += 2) { - double hgt = diphist.getSlidableNodeHeight(order[k]); - if (hgt > maxhgt) { - maxhgt = hgt; - rootn = k; - } - } - int secondn = -1; - double secondhgt = 0.0; - for (int k = 1; k < order.length; k += 2) { - if (k != rootn) { - double hgt = diphist.getSlidableNodeHeight(order[k]); - if (hgt > secondhgt) { - secondhgt = hgt; - secondn = k; - } - } - } - int leftmostdip = -1; - int rightmostdip = -1; - for (int k = 0; k < order.length; k += 2) { - if (diphist.tipIsDiploidTip(order[k])) { - if (leftmostdip < 0) { - leftmostdip = k; - } - rightmostdip = k; - } - } - if (slidingn == rootn && (secondn < leftmostdip || secondn > rightmostdip)) { - rootrange.lowerlimit = diphist.getSlidableNodeHeight(order[secondn]); - } - if (slidingn < leftmostdip || slidingn > rightmostdip) { - rootrange.upperlimit = diphist.getSlidableNodeHeight(order[rootn]); - } - return rootrange; - - } - - - private void operateOneNodeInDiploidHistory(int which, double factor) { - apspnet.beginNetworkEdit(); - int slidingn = 2 * which + 1; - AlloppDiploidHistory diphist = apspnet.getDiploidHistory(); - - NodeRef[] order = SlidableTree.Utils.mnlCanonical(diphist); - - // Find the time of the most recent gene coalescence which - // has (species,sequence)'s to left and right of this node. - FixedBitSet left = apsp.speciesseqEmptyUnion(); - FixedBitSet right = apsp.speciesseqEmptyUnion(); - for (int k = 0; k < slidingn; k += 2) { - FixedBitSet u = apspnet.calculateDipHistTipUnion(order[k]); - left.union(u); - } - for (int k = slidingn + 1; k < order.length; k += 2) { - FixedBitSet u = apspnet.calculateDipHistTipUnion(order[k]); - right.union(u); - } - double genelimit = apsp.spseqUpperBound(left, right); - - // find limit due to hyb-tips - must be bigger than adjacent heights - // Note that adjacent nodes in order[] are tips; if they are not hyb-tips - // they have height zero anyway. - double hybtiplimit = 0.0; - if (slidingn-1 >= 0) { - hybtiplimit = Math.max(hybtiplimit, diphist.getSlidableNodeHeight(order[slidingn-1])); - } - if (slidingn+1 < order.length) { - hybtiplimit = Math.max(hybtiplimit, diphist.getSlidableNodeHeight(order[slidingn+1])); - } - RootHeightRange rootrange = new RootHeightRange(0.0, Double.MAX_VALUE); - if (apspnet.getDiploidRootIsRoot()) { - rootrange = findRootRangeForDiploidRootIsRoot(diphist, order, slidingn); - } - final double upperlimit = Math.min(genelimit, rootrange.upperlimit); - final double lowerlimit = Math.max(hybtiplimit, rootrange.lowerlimit); - - // On direct call, factor==0.0 and use limit. Else use passed in scaling factor - double newHeight = -1.0; - if( factor > 0 ) { - newHeight = diphist.getSlidableNodeHeight(order[slidingn]) * factor; - } else { - newHeight = MathUtils.uniform(lowerlimit, upperlimit); - } - - assert diphist.diphistOK(apspnet.getDiploidRootIsRoot()); - final NodeRef node = order[slidingn]; - diphist.setSlidableNodeHeight(node, newHeight); - SlidableTree.Utils.mnlReconstruct(diphist, order); - if (!diphist.diphistOK(apspnet.getDiploidRootIsRoot())) { - System.out.println("BUG in operateOneNodeInDiploidHistory()"); - } - assert diphist.diphistOK(apspnet.getDiploidRootIsRoot()); - apspnet.endNetworkEdit(); - } - -} diff --git a/src/dr/evomodel/alloppnet/operators/AlloppSequenceReassignment.java b/src/dr/evomodel/alloppnet/operators/AlloppSequenceReassignment.java deleted file mode 100644 index 9c7b95e391..0000000000 --- a/src/dr/evomodel/alloppnet/operators/AlloppSequenceReassignment.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * AlloppSequenceReassignment.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.alloppnet.operators; - -import dr.evolution.util.Taxon; -import dr.evomodel.alloppnet.speciation.AlloppLeggedTree; -import dr.evomodel.alloppnet.speciation.AlloppSpeciesBindings; -import dr.evomodel.alloppnet.speciation.AlloppSpeciesNetworkModel; -import dr.evomodel.alloppnet.parsers.AlloppSequenceReassignmentParser; -import dr.inference.operators.SimpleMCMCOperator; -import dr.math.MathUtils; - -import java.util.ArrayList; - - -/** - * - * @author Graham Jones - * Date: 01/07/2011 - */ -public class AlloppSequenceReassignment extends SimpleMCMCOperator { - - private final AlloppSpeciesNetworkModel apspnet; - private final AlloppSpeciesBindings apsp; - - - public AlloppSequenceReassignment(AlloppSpeciesNetworkModel apspnet, AlloppSpeciesBindings apsp, double weight) { - this.apspnet = apspnet; - this.apsp = apsp; - setWeight(weight); - } - - - public String getPerformanceSuggestion() { - return "None"; - } - - @Override - public String getOperatorName() { - return AlloppSequenceReassignmentParser.SEQUENCE_REASSIGNMENT + "(" + apspnet.getId() + - "," + apsp.getId() + ")"; - } - - @Override - public double doOperation() { - apspnet.beginNetworkEdit(); - - if (MathUtils.nextInt(10) == 0) { - int tt = MathUtils.nextInt(apspnet.getNumberOfTetraTrees()); - AlloppLeggedTree ttree = apspnet.getTetraploidTree(tt); - ArrayList sptxs = ttree.getSpeciesTaxons(); - for (Taxon tx : sptxs) { - int spi = apsp.apspeciesId2index(tx.getId()); - apsp.flipAssignmentsForAllGenesOneSpecies(spi); - } - apspnet.flipLegsOfTetraTree(tt); - } else { - if (MathUtils.nextInt(2) == 0) { - apsp.permuteOneSpeciesOneIndivForOneGene(); - } else { - apsp.permuteSetOfIndivsForOneGene(); - } - } - - - apspnet.endNetworkEdit(); - assert apspnet.alloppspeciesnetworkOK(); - return 0; - } - -} - - diff --git a/src/dr/evomodel/alloppnet/operators/MulTreeNodeSlide.java b/src/dr/evomodel/alloppnet/operators/MulTreeNodeSlide.java deleted file mode 100644 index 8e9eedfcd5..0000000000 --- a/src/dr/evomodel/alloppnet/operators/MulTreeNodeSlide.java +++ /dev/null @@ -1,248 +0,0 @@ -/* - * MulTreeNodeSlide.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.alloppnet.operators; - -import dr.evolution.tree.NodeRef; -import dr.evolution.tree.Tree; -import dr.evomodel.alloppnet.speciation.MulSpeciesTreeModel; -import dr.evomodel.alloppnet.speciation.MulSpeciesBindings; -import dr.evomodelxml.operators.TreeNodeSlideParser; -import dr.inference.model.Parameter; -import dr.inference.operators.SimpleMCMCOperator; -import dr.math.MathUtils; -import jebl.util.FixedBitSet; - -import java.util.Arrays; - -/** - * An operator on a multiply labelled species tree based on the ideas of Mau et all. Very similar to - * JH's TreeNodeSlide. - * - * - * Bayesian Phylogenetic Inference via Markov Chain Monte Carlo Methods - * - * @author Joseph Heled, Graham Jones - * Date: 21/12/2011 - */ -public class MulTreeNodeSlide extends SimpleMCMCOperator { - - private final MulSpeciesTreeModel multree; - private final MulSpeciesBindings species; - - private final int[] preOrderIndexBefore; - private final int[] preOrderIndexAfter; - - public MulTreeNodeSlide(MulSpeciesTreeModel tree, MulSpeciesBindings species /*, boolean outgroupOnly*/, double weight) { - this.multree = tree; - this.species = species; - // this.outgroupOnly = outgroupOnly; - - preOrderIndexBefore = new int[tree.getNodeCount()]; - Arrays.fill(preOrderIndexBefore, -1); - - preOrderIndexAfter= new int[tree.getNodeCount()]; - Arrays.fill(preOrderIndexAfter, -1); - - setWeight(weight); - } - - public String getPerformanceSuggestion() { - return "none"; - } - - public String getOperatorName() { - return TreeNodeSlideParser.TREE_NODE_REHEIGHT + "(" + multree.getId() + "," + species.getId() + ")"; - } - - public double doOperation() { - operateOneNode(0.0); - return 0; - } - - - - public void operateOneNode(final double factor) { - -// #print "operate: tree", ut.treerep(t) - // if( verbose) System.out.println(" Mau at start: " + tree.getSimpleTree()); - - final int count = multree.getExternalNodeCount(); - assert count == species.nSpSeqs(); - - NodeRef[] order = new NodeRef[2 * count - 1]; - boolean[] swapped = new boolean[count-1]; - mauCanonical(multree, order, swapped); - - // internal node to change - // count-1 - number of internal nodes - int which = MathUtils.nextInt(count - 1); - - FixedBitSet left = new FixedBitSet(count); - FixedBitSet right = new FixedBitSet(count); - - for(int k = 0; k < 2*which+1; k += 2) { - left.set(multree.speciesIndex(order[k])); - } - - for(int k = 2*(which+1); k < 2*count; k += 2) { - right.set(multree.speciesIndex(order[k])); - } - - double newHeight; - - if( factor > 0 ) { - newHeight = multree.getNodeHeight(order[2*which+1]) * factor; - } else { - final double limit = species.speciationUpperBound(left, right); - newHeight = MathUtils.nextDouble() * limit; - } - - multree.beginTreeEdit(); - - multree.setPreorderIndices(preOrderIndexBefore); - - final NodeRef node = order[2 * which + 1]; - - multree.setNodeHeight(node, newHeight); - - mauReconstruct(multree, order, swapped); - - // restore pre-order of pops - - { - multree.setPreorderIndices(preOrderIndexAfter); - - double[] splitPopValues = null; - - for(int k = 0; k < preOrderIndexBefore.length; ++k) { - final int b = preOrderIndexBefore[k]; - if( b >= 0 ) { - final int a = preOrderIndexAfter[k]; - if( a != b ) { - //if( verbose) System.out.println("pops: " + a + " <- " + b); - - final Parameter p1 = multree.sppSplitPopulations; - if( splitPopValues == null ) { - splitPopValues = p1.getParameterValues(); - } - - if( multree.constPopulation() ) { - p1.setParameterValue(count + a, splitPopValues[count + b]); - } else { - for(int i = 0; i < 2; ++i) { - p1.setParameterValue(count + 2*a + i, splitPopValues[count + 2*b + i]); - } - } - } - } - } - } - - multree.endTreeEdit(); - } - - - /** - * Obtain an ordering of tree tips from randomly swaping the children order in internal nodes. - * - * @param tree tree to create order from - * @param order Nodes in their random order (only odd indices are filled) - * @param wasSwapped true if internal node was swapped - */ - static private void mauCanonical(Tree tree, NodeRef[] order, boolean[] wasSwapped) { - mauCanonicalSub(tree, tree.getRoot(), 0, order, wasSwapped); - } - - static private 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; - } - - static private void mauReconstruct(MulSpeciesTreeModel tree, NodeRef[] order, boolean[] swapped) { - final NodeRef root = mauReconstructSub(tree, 0, swapped.length, order, swapped); - if( tree.getRoot() != root ) { - tree.setRoot(root); - } - } - - static private NodeRef mauReconstructSub(MulSpeciesTreeModel tree, int from, int to, NodeRef[] order, boolean[] wasSwaped) { - if( from == to ) { - return order[2*from]; - } - - int rootIndex = -1; - { - double h = -1; - - for(int i = from; i < to; ++i) { - final double v = tree.getNodeHeight(order[2 * i + 1]); - if( h < v ) { - h = v; - rootIndex = i; - } - } - } - - final NodeRef root = order[2 * rootIndex + 1]; - - final NodeRef lchild = tree.getChild(root, 0); - final NodeRef rchild = tree.getChild(root, 1); - - NodeRef lTargetChild = mauReconstructSub(tree, from, rootIndex, order, wasSwaped); - NodeRef rTargetChild = mauReconstructSub(tree, rootIndex+1, to, order, wasSwaped); - - if( wasSwaped[rootIndex] ) { - NodeRef z = lTargetChild; - lTargetChild = rTargetChild; - rTargetChild = z; - } - - if( lchild != lTargetChild ) { - tree.replaceChild(root, lchild, lTargetChild); - } - - if( rchild != rTargetChild ) { - tree.replaceChild(root, rchild, rTargetChild); - } - - return root; - } - -} diff --git a/src/dr/evomodel/alloppnet/operators/MulTreeSequenceReassignment.java b/src/dr/evomodel/alloppnet/operators/MulTreeSequenceReassignment.java deleted file mode 100644 index 8969f351a4..0000000000 --- a/src/dr/evomodel/alloppnet/operators/MulTreeSequenceReassignment.java +++ /dev/null @@ -1,83 +0,0 @@ - -/* - * MulTreeSequenceReassignment.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.alloppnet.operators; - -import dr.evomodel.alloppnet.speciation.MulSpeciesBindings; -import dr.evomodel.alloppnet.speciation.MulSpeciesTreeModel; -import dr.evomodel.alloppnet.parsers.MulTreeSequenceReassignmentParser; -import dr.inference.operators.SimpleMCMCOperator; -import dr.math.MathUtils; - - -/** - * Changes sequence assignments for one gene, one or more individuals. - * Very similar to AlloppSequenceReassignment. - * - * @author Graham Jones - * Date: 20/12/2011 - */ -public class MulTreeSequenceReassignment extends SimpleMCMCOperator { - - private final MulSpeciesTreeModel multree; - private final MulSpeciesBindings mulspb; - - - public MulTreeSequenceReassignment(MulSpeciesTreeModel multree, MulSpeciesBindings mulspb, double weight) { - this.multree = multree; - this.mulspb = mulspb; - setWeight(weight); - } - - - public String getPerformanceSuggestion() { - return "None"; - } - - @Override - public String getOperatorName() { - return MulTreeSequenceReassignmentParser.MULTREE_SEQUENCE_REASSIGNMENT + "(" + multree.getId() + - "," + mulspb.getId() + ")"; - } - - @Override - public double doOperation() { - multree.beginTreeEdit(); - if (MathUtils.nextInt(2) == 0) { - mulspb.permuteOneSpeciesOneIndivForOneGene(); - } else { - mulspb.permuteSetOfIndivsForOneGene(); - } - - multree.endTreeEdit(); - return 0; - } - -} - - diff --git a/src/dr/evomodel/alloppnet/package-info.java b/src/dr/evomodel/alloppnet/package-info.java deleted file mode 100644 index 95aac0cff0..0000000000 --- a/src/dr/evomodel/alloppnet/package-info.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * package-info.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -/** - * dr.evomodel.alloppnet - * - * @author Graham Jones - *

- * AllopNet - *

- */ -package dr.evomodel.alloppnet; \ No newline at end of file diff --git a/src/dr/evomodel/alloppnet/parsers/AlloppChangeNumHybridizationsParser.java b/src/dr/evomodel/alloppnet/parsers/AlloppChangeNumHybridizationsParser.java deleted file mode 100644 index e41adebc5f..0000000000 --- a/src/dr/evomodel/alloppnet/parsers/AlloppChangeNumHybridizationsParser.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * AlloppChangeNumHybridizationsParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.alloppnet.parsers; - -import dr.evomodel.alloppnet.operators.AlloppChangeNumHybridizations; -import dr.evomodel.alloppnet.speciation.AlloppSpeciesBindings; -import dr.evomodel.alloppnet.speciation.AlloppSpeciesNetworkModel; -import dr.inference.operators.MCMCOperator; -import dr.xml.*; - -/** - * Created with IntelliJ IDEA. - * User: Graham - * Date: 22/07/12 - * Time: 11:24 - */ -public class AlloppChangeNumHybridizationsParser extends AbstractXMLObjectParser { - - public static final String CHANGE_NUM_HYBRIDIZATIONS = "changeNumHybridizations"; - - - public String getParserName() { - return CHANGE_NUM_HYBRIDIZATIONS; - } - - @Override - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - AlloppSpeciesBindings apsp = (AlloppSpeciesBindings) xo.getChild(AlloppSpeciesBindings.class); - AlloppSpeciesNetworkModel apspnet = (AlloppSpeciesNetworkModel) xo.getChild(AlloppSpeciesNetworkModel.class); - if (apspnet.getOneHybridization()) { - throw new XMLParseException("oneHybridization is set to true but there is a changeNumHybridizations operator"); - } - - final double weight = xo.getDoubleAttribute(MCMCOperator.WEIGHT); - return new AlloppChangeNumHybridizations(apspnet, apsp, weight); - } - - @Override - public XMLSyntaxRule[] getSyntaxRules() { - return new XMLSyntaxRule[]{ - AttributeRule.newDoubleRule(MCMCOperator.WEIGHT), - new ElementRule(AlloppSpeciesBindings.class), - new ElementRule(AlloppSpeciesNetworkModel.class) - }; - } - - @Override - public String getParserDescription() { - return "Operator which changes the number of tetraploid subtrees (hybridizations) by merging and splitting them."; - - } - - @Override - public Class getReturnType() { - return AlloppChangeNumHybridizations.class; - } - - - -} diff --git a/src/dr/evomodel/alloppnet/parsers/AlloppHybPopSizesScaleParser.java b/src/dr/evomodel/alloppnet/parsers/AlloppHybPopSizesScaleParser.java deleted file mode 100644 index e51deb8105..0000000000 --- a/src/dr/evomodel/alloppnet/parsers/AlloppHybPopSizesScaleParser.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * AlloppHybPopSizesScaleParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.alloppnet.parsers; - -import dr.evomodel.alloppnet.operators.AlloppHybPopSizesScale; -import dr.evomodel.alloppnet.speciation.AlloppSpeciesBindings; -import dr.evomodel.alloppnet.speciation.AlloppSpeciesNetworkModel; -import dr.inference.operators.MCMCOperator; -import dr.inferencexml.operators.ScaleOperatorParser; -import dr.xml.*; - -/** - * Created with IntelliJ IDEA. - * User: Graham - * Date: 03/08/12 - */ -public class AlloppHybPopSizesScaleParser extends AbstractXMLObjectParser { - - public static final String HYB_POP_SIZES_SCALE = "hybPopSizesScaleOperator"; - - - public String getParserName() { - return HYB_POP_SIZES_SCALE; - } - - @Override - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - AlloppSpeciesBindings apsp = (AlloppSpeciesBindings) xo.getChild(AlloppSpeciesBindings.class); - AlloppSpeciesNetworkModel apspnet = (AlloppSpeciesNetworkModel) xo.getChild(AlloppSpeciesNetworkModel.class); - - final double weight = xo.getDoubleAttribute(MCMCOperator.WEIGHT); - final double scalingfactor = xo.getDoubleAttribute(ScaleOperatorParser.SCALE_FACTOR); - return new AlloppHybPopSizesScale(apspnet, apsp, scalingfactor, weight); - } - - @Override - public XMLSyntaxRule[] getSyntaxRules() { - return new XMLSyntaxRule[]{ - AttributeRule.newDoubleRule(MCMCOperator.WEIGHT), - AttributeRule.newDoubleRule(ScaleOperatorParser.SCALE_FACTOR), - new ElementRule(AlloppSpeciesBindings.class), - new ElementRule(AlloppSpeciesNetworkModel.class) - }; - } - - @Override - public String getParserDescription() { - return "Operator which scales the population size of a newly formed hybrid."; - - } - - @Override - public Class getReturnType() { - return AlloppHybPopSizesScale.class; - } - -} diff --git a/src/dr/evomodel/alloppnet/parsers/AlloppMSCoalescentParser.java b/src/dr/evomodel/alloppnet/parsers/AlloppMSCoalescentParser.java deleted file mode 100644 index 348238c8c8..0000000000 --- a/src/dr/evomodel/alloppnet/parsers/AlloppMSCoalescentParser.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * AlloppMSCoalescentParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.alloppnet.parsers; - -import dr.evomodel.alloppnet.speciation.AlloppMSCoalescent; -import dr.evomodel.alloppnet.speciation.AlloppSpeciesBindings; -import dr.evomodel.alloppnet.speciation.AlloppSpeciesNetworkModel; -import dr.xml.AbstractXMLObjectParser; -import dr.xml.ElementRule; -import dr.xml.XMLObject; -import dr.xml.XMLParseException; -import dr.xml.XMLSyntaxRule; - -/** - * - * @author Graham Jones - * Date: 01/07/2011 - */ - -public class AlloppMSCoalescentParser extends AbstractXMLObjectParser { - - public static final String ALLOPPMSCOALESCENT = "apspCoalescent"; - - - public String getParserName() { - return ALLOPPMSCOALESCENT; - } - - - - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - final AlloppSpeciesBindings apsp = (AlloppSpeciesBindings) xo.getChild(AlloppSpeciesBindings.class); - final AlloppSpeciesNetworkModel apspnetwork = - (AlloppSpeciesNetworkModel) xo.getChild(AlloppSpeciesNetworkModel.class); - return new AlloppMSCoalescent(apsp, apspnetwork); - } - - public XMLSyntaxRule[] getSyntaxRules() { - return new XMLSyntaxRule[]{ - new ElementRule(AlloppSpeciesBindings.class), - new ElementRule(AlloppSpeciesNetworkModel.class), - }; - } - - - - @Override - public String getParserDescription() { - return "Likelihood of a set of gene trees embedded in a allopolyploid species network."; - } - - @Override - public Class getReturnType() { - return AlloppMSCoalescent.class; - } - -} diff --git a/src/dr/evomodel/alloppnet/parsers/AlloppMoveLegsParser.java b/src/dr/evomodel/alloppnet/parsers/AlloppMoveLegsParser.java deleted file mode 100644 index aba21ee9dc..0000000000 --- a/src/dr/evomodel/alloppnet/parsers/AlloppMoveLegsParser.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * AlloppMoveLegsParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.alloppnet.parsers; - -import dr.evomodel.alloppnet.operators.AlloppMoveLegs; -import dr.evomodel.alloppnet.speciation.AlloppSpeciesBindings; -import dr.evomodel.alloppnet.speciation.AlloppSpeciesNetworkModel; -import dr.inference.operators.MCMCOperator; -import dr.xml.AbstractXMLObjectParser; -import dr.xml.AttributeRule; -import dr.xml.ElementRule; -import dr.xml.XMLObject; -import dr.xml.XMLParseException; -import dr.xml.XMLSyntaxRule; - -/** - * - * @author Graham Jones - * Date: 31/08/2011 - */ - -public class AlloppMoveLegsParser extends AbstractXMLObjectParser { - public static final String MOVE_LEGS = "moveLegs"; - - - public String getParserName() { - return MOVE_LEGS; - } - - @Override - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - AlloppSpeciesBindings apsp = (AlloppSpeciesBindings) xo.getChild(AlloppSpeciesBindings.class); - AlloppSpeciesNetworkModel apspnet = (AlloppSpeciesNetworkModel) xo.getChild(AlloppSpeciesNetworkModel.class); - - final double weight = xo.getDoubleAttribute(MCMCOperator.WEIGHT); - return new AlloppMoveLegs(apspnet, apsp, weight); - } - - @Override - public XMLSyntaxRule[] getSyntaxRules() { - return new XMLSyntaxRule[]{ - AttributeRule.newDoubleRule(MCMCOperator.WEIGHT), - new ElementRule(AlloppSpeciesBindings.class), - new ElementRule(AlloppSpeciesNetworkModel.class) - }; - } - - @Override - public String getParserDescription() { - return "Operator which changes the way a tetraploid subtree joins the diploid tree."; - - } - - @Override - public Class getReturnType() { - return AlloppMoveLegs.class; - } - -} - - - diff --git a/src/dr/evomodel/alloppnet/parsers/AlloppNetworkNodeSlideParser.java b/src/dr/evomodel/alloppnet/parsers/AlloppNetworkNodeSlideParser.java deleted file mode 100644 index d694ce6517..0000000000 --- a/src/dr/evomodel/alloppnet/parsers/AlloppNetworkNodeSlideParser.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * AlloppNetworkNodeSlideParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.alloppnet.parsers; - -import dr.evomodel.alloppnet.operators.AlloppNetworkNodeSlide; -import dr.evomodel.alloppnet.speciation.AlloppSpeciesBindings; -import dr.evomodel.alloppnet.speciation.AlloppSpeciesNetworkModel; -import dr.inference.operators.MCMCOperator; -import dr.xml.AbstractXMLObjectParser; -import dr.xml.AttributeRule; -import dr.xml.ElementRule; -import dr.xml.XMLObject; -import dr.xml.XMLParseException; -import dr.xml.XMLSyntaxRule; - -/** - * - * @author Graham Jones - * Date: 01/07/2011 - */ - -/* - - - - - - -*/ - -public class AlloppNetworkNodeSlideParser extends AbstractXMLObjectParser { - public static final String NETWORK_NODE_REHEIGHT = "networkNodeReHeight"; - - - public String getParserName() { - return NETWORK_NODE_REHEIGHT; - } - - @Override - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - AlloppSpeciesBindings apsp = (AlloppSpeciesBindings) xo.getChild(AlloppSpeciesBindings.class); - AlloppSpeciesNetworkModel apspnet = (AlloppSpeciesNetworkModel) xo.getChild(AlloppSpeciesNetworkModel.class); - - final double weight = xo.getDoubleAttribute(MCMCOperator.WEIGHT); - return new AlloppNetworkNodeSlide(apspnet, apsp, weight); - } - - @Override - public XMLSyntaxRule[] getSyntaxRules() { - return new XMLSyntaxRule[]{ - AttributeRule.newDoubleRule(MCMCOperator.WEIGHT), - new ElementRule(AlloppSpeciesBindings.class), - new ElementRule(AlloppSpeciesNetworkModel.class) - }; - } - - @Override - public String getParserDescription() { - return "Operator for allopolyploid species network: transforms network without breaking embedding of gene trees."; - } - - @Override - public Class getReturnType() { - return AlloppNetworkNodeSlide.class; - } - -} diff --git a/src/dr/evomodel/alloppnet/parsers/AlloppNetworkPriorModelParser.java b/src/dr/evomodel/alloppnet/parsers/AlloppNetworkPriorModelParser.java deleted file mode 100644 index 0821649ba4..0000000000 --- a/src/dr/evomodel/alloppnet/parsers/AlloppNetworkPriorModelParser.java +++ /dev/null @@ -1,180 +0,0 @@ -/* - * AlloppNetworkPriorModelParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.alloppnet.parsers; - -import dr.evolution.util.Units; -import dr.evomodel.alloppnet.speciation.AlloppNetworkPriorModel; -import dr.evoxml.util.XMLUnits; -import dr.inference.model.Parameter; -import dr.inference.distribution.ParametricDistributionModel; -import dr.xml.AbstractXMLObjectParser; -import dr.xml.ElementRule; -import dr.xml.XMLObject; -import dr.xml.XMLParseException; -import dr.xml.XMLSyntaxRule; - - -/** - * - * @author Graham Jones - * Date: 01/07/2011 - */ - -/* - - - - - - - - - - - 4 - - - - - - - - - - 2 - - - - - - - - - - 1 - - - - - - - -*/ -public class AlloppNetworkPriorModelParser extends AbstractXMLObjectParser { - - public static final String ALLOPPNETWORKPRIORMODEL = "alloppNetworkPriorModel"; - public static final String EVENTRATE = "eventRate"; - public static final String POPULATION_SCALING_FACTOR = "populationScalingFactor"; - public static final String TIP_POPULATION_DISTRIBUTION = "tipPopulationDistribution"; - public static final String ROOT_POPULATION_DISTRIBUTION = "rootPopulationDistribution"; - public static final String HYBRID_POPULATION_DISTRIBUTION = "hybridPopulationDistribution"; - - - public String getParserName() { - return ALLOPPNETWORKPRIORMODEL; - } - - - - @Override - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - final Units.Type units = XMLUnits.Utils.getUnitsAttr(xo); - final XMLObject erXo = xo.getChild(EVENTRATE); - final Parameter eventrate = (Parameter) erXo.getChild(Parameter.class); - final XMLObject psfXo = xo.getChild(POPULATION_SCALING_FACTOR); - final Parameter popscalingfactor = (Parameter) psfXo.getChild(Parameter.class); - final XMLObject tpdXo = xo.getChild(TIP_POPULATION_DISTRIBUTION); - ParametricDistributionModel tippopmodel = (ParametricDistributionModel) tpdXo.getChild(ParametricDistributionModel.class); - final XMLObject rpdXo = xo.getChild(ROOT_POPULATION_DISTRIBUTION); - ParametricDistributionModel rootpopmodel = (ParametricDistributionModel) rpdXo.getChild(ParametricDistributionModel.class); - final XMLObject hpdXo = xo.getChild(HYBRID_POPULATION_DISTRIBUTION); - ParametricDistributionModel hybpopmodel = (ParametricDistributionModel) hpdXo.getChild(ParametricDistributionModel.class); - return new AlloppNetworkPriorModel(eventrate, popscalingfactor, tippopmodel, rootpopmodel, hybpopmodel, units); - } - - - - private XMLSyntaxRule[] eventrateRules() { - return new XMLSyntaxRule[]{ - new ElementRule(Parameter.class) - }; - } - - - private XMLSyntaxRule[] popscalingfactorRules() { - return new XMLSyntaxRule[]{ - new ElementRule(Parameter.class) - }; - } - - - private XMLSyntaxRule[] tippopmodelRules() { - return new XMLSyntaxRule[]{ - new ElementRule(ParametricDistributionModel.class) - }; - } - - - - private XMLSyntaxRule[] rootpopmodelRules() { - return new XMLSyntaxRule[]{ - new ElementRule(ParametricDistributionModel.class) - }; - } - - - private XMLSyntaxRule[] hybpopmodelRules() { - return new XMLSyntaxRule[]{ - new ElementRule(ParametricDistributionModel.class) - }; - } - - - @Override - public XMLSyntaxRule[] getSyntaxRules() { - return new XMLSyntaxRule[]{ - XMLUnits.SYNTAX_RULES[0], - new ElementRule(EVENTRATE, eventrateRules()), - new ElementRule(POPULATION_SCALING_FACTOR, popscalingfactorRules()), - new ElementRule(TIP_POPULATION_DISTRIBUTION, tippopmodelRules()), - new ElementRule(ROOT_POPULATION_DISTRIBUTION, rootpopmodelRules()), - new ElementRule(HYBRID_POPULATION_DISTRIBUTION, hybpopmodelRules()) - }; - } - - @Override - public String getParserDescription() { - return "Model for speciation, extinction, hybridization in allopolyploid network."; - } - - @Override - public Class getReturnType() { - return AlloppNetworkPriorModel.class; - } - -} diff --git a/src/dr/evomodel/alloppnet/parsers/AlloppNetworkPriorParser.java b/src/dr/evomodel/alloppnet/parsers/AlloppNetworkPriorParser.java deleted file mode 100644 index 7d0deefbfb..0000000000 --- a/src/dr/evomodel/alloppnet/parsers/AlloppNetworkPriorParser.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * AlloppNetworkPriorParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.alloppnet.parsers; - -import dr.evomodel.alloppnet.speciation.AlloppNetworkPrior; -import dr.evomodel.alloppnet.speciation.AlloppNetworkPriorModel; -import dr.evomodel.alloppnet.speciation.AlloppSpeciesNetworkModel; -import dr.xml.*; - - -/** - * - * @author Graham Jones - * Date: 01/07/2011 - */ - - -public class AlloppNetworkPriorParser extends AbstractXMLObjectParser { - - public static final String APSPNETWORKPRIOR = "apspNetworkPrior"; - public static final String MODEL = "model"; - public static final String APSPNETWORK = "apspNetwork"; - - - public String getParserName() { - return APSPNETWORKPRIOR; - } - - -/* - - - - - - - - -*/ - @Override - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - final XMLObject mxo = xo.getChild(MODEL); - final AlloppNetworkPriorModel anpm = (AlloppNetworkPriorModel) mxo.getChild(AlloppNetworkPriorModel.class); - final XMLObject asnmxo = xo.getChild(APSPNETWORK); - final AlloppSpeciesNetworkModel asnm = (AlloppSpeciesNetworkModel) asnmxo.getChild(AlloppSpeciesNetworkModel.class); - return new AlloppNetworkPrior(anpm, asnm); - } - - private XMLSyntaxRule[] modelRules() { - return new XMLSyntaxRule[]{ - new ElementRule(AlloppNetworkPriorModel.class) - }; - - } - - private XMLSyntaxRule[] asnmRules() { - return new XMLSyntaxRule[]{ - new ElementRule(AlloppSpeciesNetworkModel.class) - }; - - } - - @Override - public XMLSyntaxRule[] getSyntaxRules() { - return new XMLSyntaxRule[]{ - new ElementRule(MODEL, modelRules()), - new ElementRule(APSPNETWORK, asnmRules()), - - }; - } - - @Override - public String getParserDescription() { - return "Prior for an allopolyploid species network."; - } - - @Override - public Class getReturnType() { - return AlloppNetworkPrior.class; - } - -} diff --git a/src/dr/evomodel/alloppnet/parsers/AlloppNumHybsStatisticParser.java b/src/dr/evomodel/alloppnet/parsers/AlloppNumHybsStatisticParser.java deleted file mode 100644 index e87b5709b5..0000000000 --- a/src/dr/evomodel/alloppnet/parsers/AlloppNumHybsStatisticParser.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * AlloppNumHybsStatisticParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.alloppnet.parsers; - -import dr.evomodel.alloppnet.speciation.AlloppNumHybsStatistic; -import dr.evomodel.alloppnet.speciation.AlloppSpeciesNetworkModel; - -import dr.xml.*; - -/** - * @author Graham Jones - * Date: 08/10/2012 - */ -public class AlloppNumHybsStatisticParser extends AbstractXMLObjectParser { - public static final String NUMHYBS_STATISTIC = "alloppNumHybsStatistic"; - public static final String APSPNETWORK = "apspNetwork"; - - public String getParserName() { - return NUMHYBS_STATISTIC; - } - - - @Override - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - final XMLObject asnmxo = xo.getChild(APSPNETWORK); - AlloppSpeciesNetworkModel aspnet = (AlloppSpeciesNetworkModel) asnmxo.getChild(AlloppSpeciesNetworkModel.class); - return new AlloppNumHybsStatistic(aspnet); - } - - - - private XMLSyntaxRule[] asnmRules() { - return new XMLSyntaxRule[]{ - new ElementRule(AlloppSpeciesNetworkModel.class) - }; - - } - - @Override - public XMLSyntaxRule[] getSyntaxRules() { - return new XMLSyntaxRule[]{ - new ElementRule(APSPNETWORK, asnmRules()), - - }; - } - - - - @Override - public String getParserDescription() { - return "Statistic for number of hybridizations in allopolyploid network"; - } - - @Override - public Class getReturnType() { - return AlloppNumHybsStatistic.class; - } -} diff --git a/src/dr/evomodel/alloppnet/parsers/AlloppSequenceReassignmentParser.java b/src/dr/evomodel/alloppnet/parsers/AlloppSequenceReassignmentParser.java deleted file mode 100644 index 4bb0de8a5f..0000000000 --- a/src/dr/evomodel/alloppnet/parsers/AlloppSequenceReassignmentParser.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * AlloppSequenceReassignmentParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.alloppnet.parsers; - - -import dr.evomodel.alloppnet.operators.AlloppSequenceReassignment; -import dr.evomodel.alloppnet.speciation.AlloppSpeciesBindings; -import dr.evomodel.alloppnet.speciation.AlloppSpeciesNetworkModel; -import dr.inference.operators.MCMCOperator; -import dr.xml.AbstractXMLObjectParser; -import dr.xml.AttributeRule; -import dr.xml.ElementRule; -import dr.xml.XMLObject; -import dr.xml.XMLParseException; -import dr.xml.XMLSyntaxRule; - -/** - * - * @author Graham Jones - * Date: 01/07/2011 - */ - - -public class AlloppSequenceReassignmentParser extends AbstractXMLObjectParser { - public static final String SEQUENCE_REASSIGNMENT = "sequenceReassignment"; - - - public String getParserName() { - return SEQUENCE_REASSIGNMENT; - } - - @Override - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - AlloppSpeciesBindings apsp = (AlloppSpeciesBindings) xo.getChild(AlloppSpeciesBindings.class); - AlloppSpeciesNetworkModel apspnet = (AlloppSpeciesNetworkModel) xo.getChild(AlloppSpeciesNetworkModel.class); - - final double weight = xo.getDoubleAttribute(MCMCOperator.WEIGHT); - return new AlloppSequenceReassignment(apspnet, apsp, weight); - } - - @Override - public XMLSyntaxRule[] getSyntaxRules() { - return new XMLSyntaxRule[]{ - AttributeRule.newDoubleRule(MCMCOperator.WEIGHT), - new ElementRule(AlloppSpeciesBindings.class), - new ElementRule(AlloppSpeciesNetworkModel.class) - }; - } - - @Override - public String getParserDescription() { - return "Operator which reassigns sequences within an allopolyploid species."; - } - - @Override - public Class getReturnType() { - return AlloppSequenceReassignment.class; - } - -} diff --git a/src/dr/evomodel/alloppnet/parsers/AlloppSpeciesBindingsApSpInfoParser.java b/src/dr/evomodel/alloppnet/parsers/AlloppSpeciesBindingsApSpInfoParser.java deleted file mode 100644 index 8ae3fb677e..0000000000 --- a/src/dr/evomodel/alloppnet/parsers/AlloppSpeciesBindingsApSpInfoParser.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * AlloppSpeciesBindingsApSpInfoParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.alloppnet.parsers; - - -import dr.evomodel.alloppnet.speciation.AlloppSpeciesBindings; -import dr.xml.AbstractXMLObjectParser; -import dr.xml.AttributeRule; -import dr.xml.ElementRule; -import dr.xml.XMLObject; -import dr.xml.XMLParseException; -import dr.xml.XMLSyntaxRule; - - -/** - * - * Parses a possibly-allopolyploid species made of individual organisms. - * - * @author Graham Jones - * Date: 18/04/2011 - */ - - - -/* - * - * Parses a diploid or allopolyploid species, recording ploidy level - * and running through all individual organisms belonging to the species. - * - * Part of parsing a AlloppSpeciesBindings. - * - */ - - -public class AlloppSpeciesBindingsApSpInfoParser extends - AbstractXMLObjectParser { - public static final String APSP = "apsp"; - public static final String PLOIDYLEVEL = "ploidylevel"; - - public String getParserName() { - return APSP; - } - - @Override - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - AlloppSpeciesBindings.Individual[] individuals = - new AlloppSpeciesBindings.Individual[xo.getChildCount()]; - for (int ni = 0; ni < individuals.length; ++ni) { - individuals[ni] = (AlloppSpeciesBindings.Individual) xo.getChild(ni); - } - return new AlloppSpeciesBindings.ApSpInfo(xo.getId(), xo.getIntegerAttribute(PLOIDYLEVEL), individuals); - } - - @Override - public XMLSyntaxRule[] getSyntaxRules() { - return new XMLSyntaxRule[] { - AttributeRule.newDoubleRule(PLOIDYLEVEL), - new ElementRule(AlloppSpeciesBindings.Individual.class, 1, Integer.MAX_VALUE) - }; - } - - @Override - public String getParserDescription() { - return "A diploid or allopolyploid species made of individuals"; - } - - @Override - public Class getReturnType() { - return AlloppSpeciesBindings.ApSpInfo.class; - } - -} diff --git a/src/dr/evomodel/alloppnet/parsers/AlloppSpeciesBindingsIndividualParser.java b/src/dr/evomodel/alloppnet/parsers/AlloppSpeciesBindingsIndividualParser.java deleted file mode 100644 index e86e57f983..0000000000 --- a/src/dr/evomodel/alloppnet/parsers/AlloppSpeciesBindingsIndividualParser.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * AlloppSpeciesBindingsIndividualParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.alloppnet.parsers; - - - -import dr.evolution.util.Taxon; -import dr.evomodel.alloppnet.speciation.AlloppSpeciesBindings; -import dr.xml.AbstractXMLObjectParser; -import dr.xml.ElementRule; -import dr.xml.XMLObject; -import dr.xml.XMLParseException; -import dr.xml.XMLSyntaxRule; - - -/** - * Parses an individual from a possibly-allopolyploid species. - * - * @author Graham Jones - * Date: 18/04/2011 - */ - - -/* - * - * Parses an individual (which is a list of taxa) from a - * possibly-allopolyploid species. Part of parsing a AlloppSpeciesBindings. - * - */ - -public class AlloppSpeciesBindingsIndividualParser extends - AbstractXMLObjectParser { - public static final String INDIVIDUAL = "individual"; - - public String getParserName() { - return INDIVIDUAL; - } - - @Override - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - Taxon[] taxa = new Taxon[xo.getChildCount()]; - for (int nt = 0; nt < taxa.length; ++nt) { - taxa[nt] = (Taxon) xo.getChild(nt); - } - return new AlloppSpeciesBindings.Individual(xo.getId(), taxa); - } - - @Override - public XMLSyntaxRule[] getSyntaxRules() { - return new XMLSyntaxRule[]{ - new ElementRule(Taxon.class, 1, Integer.MAX_VALUE) - }; - } - - - @Override - public String getParserDescription() { - return "Individual specimen from a species, possibly containing multiple genomes."; - } - - @Override - public Class getReturnType() { - return AlloppSpeciesBindings.Individual.class; - } - -} - diff --git a/src/dr/evomodel/alloppnet/parsers/AlloppSpeciesBindingsParser.java b/src/dr/evomodel/alloppnet/parsers/AlloppSpeciesBindingsParser.java deleted file mode 100644 index ec8898bba7..0000000000 --- a/src/dr/evomodel/alloppnet/parsers/AlloppSpeciesBindingsParser.java +++ /dev/null @@ -1,168 +0,0 @@ -/* - * AlloppSpeciesBindingsParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.alloppnet.parsers; - -import dr.evomodel.alloppnet.speciation.AlloppSpeciesBindings; -import dr.evomodel.tree.TreeModel; -import dr.xml.*; -import java.util.ArrayList; -import java.util.List; - -/** - * Parser for list of possibly-allopolyploid species containing individuals - * in turn containing taxons (which are diploid genomes). - * - * @author Graham Jones - * Date: 18/04/2011 - */ - - - - -/* - * - * Parses something like this: - - - - - - - - - - - - - - - - - - - - - - - - ... - (more species, then genetrees) - - - */ - - -// I have adapted code from SpeciesBindingsParser. -// I changed 'ploidy' to 'popfactor' to reduce confusion with the ploidy level -// of a species which is independent of which gene is considered. -// Use of popfactors is untested. Maybe chloroplast data would use it. - - -public class AlloppSpeciesBindingsParser extends AbstractXMLObjectParser { - public static final String ALLOPPSPECIES = "alloppspecies"; - public static final String GENE_TREES = "geneTrees"; - public static final String GTREE = "gtree"; - public static final String POPFACTOR = "popfactor"; - public static final String MIN_GENENODE_HEIGHT = "minGeneNodeHeight"; - - - public String getParserName() { - return ALLOPPSPECIES; - } - - @Override - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - List apsp = new ArrayList(); - for (int k = 0; k < xo.getChildCount(); ++k) { - final Object child = xo.getChild(k); - if (child instanceof AlloppSpeciesBindings.ApSpInfo) { - apsp.add((AlloppSpeciesBindings.ApSpInfo) child); - } - } - final double mingenenodeheight = xo.getDoubleAttribute(MIN_GENENODE_HEIGHT); - final XMLObject xogt = xo.getChild(GENE_TREES); - final int nTrees = xogt.getChildCount(); - final TreeModel[] trees = new TreeModel[nTrees]; - double[] popFactors = new double[nTrees]; - - for (int nt = 0; nt < trees.length; ++nt) { - Object child = xogt.getChild(nt); - if (!(child instanceof TreeModel)) { - assert child instanceof XMLObject; - popFactors[nt] = ((XMLObject) child).getDoubleAttribute(POPFACTOR); - child = ((XMLObject) child).getChild(TreeModel.class); - - } else { - popFactors[nt] = -1; - } - trees[nt] = (TreeModel) child; - } - - try { - return new AlloppSpeciesBindings(apsp.toArray(new AlloppSpeciesBindings.ApSpInfo[apsp.size()]), - trees, mingenenodeheight, popFactors); - } catch (Error e) { - throw new XMLParseException(e.getMessage()); - } - } - - - // I have adapted code from SpeciesBindingsParser - // I changed 'Ploidy' to 'PopFactors' to reduce confusion - - // the only use I can think of for popfactors in an AlloppNetwork is chloroplast data - ElementRule treeWithPopFactors = new ElementRule(GTREE, - new XMLSyntaxRule[]{AttributeRule.newDoubleRule(POPFACTOR), - new ElementRule(TreeModel.class)}, 0, Integer.MAX_VALUE); - - - @Override - public XMLSyntaxRule[] getSyntaxRules() { - return new XMLSyntaxRule[]{ - AttributeRule.newDoubleRule(MIN_GENENODE_HEIGHT), - new ElementRule(AlloppSpeciesBindings.ApSpInfo.class, 2, Integer.MAX_VALUE), - new ElementRule(GENE_TREES, - new XMLSyntaxRule[]{ - new ElementRule(TreeModel.class, 0, Integer.MAX_VALUE), - treeWithPopFactors - }), - }; - } - - - @Override - public String getParserDescription() { - return "Binds taxa to gene trees with information about possibly allopolyploid species."; - } - - @Override - public Class getReturnType() { - return AlloppSpeciesBindings.class; - } - -} diff --git a/src/dr/evomodel/alloppnet/parsers/AlloppSpeciesNetworkModelParser.java b/src/dr/evomodel/alloppnet/parsers/AlloppSpeciesNetworkModelParser.java deleted file mode 100644 index 38d0ccd15e..0000000000 --- a/src/dr/evomodel/alloppnet/parsers/AlloppSpeciesNetworkModelParser.java +++ /dev/null @@ -1,184 +0,0 @@ -/* - * AlloppSpeciesNetworkModelParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.alloppnet.parsers; - - -import dr.evomodel.alloppnet.speciation.AlloppSpeciesBindings; -import dr.evomodel.alloppnet.speciation.AlloppSpeciesNetworkModel; -import dr.inference.model.Parameter; -import dr.inference.model.ParameterParser; -import dr.util.Attributable; -import dr.xml.*; - - -/** - * - * Parses a AlloppSpeciesNetworkModel. - * - * @author Graham Jones - * Date: 19/04/2011 - */ - - - -/* - * - * Parses a MulLabSpeciesTreeModel which might look like this. - * - - - - - - - - - - * - */ - - -/* - * 2011-07-07 decided to remove preRootHeights, and therefore these bits of code. - * (instead, incorporate into AlloppNetworkNodeSlide) - * - * - * public static final String PRE_ROOT_HEIGHTS = "preRootHeights"; - * - * - * final XMLObject prhxo = xo.getChild(PRE_ROOT_HEIGHTS); - * - * - * ParameterParser.replaceParameter(prhxo, asnm.prHeights); - * final Parameter.DefaultBounds prhbounds = - * new Parameter.DefaultBounds(Double.MAX_VALUE, 0, asnm.prHeights.getDimension()); - * asnm.prHeights.addBounds(prhbounds); - * - * private ElementRule prhElementRule() { - * return new ElementRule(PRE_ROOT_HEIGHTS, new XMLSyntaxRule[]{ - * new ElementRule(Parameter.class)}); - * } - * - * also code in AlloppSpeciesNetworkModel - * - */ - - - -public class AlloppSpeciesNetworkModelParser extends AbstractXMLObjectParser { - public static final String ALLOPPSPECIESNETWORK = "alloppSpeciesNetwork"; - public static final String ONEHYBRIDIZATION = "oneHybridization"; - public static final String DIPLOIDROOT_ISROOT = "diploidRootIsRoot"; - public static final String TIP_POPULATIONS = "tipPopulations"; - public static final String ROOT_POPULATIONS = "rootPopulations"; - public static final String HYBRID_POPULATIONS = "hybridPopulations"; - - - - - public String getParserName() { - return ALLOPPSPECIESNETWORK; - } - - @Override - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - AlloppSpeciesBindings apspb = (AlloppSpeciesBindings) xo.getChild(AlloppSpeciesBindings.class); - boolean onehyb = xo.getBooleanAttribute(ONEHYBRIDIZATION); - boolean diprootisroot = xo.getBooleanAttribute(DIPLOIDROOT_ISROOT); - - final XMLObject tippopxo = xo.getChild(TIP_POPULATIONS); - final double tippopvalue = tippopxo.getAttribute(Attributable.VALUE, 1.0); - final XMLObject rootpopxo = xo.getChild(ROOT_POPULATIONS); - final double rootpopvalue = rootpopxo.getAttribute(Attributable.VALUE, 1.0); - final XMLObject hybpopxo = xo.getChild(HYBRID_POPULATIONS); - final double hybpopvalue = hybpopxo.getAttribute(Attributable.VALUE, 1.0); - - AlloppSpeciesNetworkModel asnm = new AlloppSpeciesNetworkModel(apspb, - tippopvalue, rootpopvalue, hybpopvalue, onehyb, diprootisroot); - // don't know dimensionality until network created, so replace parameters - ParameterParser.replaceParameter(tippopxo, asnm.tippopvalues); - final Parameter.DefaultBounds tippopbounds = - new Parameter.DefaultBounds(Double.MAX_VALUE, 0, asnm.tippopvalues.getDimension()); - asnm.tippopvalues.addBounds(tippopbounds); - - ParameterParser.replaceParameter(rootpopxo, asnm.rootpopvalues); - final Parameter.DefaultBounds rootpopbounds = - new Parameter.DefaultBounds(Double.MAX_VALUE, 0, asnm.rootpopvalues.getDimension()); - asnm.rootpopvalues.addBounds(rootpopbounds); - - ParameterParser.replaceParameter(hybpopxo, asnm.logginghybpopvalues); - final Parameter.DefaultBounds hybpopbounds = - new Parameter.DefaultBounds(Double.MAX_VALUE, 0, asnm.logginghybpopvalues.getDimension()); - asnm.logginghybpopvalues.addBounds(hybpopbounds); - // note hybpopvalues are different and only work for logging. - return asnm; - } - - - private ElementRule tippopElementRule() { - return new ElementRule(TIP_POPULATIONS, new XMLSyntaxRule[]{ - AttributeRule.newDoubleRule(Attributable.VALUE, true), - new ElementRule(Parameter.class)}); - } - - private ElementRule rootpopElementRule() { - return new ElementRule(ROOT_POPULATIONS, new XMLSyntaxRule[]{ - AttributeRule.newDoubleRule(Attributable.VALUE, true), - new ElementRule(Parameter.class)}); - } - private ElementRule hybpopElementRule() { - return new ElementRule(HYBRID_POPULATIONS, new XMLSyntaxRule[]{ - AttributeRule.newDoubleRule(Attributable.VALUE, true), - new ElementRule(Parameter.class)}); - } - - - - @Override - public XMLSyntaxRule[] getSyntaxRules() { - return new XMLSyntaxRule[]{ - AttributeRule.newBooleanRule(ONEHYBRIDIZATION, true), - AttributeRule.newBooleanRule(DIPLOIDROOT_ISROOT, true), - new ElementRule(AlloppSpeciesBindings.class), - tippopElementRule(), - rootpopElementRule(), - hybpopElementRule() - }; - } - - @Override - public String getParserDescription() { - return "Species network with population sizes along branches"; - } - - @Override - public Class getReturnType() { - return AlloppSpeciesNetworkModel.class; - } - -} diff --git a/src/dr/evomodel/alloppnet/parsers/BirthDeathCollapseModelParser.java b/src/dr/evomodel/alloppnet/parsers/BirthDeathCollapseModelParser.java deleted file mode 100644 index 06d14d7f77..0000000000 --- a/src/dr/evomodel/alloppnet/parsers/BirthDeathCollapseModelParser.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * BirthDeathCollapseModelParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.alloppnet.parsers; - -/** - * @author Graham Jones - * Date: 01/09/2013 - */ - - -import dr.evolution.tree.Tree; -import dr.evolution.util.Units; -import dr.evomodel.alloppnet.speciation.BirthDeathCollapseModel; -import dr.evoxml.util.XMLUnits; -import dr.inference.model.Parameter; -import dr.xml.*; - - -import static dr.xml.AttributeRule.newDoubleRule; - - -public class BirthDeathCollapseModelParser extends AbstractXMLObjectParser { - - public static final String BIRTH_DEATH_COLLAPSE_MODEL = "birthDeathCollapseModel"; - - public static final String COLLAPSE_HEIGHT = "collapseHeight"; - - public static final String TREE = "speciesTree"; - - public static final String BIRTHDIFF_RATE = "birthMinusDeathRate"; - public static final String RELATIVE_DEATH_RATE = "relativeDeathRate"; - public static final String ORIGIN_HEIGHT = "originHeight"; - public static final String COLLAPSE_WEIGHT = "collapseWeight"; - - - - public String getParserName() { - return BIRTH_DEATH_COLLAPSE_MODEL; - } - - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - final Units.Type units = XMLUnits.Utils.getUnitsAttr(xo); - - final double collH = xo.getDoubleAttribute(COLLAPSE_HEIGHT); - - XMLObject cxo = xo.getChild(TREE); - final Tree tree = (Tree) cxo.getChild(Tree.class); - - final Parameter birthMinusDeath = (Parameter) xo.getElementFirstChild(BIRTHDIFF_RATE); - final Parameter relativeDeathRate = (Parameter) xo.getElementFirstChild(RELATIVE_DEATH_RATE); - final Parameter originHeight = (Parameter) xo.getElementFirstChild(ORIGIN_HEIGHT); - final Parameter collapseWeight = (Parameter) xo.getElementFirstChild(COLLAPSE_WEIGHT); - - final String modelName = xo.getId(); - - return new BirthDeathCollapseModel(modelName, tree, units, - birthMinusDeath, relativeDeathRate, originHeight, collapseWeight, collH); - } - - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - - public Class getReturnType() { - return BirthDeathCollapseModel.class; - } - - public String getParserDescription() { - return "A speciation model aimed at species delimitation, mixing birth-death model with spike near zero for node heights."; - } - - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private final XMLSyntaxRule[] rules = { - new ElementRule(TREE, new XMLSyntaxRule[]{new ElementRule(Tree.class)}), - new ElementRule(BIRTHDIFF_RATE, new XMLSyntaxRule[]{new ElementRule(Parameter.class)}), - new ElementRule(RELATIVE_DEATH_RATE, new XMLSyntaxRule[]{new ElementRule(Parameter.class)}), - new ElementRule(ORIGIN_HEIGHT, new XMLSyntaxRule[]{new ElementRule(Parameter.class)}), - new ElementRule(COLLAPSE_WEIGHT, new XMLSyntaxRule[]{new ElementRule(Parameter.class)}), - XMLUnits.SYNTAX_RULES[0], - newDoubleRule(COLLAPSE_HEIGHT), - }; -} - - - - - diff --git a/src/dr/evomodel/alloppnet/parsers/BirthDeathCollapseNClustersStatisticParser.java b/src/dr/evomodel/alloppnet/parsers/BirthDeathCollapseNClustersStatisticParser.java deleted file mode 100644 index 024eeed910..0000000000 --- a/src/dr/evomodel/alloppnet/parsers/BirthDeathCollapseNClustersStatisticParser.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * BirthDeathCollapseNClustersStatisticParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.alloppnet.parsers; - -import dr.evomodel.alloppnet.speciation.BirthDeathCollapseModel; -import dr.evomodel.alloppnet.speciation.BirthDeathCollapseNClustersStatistic; -import dr.evomodel.speciation.SpeciesTreeModel; -import dr.xml.*; - -/** - * @author Graham Jones - * Date: 01/09/2013 - */ -public class BirthDeathCollapseNClustersStatisticParser extends AbstractXMLObjectParser { - public static final String BDC_NCLUSTERS_STATISTIC = "bdcNClustersStatistic"; - public static final String SPECIES_TREE = "speciesTree"; - public static final String COLLAPSE_MODEL = "collapseModel"; - - - - public String getParserName() { - return BDC_NCLUSTERS_STATISTIC; - } - - - @Override - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - xo.getAttribute("name"); - final XMLObject spptreexo = xo.getChild(SPECIES_TREE); - SpeciesTreeModel spptree = (SpeciesTreeModel) spptreexo.getChild(SpeciesTreeModel.class); - final XMLObject cmxo = xo.getChild(COLLAPSE_MODEL); - BirthDeathCollapseModel bdcm = (BirthDeathCollapseModel)cmxo.getChild(BirthDeathCollapseModel.class); - return new BirthDeathCollapseNClustersStatistic(spptree, bdcm); - } - - - private XMLSyntaxRule[] spptreeRules() { - return new XMLSyntaxRule[]{ - new ElementRule(SpeciesTreeModel.class) - }; - } - - private XMLSyntaxRule[] bdcmRules() { - return new XMLSyntaxRule[]{ - new ElementRule(BirthDeathCollapseModel.class) - }; - } - - - - @Override - public XMLSyntaxRule[] getSyntaxRules() { - return new XMLSyntaxRule[]{ - AttributeRule.newStringRule("name"), - new ElementRule(SPECIES_TREE, spptreeRules()), - new ElementRule(COLLAPSE_MODEL, bdcmRules()) - }; - } - - - @Override - public String getParserDescription() { - return "Statistic for number of collapsed nodes in species tree when using birth-death-collapse model."; - } - - @Override - public Class getReturnType() { - return BirthDeathCollapseNClustersStatistic.class; - } - - -} diff --git a/src/dr/evomodel/alloppnet/parsers/MulMSCoalescentParser.java b/src/dr/evomodel/alloppnet/parsers/MulMSCoalescentParser.java deleted file mode 100644 index ac282e9451..0000000000 --- a/src/dr/evomodel/alloppnet/parsers/MulMSCoalescentParser.java +++ /dev/null @@ -1,68 +0,0 @@ - -/* - * MulMSCoalescentParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.alloppnet.parsers; - -import dr.evomodel.alloppnet.speciation.MulMSCoalescent; -import dr.evomodel.alloppnet.speciation.MulSpeciesBindings; -import dr.evomodel.alloppnet.speciation.MulSpeciesTreeModel; -import dr.xml.*; - -/** - * - * @author Graham Jones - * Date: 20/12/2011 - */ -public class MulMSCoalescentParser extends AbstractXMLObjectParser { - public static final String MUL_MS_COALESCENT = "mulMSCoalescent"; - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - final MulSpeciesBindings sb = (MulSpeciesBindings) xo.getChild(MulSpeciesBindings.class); - final MulSpeciesTreeModel tree = (MulSpeciesTreeModel) xo.getChild(MulSpeciesTreeModel.class); - return new MulMSCoalescent(sb, tree); - } - - public XMLSyntaxRule[] getSyntaxRules() { - return new XMLSyntaxRule[]{ - new ElementRule(MulSpeciesBindings.class), - new ElementRule(MulSpeciesTreeModel.class), - }; - } - - public String getParserDescription() { - return "Compute coalecent log-liklihood of a set of gene trees embedded inside one species tree."; - } - - public Class getReturnType() { - return MulMSCoalescent.class; - } - - public String getParserName() { - return MUL_MS_COALESCENT; - } -} diff --git a/src/dr/evomodel/alloppnet/parsers/MulSpeciesBindingsParser.java b/src/dr/evomodel/alloppnet/parsers/MulSpeciesBindingsParser.java deleted file mode 100644 index 1dce20897c..0000000000 --- a/src/dr/evomodel/alloppnet/parsers/MulSpeciesBindingsParser.java +++ /dev/null @@ -1,173 +0,0 @@ -/* - * MulSpeciesBindingsParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.alloppnet.parsers; - -import dr.evomodel.alloppnet.speciation.AlloppSpeciesBindings; -import dr.evomodel.alloppnet.speciation.MulSpeciesBindings; -import dr.evomodel.tree.TreeModel; -import dr.xml.*; - -import java.util.ArrayList; -import java.util.List; - - -/** - * Parser for list of possibly-allopolyploid species containing individuals - * in turn containing taxons (which are diploid genomes). This is similar - * to AlloppSpeciesBindingsParser but makes a MulSpeciesBindings not a - * AlloppSpeciesBindings. XML only different in using "mulSpecies" not - * "alloppspecies", and no "minGeneNodeHeight".. - * - * @author Graham Jones - * Date: 20/12/2011 - */ - - - - -/* - * - * Parses something like this: - - - - - - - - - - - - - - - - - - - - - - - - ... - (more species, then genetrees) - - - */ - - - - -// I have adapted code from SpeciesBindingsParser. -// I changed 'ploidy' to 'popfactor' to reduce confusion with the ploidy level -// of a species which is independent of which gene is considered. -// Use of popfactors is untested. Maybe chloroplast data would use it. - - - -public class MulSpeciesBindingsParser extends AbstractXMLObjectParser { - public static final String MUL_SPECIES = "mulSpecies"; - public static final String GENE_TREES = "geneTrees"; - public static final String GTREE = "gtree"; - public static final String POPFACTOR = "popfactor"; - - - public String getParserName() { - return MUL_SPECIES; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - List apsp = new ArrayList(); - for (int k = 0; k < xo.getChildCount(); ++k) { - final Object child = xo.getChild(k); - if (child instanceof AlloppSpeciesBindings.ApSpInfo) { - apsp.add((AlloppSpeciesBindings.ApSpInfo) child); - } - } - final XMLObject xogt = xo.getChild(GENE_TREES); - final int nTrees = xogt.getChildCount(); - final TreeModel[] trees = new TreeModel[nTrees]; - double[] popFactors = new double[nTrees]; - - for (int nt = 0; nt < trees.length; ++nt) { - Object child = xogt.getChild(nt); - if (!(child instanceof TreeModel)) { - assert child instanceof XMLObject; - popFactors[nt] = ((XMLObject) child).getDoubleAttribute(POPFACTOR); - child = ((XMLObject) child).getChild(TreeModel.class); - - } else { - popFactors[nt] = -1; - } - trees[nt] = (TreeModel) child; - } - - try { - return new MulSpeciesBindings(apsp.toArray(new AlloppSpeciesBindings.ApSpInfo[apsp.size()]), - trees, popFactors); - } catch (Error e) { - throw new XMLParseException(e.getMessage()); - } - } - - - // I have adapted code from SpeciesBindingsParser - // I changed 'Ploidy' to 'PopFactors' to reduce confusion - - // the only use I can think of for popfactors in an AlloppNetwork is chloroplast data - ElementRule treeWithPopFactors = new ElementRule(GTREE, - new XMLSyntaxRule[]{AttributeRule.newDoubleRule(POPFACTOR), - new ElementRule(TreeModel.class)}, 0, Integer.MAX_VALUE); - - - @Override - public XMLSyntaxRule[] getSyntaxRules() { - return new XMLSyntaxRule[]{ - new ElementRule(AlloppSpeciesBindings.ApSpInfo.class, 2, Integer.MAX_VALUE), - new ElementRule(GENE_TREES, - new XMLSyntaxRule[]{ - new ElementRule(TreeModel.class, 0, Integer.MAX_VALUE), - treeWithPopFactors - }), - }; - } - - - @Override - public String getParserDescription() { - return "Binds taxa to gene trees with information about possibly allopolyploid species."; - } - - @Override - public Class getReturnType() { - return MulSpeciesBindings.class; - } -} - diff --git a/src/dr/evomodel/alloppnet/parsers/MulSpeciesTreeModelParser.java b/src/dr/evomodel/alloppnet/parsers/MulSpeciesTreeModelParser.java deleted file mode 100644 index 38a85bb9e0..0000000000 --- a/src/dr/evomodel/alloppnet/parsers/MulSpeciesTreeModelParser.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * MulSpeciesTreeModelParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.alloppnet.parsers; - -import dr.evolution.tree.Tree; -import dr.evomodel.alloppnet.speciation.MulSpeciesBindings; -import dr.evomodel.alloppnet.speciation.MulSpeciesTreeModel; -import dr.inference.model.Parameter; -import dr.inference.model.ParameterParser; -import dr.util.Attributable; -import dr.xml.*; - -/** - * Very similar for JH's SpeciesTreeModelParser but no support for bmp prior, - * piece-wise pop sizes, or user starting tree. - * - * @author Graham Jones - * Date: 20/12/2011 - */ -public class MulSpeciesTreeModelParser extends AbstractXMLObjectParser { - public static final String MUL_SPECIES_TREE = "mulSpeciesTree"; - - public static final String SPP_SPLIT_POPULATIONS = "sppSplitPopulations"; - - public static final String CONST_ROOT_POPULATION = "constantRoot"; - public static final String CONSTANT_POPULATION = "constantPopulation"; - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - MulSpeciesBindings spb = (MulSpeciesBindings) xo.getChild(MulSpeciesBindings.class); - - final Boolean cr = xo.getAttribute(CONST_ROOT_POPULATION, false); - final Boolean cp = xo.getAttribute(CONSTANT_POPULATION, false); - - final XMLObject cxo = xo.getChild(SPP_SPLIT_POPULATIONS); - - final double value = cxo.getAttribute(Attributable.VALUE, 1.0); - final boolean nonConstRootPopulation = !cr; - final Parameter sppSplitPopulations = MulSpeciesTreeModel.createSplitPopulationsParameter(spb, value, nonConstRootPopulation, cp); - ParameterParser.replaceParameter(cxo, sppSplitPopulations); - - final Parameter.DefaultBounds bounds = - new Parameter.DefaultBounds(Double.MAX_VALUE, 0, sppSplitPopulations.getDimension()); - sppSplitPopulations.addBounds(bounds); - - final Tree startTree = null; //(Tree) xo.getChild(Tree.class); - - return new MulSpeciesTreeModel(spb, sppSplitPopulations, null, null, startTree, false, nonConstRootPopulation, cp); - } - - public XMLSyntaxRule[] getSyntaxRules() { - return new XMLSyntaxRule[]{ - AttributeRule.newBooleanRule(CONST_ROOT_POPULATION, true), - AttributeRule.newBooleanRule(CONSTANT_POPULATION, true), - new ElementRule(MulSpeciesBindings.class), - // A starting tree. Can be very minimal, i.e. no branch lengths and not resolved - new ElementRule(Tree.class, true), - new ElementRule(SPP_SPLIT_POPULATIONS, new XMLSyntaxRule[]{ - AttributeRule.newDoubleRule(Attributable.VALUE, true), - new ElementRule(Parameter.class)}) - }; - } - - public String getParserDescription() { - return "Multiply-labelled species tree which includes demographic function per branch."; - } - - public Class getReturnType() { - return MulSpeciesTreeModel.class; - } - - public String getParserName() { - return MUL_SPECIES_TREE; - } - - -} - diff --git a/src/dr/evomodel/alloppnet/parsers/MulSpeciesTreePriorParser.java b/src/dr/evomodel/alloppnet/parsers/MulSpeciesTreePriorParser.java deleted file mode 100644 index 83adcec235..0000000000 --- a/src/dr/evomodel/alloppnet/parsers/MulSpeciesTreePriorParser.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * MulSpeciesTreePriorParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.alloppnet.parsers; - - -import dr.evomodel.alloppnet.speciation.MulSpeciesTreeModel; -import dr.evomodel.alloppnet.speciation.MulSpeciesTreePrior; -import dr.evomodel.speciation.SpeciationModel; -import dr.xml.AbstractXMLObjectParser; -import dr.xml.ElementRule; -import dr.xml.XMLObject; -import dr.xml.XMLParseException; -import dr.xml.XMLSyntaxRule; - -public class MulSpeciesTreePriorParser extends AbstractXMLObjectParser { - public static final String MUL_SPECIES_TREE_PRIOR = "mulSpeciesTreePrior"; - public static final String MODEL = "model"; - public static final String MUL_SPECIES_TREE = "mulTree"; - - - public String getParserName() { - return MUL_SPECIES_TREE_PRIOR; - } - - - @Override - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - final XMLObject mxo = xo.getChild(MODEL); - final SpeciationModel sppm = (SpeciationModel) mxo.getChild(SpeciationModel.class); - final XMLObject mulsptxo = xo.getChild(MUL_SPECIES_TREE); - final MulSpeciesTreeModel mulspt = (MulSpeciesTreeModel) mulsptxo.getChild(MulSpeciesTreeModel.class); - return new MulSpeciesTreePrior(sppm, mulspt); - } - - private XMLSyntaxRule[] modelRules() { - return new XMLSyntaxRule[]{ - new ElementRule(SpeciationModel.class) - }; - } - - private XMLSyntaxRule[] mulsptRules() { - return new XMLSyntaxRule[]{ - new ElementRule(MulSpeciesTreeModel.class) - }; - } - - @Override - public XMLSyntaxRule[] getSyntaxRules() { - return new XMLSyntaxRule[]{ - new ElementRule(MODEL, modelRules()), - new ElementRule(MUL_SPECIES_TREE, mulsptRules()), - - }; - } - - - - @Override - public String getParserDescription() { - return "Prior for a multiply-labelled species tree for allopolyploids."; - } - - @Override - public Class getReturnType() { - return MulSpeciesTreePrior.class; - } - -} diff --git a/src/dr/evomodel/alloppnet/parsers/MulTreeNodeSlideParser.java b/src/dr/evomodel/alloppnet/parsers/MulTreeNodeSlideParser.java deleted file mode 100644 index 5b7c84d9b8..0000000000 --- a/src/dr/evomodel/alloppnet/parsers/MulTreeNodeSlideParser.java +++ /dev/null @@ -1,81 +0,0 @@ - -/* - * MulTreeNodeSlideParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.alloppnet.parsers; - -import dr.evomodel.alloppnet.operators.MulTreeNodeSlide; -import dr.evomodel.alloppnet.speciation.MulSpeciesBindings; -import dr.evomodel.alloppnet.speciation.MulSpeciesTreeModel; -import dr.inference.operators.MCMCOperator; -import dr.xml.*; - -/** - * - * @author Graham Jones - * Date: 20/12/2011 - */ -public class MulTreeNodeSlideParser extends AbstractXMLObjectParser { - public static final String MULTREE_NODE_REHEIGHT = "mulTreeNodeReHeight"; - - public String getParserName() { - return MULTREE_NODE_REHEIGHT; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - MulSpeciesBindings species = (MulSpeciesBindings) xo.getChild(MulSpeciesBindings.class); - MulSpeciesTreeModel tree = (MulSpeciesTreeModel) xo.getChild(MulSpeciesTreeModel.class); - - final double weight = xo.getDoubleAttribute(MCMCOperator.WEIGHT); -// final double range = xo.getAttribute("range", 1.0); -// if( range <= 0 || range > 1.0 ) { -// throw new XMLParseException("range out of range"); -// } - //final boolean oo = xo.getAttribute("outgroup", false); - return new MulTreeNodeSlide(tree, species /*, range*//*, oo*/, weight); - } - - public String getParserDescription() { - return "Specialized Species tree operator, transform tree without breaking embedding of gene trees."; - } - - public Class getReturnType() { - return MulTreeNodeSlide.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return new XMLSyntaxRule[]{ - AttributeRule.newDoubleRule(MCMCOperator.WEIGHT), - // AttributeRule.newDoubleRule("range", true), - // AttributeRule.newBooleanRule("outgroup", true), - - new ElementRule(MulSpeciesBindings.class), - new ElementRule(MulSpeciesTreeModel.class) - }; - } - -} diff --git a/src/dr/evomodel/alloppnet/parsers/MulTreeSequenceReassignmentParser.java b/src/dr/evomodel/alloppnet/parsers/MulTreeSequenceReassignmentParser.java deleted file mode 100644 index 6f2d572dad..0000000000 --- a/src/dr/evomodel/alloppnet/parsers/MulTreeSequenceReassignmentParser.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * MulTreeSequenceReassignmentParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.alloppnet.parsers; - - -import dr.evomodel.alloppnet.operators.MulTreeSequenceReassignment; -import dr.evomodel.alloppnet.speciation.MulSpeciesBindings; -import dr.evomodel.alloppnet.speciation.MulSpeciesTreeModel; -import dr.inference.operators.MCMCOperator; -import dr.xml.AbstractXMLObjectParser; -import dr.xml.AttributeRule; -import dr.xml.ElementRule; -import dr.xml.XMLObject; -import dr.xml.XMLParseException; -import dr.xml.XMLSyntaxRule; - -/** - * - * @author Graham Jones - * Date: 20/12/2011 - */ - - -public class MulTreeSequenceReassignmentParser extends AbstractXMLObjectParser { - public static final String MULTREE_SEQUENCE_REASSIGNMENT = "mulTreeSequenceReassignment"; - - - public String getParserName() { - return MULTREE_SEQUENCE_REASSIGNMENT; - } - - @Override - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - MulSpeciesBindings mulspb = (MulSpeciesBindings) xo.getChild(MulSpeciesBindings.class); - MulSpeciesTreeModel multree = (MulSpeciesTreeModel) xo.getChild(MulSpeciesTreeModel.class); - - final double weight = xo.getDoubleAttribute(MCMCOperator.WEIGHT); - return new MulTreeSequenceReassignment(multree, mulspb, weight); - } - - @Override - public XMLSyntaxRule[] getSyntaxRules() { - return new XMLSyntaxRule[]{ - AttributeRule.newDoubleRule(MCMCOperator.WEIGHT), - new ElementRule(MulSpeciesBindings.class), - new ElementRule(MulSpeciesTreeModel.class) - }; - } - - @Override - public String getParserDescription() { - return "Operator which reassigns sequences within an allopolyploid species."; - } - - @Override - public Class getReturnType() { - return MulTreeSequenceReassignment.class; - } - -} diff --git a/src/dr/evomodel/alloppnet/speciation/AlloppDiploidHistory.java b/src/dr/evomodel/alloppnet/speciation/AlloppDiploidHistory.java deleted file mode 100644 index 1b2196360c..0000000000 --- a/src/dr/evomodel/alloppnet/speciation/AlloppDiploidHistory.java +++ /dev/null @@ -1,1011 +0,0 @@ -/* - * AlloppDiploidHistory.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.alloppnet.speciation; - -import java.util.ArrayList; -import java.util.Formatter; -import java.util.Locale; -import java.util.Stack; - -import dr.evolution.tree.NodeRef; -import dr.evolution.tree.SimpleNode; -import dr.evolution.tree.SimpleTree; -import dr.evomodel.alloppnet.tree.SlidableTree; -import dr.evolution.util.Taxon; -import dr.math.MathUtils; -import dr.evomodel.alloppnet.util.AlloppMisc; -import jebl.util.FixedBitSet; - - -/** - * AlloppDiploidHistory represents part of the network before hybridizations. - * It is basically a tree with some tips representing diploid species at present time - * and others representing the points at which hybridization occurs. - * - * @author Graham Jones - * Date: 13/03/2012 - */ - - -/* - * This a tree with some tips representing diploid species at present time - * and others representing the points at which hybridization (to form a - * tetraploid) occurs. The latter are in pairs and have times before present, - * and I call them `hydridization tips' or `hyb-tips'. From the point of - * view of a tetraploid tree these hyb-tips are feet at the ends of legs. - * - * The purpose of this class is to represent the part of the network before - * hybridizations (=`diploid history') in a form (the array of DipHistNode's) - * that can be subjected to Mau-type moves. - * - * The diploid history is constructed from a diploid tree and a single - * tetraploid tree initially. MCMC moves can change the number of tetraploid - * trees. - * - */ - - - -public class AlloppDiploidHistory implements SlidableTree { - private DipHistNode[] dhnodes; - private int rootn; - private int nextn; - private AlloppSpeciesBindings apsp; - - - /******************************** Inner classes ****************************************/ - - public enum LegLorR {left, right, dud}; - - - // Small class for returning two heights. For ChangeNumHybs move - public class FootAncHeights { - public double anchgt; - public double ancanchgt; - FootAncHeights(double anchgt, double ancanchgt) { - this.anchgt = anchgt; - this.ancanchgt = ancanchgt; - } - } - - /* - * parent, child[] implement the tree topology. - * - * height is the node height; can be > 0 for hyb-tips. - * - * union is a spseq-union. At diploid tips they are used normally. - * Hyb-tips have unions derived from the tetratree and leg index (0 or 1). - * Unions are taken towards the root. - * - * For a hyb-tip, tettree specifies the index of the tetratree whose - * root comes from it. It is not used for other nodes. - */ - private class DipHistNode extends AlloppNode.Abstract implements AlloppNode, NodeRef { - private int anc; - private int lft; - private int rgt; - private double height; - private Taxon taxon; - private FixedBitSet union; - private int tettree; - private LegLorR leg; - private int nodeNumber; - - // dud constuctor - DipHistNode(int nn) { - anc = -1; - lft = -1; - rgt = -1; - height = -1.0; - taxon = new Taxon(""); - union = null; - tettree = -1; - leg = LegLorR.dud; - nodeNumber = nn; - } - - // copy constructor - public DipHistNode(DipHistNode node) { - anc = node.anc; - lft = node.lft; - rgt = node.rgt; - nodeNumber = node.nodeNumber; - copyNonTopologyFields(node); - } - - - // no-topology constructor. Copies all fields of argument node, - // except the anc, lft, rgt fields which are set to `unknown', - // and the index field, which is set to nn - public DipHistNode(int nn, DipHistNode node) { - anc = -1; - lft = -1; - rgt = -1; - nodeNumber = nn; - copyNonTopologyFields(node); - } - - private void copyNonTopologyFields(DipHistNode node) { - height = node.height; - taxon = new Taxon(node.taxon.getId()); - if (node.union == null) { - union = null; - } else { - union = new FixedBitSet(node.union); - } - tettree = node.tettree; - leg = node.leg; - } - - - @Override - public AlloppNode getChild(int ch) { - return ch==0 ? dhnodes[lft] : dhnodes[rgt]; - } - - @Override - public AlloppNode getAnc() { - return dhnodes[anc]; - } - - - @Override - public double getHeight() { - return height; - } - - @Override - public Taxon getTaxon() { - return taxon; - } - - @Override - public FixedBitSet getUnion() { - return union; - } - - @Override - public void setChild(int ch, AlloppNode newchild) { - int newch = ((DipHistNode)newchild).nodeNumber; - if (ch == 0) { - lft = newch; - } else { - rgt = newch; - } - } - - @Override - public void setAnc(AlloppNode anc) { - this.anc = ((DipHistNode)anc).nodeNumber; - } - - @Override - public void setTaxon(String name) { - this.taxon = new Taxon(name); - - } - - - @Override - public void setHeight(double height) { - this.height = height; - - } - - @Override - public void setUnion(FixedBitSet union) { - this.union = union; - } - - @Override - public void addChildren(AlloppNode c0, AlloppNode c1) { - lft = ((DipHistNode)c0).nodeNumber; - dhnodes[lft].anc = nodeNumber; - rgt = ((DipHistNode)c1).nodeNumber; - dhnodes[rgt].anc = nodeNumber; - } - - @Override - public String asText(int indentlen) { - StringBuilder s = new StringBuilder(); - Formatter formatter = new Formatter(s, Locale.US); - if (lft < 0) { - String nodename; - if (tettree >= 0) { - nodename = String.valueOf(tettree); - String legtext = "*"; - if (leg == LegLorR.left) { - legtext = "L"; - } - if (leg == LegLorR.right) { - legtext = "R"; - } - nodename += legtext; - } else { - nodename = taxon.getId(); - } - formatter.format("%s ", nodename); - } else { - formatter.format("%s ", "+"); - } - while (s.length() < 25-indentlen) { - formatter.format("%s", " "); - } - formatter.format("%s ", AlloppMisc.nonnegIn8Chars(height)); - return s.toString(); - } - - - @Override - public int nofChildren() { - return (lft < 0) ? 0 : 2; - } - - @Override - public int getNumber() { - return nodeNumber; - } - - @Override - public void setNumber(int n) { - nodeNumber = n; - - } - - - - } - - - /******************************** Constructors ****************************************/ - - - - private class JoiningNode { - int nn; - boolean hasdip; - JoiningNode(int nn, boolean hasdip) { - this.nn = nn; - this.hasdip = hasdip; - } - } - - - /* - * Constructor makes initial random AlloppDiploidHistory from a diploid tree - * and previously constructed tetratrees. - * apsp needed for speciesseqEmptyUnion(). grjtodo-oneday really needed? - * - */ - AlloppDiploidHistory(Taxon [] dipspp, ArrayList tettrees, - boolean diploidrootisroot, double rate, AlloppSpeciesBindings apsp) { - this.apsp = apsp; - int nofdips = dipspp.length; - int ntips = nofdips + 2 * tettrees.size(); - // Make array of dud nodes - dhnodes = new DipHistNode[2 * ntips - 1]; - for (int i = 0; i < dhnodes.length; i++) { - dhnodes[i] = new DipHistNode(i); - } - // Make tips for diploids and add them to tojoin[] - ArrayList tojoin = new ArrayList(); - for (nextn = 0; nextn < nofdips; nextn++) { - dhnodes[nextn].taxon = new Taxon(dipspp[nextn].getId()); - dhnodes[nextn].height = 0.0; - tojoin.add(new JoiningNode(nextn, true)); - } - // Make two tips for each tet tree, and add to tojoin[] - for (int tt = 0; tt < tettrees.size(); tt++) { - AlloppLeggedTree ttree = tettrees.get(tt); - double tettipsheight = ttree.getRootHeight() + MathUtils.nextExponential(rate); - dhnodes[nextn].tettree = tt; - dhnodes[nextn].leg = LegLorR.left; - ttree.setDiphistLftLeg(nextn); - dhnodes[nextn].height = tettipsheight; - tojoin.add(new JoiningNode(nextn, false)); - nextn++; - dhnodes[nextn].tettree = tt; - dhnodes[nextn].leg = LegLorR.right; - ttree.setDiphistRgtLeg(nextn); - dhnodes[nextn].height = tettipsheight; - tojoin.add(new JoiningNode(nextn, false)); - nextn ++; - } - - // build the tree from tips, taking care not to join the last diploids before all tets used up - for (int i = 0; i < ntips-1; i++) { - int numtojoin = tojoin.size(); - int numwithdips = 0; - for (JoiningNode jn : tojoin) { - numwithdips += jn.hasdip ? 1 : 0; - } - int j = MathUtils.nextInt(numtojoin); - JoiningNode child0 = tojoin.get(j); - // if diploidrootisroot, and down to 2 diploids, and still a tet, ensure ch0 has no dips - if (diploidrootisroot && numtojoin > 2 && numwithdips == 2) { - while (child0.hasdip) { - j = MathUtils.nextInt(numtojoin); - child0 = tojoin.get(j); - } - } - tojoin.remove(j); - int k = MathUtils.nextInt(numtojoin-1); - JoiningNode child1 = tojoin.get(k); - tojoin.remove(k); - dhnodes[nextn].lft = child0.nn; dhnodes[child0.nn].anc = nextn; - dhnodes[nextn].rgt = child1.nn; dhnodes[child1.nn].anc = nextn; - double maxchhgt = Math.max(dhnodes[child0.nn].height, dhnodes[child1.nn].height); - dhnodes[nextn].height = maxchhgt + MathUtils.nextExponential(numtojoin*rate); - tojoin.add(new JoiningNode(nextn, child0.hasdip || child1.hasdip)); - nextn++; - } - rootn = nextn - 1; - assert diphistOK(diploidrootisroot); - makesimpletree(); - } - - - - - // copy constructor. - public AlloppDiploidHistory(AlloppDiploidHistory x) { - dhnodes = new DipHistNode[x.dhnodes.length]; - for (int n = 0; n < dhnodes.length; n++) { - dhnodes[n] = new DipHistNode(x.dhnodes[n]); - } - rootn = x.rootn; - nextn = x.nextn; - apsp = x.apsp; - } - - - // constructor for testing. - public AlloppDiploidHistory(SimpleNode[] snodes, int sroot, ArrayList tettrees, - boolean diprootisroot, AlloppSpeciesBindings apsp) { - this.apsp = apsp; - // Make array of dud nodes - dhnodes = new DipHistNode[snodes.length]; - for (int i = 0; i < dhnodes.length; i++) { - dhnodes[i] = new DipHistNode(i); - } - // Convert snodes tree into dhnodes tree - nextn = 0; - simpletree2dhtesttree(snodes[sroot]); - rootn = nextn - 1; - - // link the hyb-tips to tet roots. - for (int n = 0; n < dhnodes.length; n++) { - String tipname = dhnodes[n].taxon.getId(); - LegLorR leg = LegLorR.dud; - int tt = -1; - if (tipname.contains("L")) { leg = LegLorR.left; } - if (tipname.contains("R")) { leg = LegLorR.right; } - if (tipname.contains("0")) { tt = 0; } - if (tipname.contains("1")) { tt = 1; } - if (tipname.contains("2")) { tt = 2; } - if (leg != LegLorR.dud) { - assert tt >= 0; - dhnodes[n].tettree = tt; - dhnodes[n].leg = leg; - if (leg == LegLorR.left) { tettrees.get(tt).setDiphistLftLeg(n); } - if (leg == LegLorR.right) { tettrees.get(tt).setDiphistRgtLeg(n); } - } - } - dhnodes[rootn].fillinUnionsInSubtree(apsp.numberOfSpSeqs()); - assert diphistOK(diprootisroot); - makesimpletree(); - } - - - - /******************************** SlidableTree implementation ****************************************/ - - - @Override - public NodeRef getSlidableRoot() { - assert dhnodes[rootn].anc < 0; - return dhnodes[rootn]; - } - - - @Override - public void replaceSlidableRoot(NodeRef root) { - rootn = root.getNumber(); - dhnodes[rootn].anc = -1; - } - - - @Override - public int getSlidableNodeCount() { - return dhnodes.length; - } - - - @Override - public double getSlidableNodeHeight(NodeRef node) { - return dhnodes[node.getNumber()].getHeight(); - } - - @Override - public Taxon getSlidableNodeTaxon(NodeRef node) { - return dhnodes[node.getNumber()].getTaxon(); - } - - @Override - public void setSlidableNodeHeight(NodeRef node, double height) { - dhnodes[node.getNumber()].height = height; - } - - - @Override - public boolean isExternalSlidable(NodeRef node) { - return (dhnodes[node.getNumber()].lft < 0); - } - - - - @Override - public NodeRef getSlidableChild(NodeRef node, int j) { - int n = node.getNumber(); - return j == 0 ? dhnodes[ dhnodes[n].lft ] : dhnodes[ dhnodes[n].rgt ]; - } - - - - @Override - public void replaceSlidableChildren(NodeRef node, NodeRef lft, NodeRef rgt) { - int nn = node.getNumber(); - int lftn = lft.getNumber(); - int rgtn = rgt.getNumber(); - assert dhnodes[nn].lft >= 0; - dhnodes[nn].lft = lftn; - dhnodes[nn].rgt = rgtn; - dhnodes[lftn].anc = dhnodes[nn].nodeNumber; - dhnodes[rgtn].anc = dhnodes[nn].nodeNumber; - } - - - - String asText() { - String header = "Diploid history height" + System.getProperty("line.separator"); - String s = ""; - Stack x = new Stack(); - return header + AlloppNode.Abstract.subtreeAsText(dhnodes[rootn], s, x, 0, ""); - } - - - int getInternalNodeCount() { - return (dhnodes.length - 1) / 2; - } - - - int getDiploidTipCount() { - int ndiptips = 0; - for (int i = 0; i < dhnodes.length; i++) { - if (dhnodes[i].lft < 0 && dhnodes[i].tettree < 0) { - ndiptips++; - } - } - return ndiptips; - } - - - public ArrayList collectFeet() { - ArrayList feet = new ArrayList(); - for (int i = 0; i < dhnodes.length; i++) { - if (dhnodes[i].tettree >= 0) { - feet.add(i); - } - } - return feet; - } - - - public boolean tipIsDiploidTip(NodeRef node) { - assert dhnodes[node.getNumber()].lft < 0; - return (dhnodes[node.getNumber()].tettree < 0); - } - - // For move that merges two tettrees. This is part of - // test that they can be merged. - public boolean tettreesShareLegs(AlloppLeggedTree ttree1, AlloppLeggedTree ttree2) { - int lftleg1 = ttree1.getDiphistLftLeg(); - int lftleg1anc = dhnodes[lftleg1].anc; - int lftleg2 = ttree2.getDiphistLftLeg(); - int lftleg2anc = dhnodes[lftleg2].anc; - int rgtleg1 = ttree1.getDiphistRgtLeg(); - int rgtleg1anc = dhnodes[rgtleg1].anc; - int rgtleg2 = ttree2.getDiphistRgtLeg(); - int rgtleg2anc = dhnodes[rgtleg2].anc; - boolean llrr = ((lftleg1anc == lftleg2anc) && (rgtleg1anc == rgtleg2anc)); - return llrr; - /* - boolean lrrl = ((lftleg1anc == rgtleg2anc) && (rgtleg1anc == lftleg2anc)); - return (llrr || lrrl); */ - } - - - // For (old?) move that merges two tettrees. This is for Hastings ratio calculation. - public double intervalOfFoot(AlloppLeggedTree ttree, boolean left) { - double hybh = getHybHeight(ttree); - int foot = left ? ttree.getDiphistLftLeg() : ttree.getDiphistRgtLeg(); - int footanc = dhnodes[foot].anc; - assert footanc >= 0; - int footancanc = dhnodes[footanc].anc; - assert footancanc >= 0; - return (dhnodes[footancanc].height - hybh); - } - - - // For move that merges two tettrees. This is for Hastings ratio calculation. - public FootAncHeights intervalOfFootAncestor(AlloppLeggedTree ttree, LegLorR leg) { - double hybh = getHybHeight(ttree); - int foot = (leg==LegLorR.left) ? ttree.getDiphistLftLeg() : ttree.getDiphistRgtLeg(); - assert hybh == dhnodes[foot].height; - int footanc = dhnodes[foot].anc; - int footancanc = dhnodes[footanc].anc; - assert footancanc >= 0; - return new FootAncHeights(dhnodes[footanc].height, dhnodes[footancanc].height); - } - - - - public void setHybridHeight(AlloppLeggedTree ttree, double newh) { - int foot1 = ttree.getDiphistLftLeg(); - int foot2 = ttree.getDiphistRgtLeg(); - dhnodes[foot1].height = dhnodes[foot2].height = newh; - } - - - - // For move that merges two tettrees. This is for after merge. - // It removes two tips that were joined to ttree - public void removeFeet(AlloppSpeciesNetworkModel apspnet, AlloppLeggedTree ttree) { - DipHistNode [] tmpnodes = new DipHistNode[dhnodes.length]; - for (int i = 0; i < tmpnodes.length; i++) { - tmpnodes[i] = new DipHistNode(dhnodes[i]); - } - removeTip(ttree.getDiphistLftLeg(), tmpnodes); - removeTip(ttree.getDiphistRgtLeg(), tmpnodes); - dhnodes = new DipHistNode[tmpnodes.length - 4]; - nextn = 0; - buildSubtreeFromNodes(apspnet, tmpnodes, rootn); - rootn = nextn - 1; - } - - - // Adds two hyb-tips for tettree tt1. these are joined to legs of tettree tt2 - public void addTwoDipTips(AlloppSpeciesNetworkModel apspnet, int tt1, int tt2, double lfthgt, double rgthgt, double tiphgt) { - AlloppLeggedTree tettree1 = apspnet.getTetraploidTree(tt1); - AlloppLeggedTree tettree2 = apspnet.getTetraploidTree(tt2); - int lftleg = tettree2.getDiphistLftLeg(); - int rgtleg = tettree2.getDiphistRgtLeg(); - int oldn = dhnodes.length; - DipHistNode [] tmpnodes = new DipHistNode[oldn + 4]; - for (int n = 0; n < oldn; n++) { - tmpnodes[n] = new DipHistNode(dhnodes[n]); - } - - // two new diploid tips for tettree tt1 - tmpnodes[oldn] = new DipHistNode(oldn); - tmpnodes[oldn].height = tiphgt; - tmpnodes[oldn].tettree = tt1; - tmpnodes[oldn].leg = LegLorR.left; - tettree1.setDiphistLftLeg(oldn); - - tmpnodes[oldn+1] = new DipHistNode(oldn+1); - tmpnodes[oldn+1].height = tiphgt; - tmpnodes[oldn+1].tettree = tt1; - tmpnodes[oldn+1].leg = LegLorR.right; - tettree1.setDiphistRgtLeg(oldn+1); - - // two new nodes to go into existing branches - tmpnodes[oldn+2] = new DipHistNode(oldn+2); - tmpnodes[oldn+2].height = lfthgt; - tmpnodes[oldn+2].anc = tmpnodes[lftleg].anc; - tmpnodes[oldn+2].lft = oldn; - tmpnodes[oldn+2].rgt = lftleg; - - tmpnodes[oldn+3] = new DipHistNode(oldn+3); - tmpnodes[oldn+3].height = rgthgt; - tmpnodes[oldn+3].anc = tmpnodes[rgtleg].anc; - tmpnodes[oldn+3].lft = oldn+1; - tmpnodes[oldn+3].rgt = rgtleg; - - // divide branch by pointing to new nodes oldn+2,+3 - int lftfootanc = tmpnodes[lftleg].anc; - if (tmpnodes[lftfootanc].lft == lftleg) { - tmpnodes[lftfootanc].lft = oldn+2; - } else { - assert tmpnodes[lftfootanc].rgt == lftleg; - tmpnodes[lftfootanc].rgt = oldn+2; - } - - int rgtfootanc = tmpnodes[rgtleg].anc; - if (tmpnodes[rgtfootanc].lft == rgtleg) { - tmpnodes[rgtfootanc].lft = oldn+3; - } else { - assert tmpnodes[rgtfootanc].rgt == rgtleg; - tmpnodes[rgtfootanc].rgt = oldn+3; - } - - dhnodes = new DipHistNode[tmpnodes.length]; - nextn = 0; - buildSubtreeFromNodes(apspnet, tmpnodes, rootn); - rootn = nextn - 1; - } - - - // For move that splits a tetree - public double getAncHeight(int n) { - int nanc = dhnodes[n].anc; - assert nanc >= 0; - return dhnodes[nanc].height; - } - - - // next bunch for AlloppMulLabTree constructor - int getRootIndex() { - return rootn; - } - - double getHeightFromIndex(int n) { - return dhnodes[n].height; - } - - int getLftFromIndex(int n) { - return dhnodes[n].lft; - } - int getRgtFromIndex(int n) { - return dhnodes[n].rgt; - } - Taxon getTaxonFromIndex(int n) { - return dhnodes[n].taxon; - } - - - double getRootHeight() { - return dhnodes[rootn].height; - } - - - public double getHybHeight(AlloppLeggedTree tettree) { - return dhnodes[tettree.getDiphistLftLeg()].height; - } - - - // for prior lhood - void collectInternalAndHybHeights(ArrayList heights) { - for (DipHistNode node : dhnodes) { - if (node.lft >= 0) { - heights.add(node.height); - } else { - if (node.tettree >= 0 && node.leg == LegLorR.left) { - heights.add(node.height); - } - } - } - } - - - public void moveHybridHeight(int foot1, int foot2, double minh) { - int f1anc = dhnodes[foot1].anc; - int f2anc = dhnodes[foot2].anc; - double maxh = Math.min(dhnodes[f1anc].height, dhnodes[f2anc].height); - double oldh = dhnodes[foot1].height; - double newh = AlloppMisc.uniformInRange(oldh, minh, maxh, 0.3); - dhnodes[foot1].height = dhnodes[foot2].height = newh; - } - - - int scaleAllHeights(double scale) { - int nofnodes = dhnodes.length; - int count = 0; - for (int n = 0; n < nofnodes; n++) { - if (dhnodes[n].lft >= 0 || dhnodes[n].tettree >= 0) { - dhnodes[n].height *= scale; - count++; - } - } - return count; - } - - - // for assert tests during merging tetrees in move - public void clearAllNodeTettree() { - for (int n = 0; n < dhnodes.length; ++n) { - dhnodes[n].tettree = -1; - } - } - - // for moving hyb time, and for assert tests during merging tetrees in move, and - public int getNodeTettree(int node) { - return dhnodes[node].tettree; - } - - LegLorR getNodeLeg(int node) { - return dhnodes[node].leg; - } - - // for move that flips all seqs of tet tree and its legs - void setNodeLeg(int nn, LegLorR leg) { - dhnodes[nn].leg = leg; - } - - - // for merging tetrees in move - public void setNodeTettree(int node, int tt) { - dhnodes[node].tettree = tt; - } - - - - /* - * For testing - */ - public boolean diphistOK(boolean diprootisroot) { - int nroots = 0; - for (int i = 0; i < dhnodes.length; i++) { - if (dhnodes[i].anc < 0) { - nroots++; - } - } - if (nroots != 1) { - return false; - } - for (int i = 0; i < dhnodes.length; i++) { - int nparents = 0; - for (int j = 0; j < dhnodes.length; j++) { - if (dhnodes[j].lft == i) { nparents++; } - if (dhnodes[j].rgt == i) { nparents++; } - } - if (dhnodes[i].anc < 0 && nparents != 0) { - return false; - } - if (dhnodes[i].anc >= 0 && nparents != 1) { - return false; - } - } - - for (int i = 0; i < dhnodes.length; i++) { - if (dhnodes[i].getNumber() != i) { - return false; - } - } - - for (int i = 0; i < dhnodes.length; i++) { - if (dhnodes[i].lft >= 0) { - if (dhnodes[i].rgt < 0) { - return false; - } - int lft = dhnodes[i].lft; - int rgt = dhnodes[i].rgt; - if (dhnodes[lft].anc != i) { - return false; - } - if (dhnodes[rgt].anc != i) { - return false; - } - if (dhnodes[i].height <= dhnodes[lft].height) { - return false; - } - if (dhnodes[i].height <= dhnodes[rgt].height) { - return false; - } - if (dhnodes[i].tettree >= 0) { - return false; - } - } else { - if (dhnodes[i].tettree >= 0) { - if (dhnodes[i].height <= 0) { - return false; - } - if (dhnodes[i].leg != LegLorR.left && dhnodes[i].leg != LegLorR.right) { - return false; - } - } else { - if (dhnodes[i].height != 0) { - return false; - } - } - } - } - if (dhnodes[rootn].anc >= 0) { - return false; - } - ArrayList feet = collectFeet(); - for (Integer f1 : feet) { - for (Integer f2 : feet) { - if (dhnodes[f1].tettree == dhnodes[f2].tettree) { - if (dhnodes[f1].height != dhnodes[f2].height) { - return false; - } - } - } - } - if (diprootisroot) { - if (!gotDipTipInSubtree(dhnodes[rootn].lft) || !gotDipTipInSubtree(dhnodes[rootn].rgt)) { - return false; - } - } - - - return true; - } - - - private boolean gotDipTipInSubtree(int nn) { - if (dhnodes[nn].lft < 0) { - return (dhnodes[nn].tettree < 0); - } else { - return gotDipTipInSubtree(dhnodes[nn].lft) || gotDipTipInSubtree(dhnodes[nn].rgt); - } - } - - - - /* - * ************************************************************************** - * PRIVATE methods - * ************************************************************************** - */ - - - - - - /* - * This builds a new tree in dhnodes[] from the one in tmpnodes. - * The reason for not just copying the array is that the order of - * nodes in tmpnodes[] is not postorder. (One could live with the - * nodes in any order, but it would complicate things elsewhere.) - */ - private void buildSubtreeFromNodes(AlloppSpeciesNetworkModel apspnet, - DipHistNode[] tmpnodes, int n) { - if (tmpnodes[n].lft < 0) { - assert tmpnodes[n].rgt < 0; - dhnodes[nextn] = new DipHistNode(nextn, tmpnodes[n]); - int tt = dhnodes[nextn].tettree; - LegLorR leg = dhnodes[nextn].leg; - AlloppLeggedTree ttree; - if (tt >= 0) { - ttree = apspnet.getTetraploidTree(tt); - if (ttree.getDiphistLftLeg() == n) { - if (leg == LegLorR.left) { - ttree.setDiphistLftLeg(nextn); - } else { - assert leg == LegLorR.right; - ttree.setDiphistRgtLeg(nextn); - } - } else { - assert apspnet.getTetraploidTree(tt).getDiphistRgtLeg() == n; - if (leg == LegLorR.left) { - ttree.setDiphistLftLeg(nextn); - } else { - assert leg == LegLorR.right; - ttree.setDiphistRgtLeg(nextn); - } - } - } - nextn ++; - } else { - assert tmpnodes[n].rgt >= 0; - buildSubtreeFromNodes(apspnet, tmpnodes, tmpnodes[n].lft); - int lft = nextn - 1; - buildSubtreeFromNodes(apspnet, tmpnodes, tmpnodes[n].rgt); - int rgt = nextn - 1; - dhnodes[nextn] = new DipHistNode(nextn, tmpnodes[n]); - dhnodes[nextn].lft = lft; - dhnodes[lft].anc = nextn; - dhnodes[nextn].rgt = rgt; - dhnodes[rgt].anc = nextn; - nextn ++; - } - } - - - - private void removeTip(int leg, DipHistNode[] tmpnodes) { - int legsibling; - int leganc = tmpnodes[leg].anc; - assert leganc >= 0; - if (tmpnodes[leganc].lft == leg) { - legsibling = tmpnodes[leganc].rgt; - } else { - assert tmpnodes[leganc].rgt == leg; - legsibling = tmpnodes[leganc].lft; - } - int legancanc = tmpnodes[leganc].anc; - assert legancanc >= 0; - if (tmpnodes[legancanc].lft == leganc) { - tmpnodes[legancanc].lft = legsibling; - } else { - assert tmpnodes[legancanc].rgt == leganc; - tmpnodes[legancanc].rgt = legsibling; - } - } - - // for testing - private SimpleTree makesimpletree() { - SimpleNode[] snodes = new SimpleNode[dhnodes.length]; - for (int n = 0; n < dhnodes.length; n++) { - snodes[n] = new SimpleNode(); - snodes[n].setTaxon(null); // I use taxon==null to identify joined leg node when removing hybtips - } - makesimplesubtree(snodes, 0, dhnodes[rootn]); - return new SimpleTree(snodes[dhnodes.length-1]); - } - - - // for testing. for makesimpletree() - private int makesimplesubtree(SimpleNode[] snodes, int nextsn, DipHistNode dhnode) { - if (dhnode.lft < 0) { - Taxon tx = new Taxon(dhnode.taxon.getId()); - snodes[nextsn].setTaxon(tx); - if (dhnode.tettree >= 0) { - snodes[nextsn].setAttribute("tettree", dhnode.tettree); - snodes[nextsn].setAttribute("leg", dhnode.leg); - } - } else { - nextsn = makesimplesubtree(snodes, nextsn, dhnodes[dhnode.lft]); - int subtree0 = nextsn-1; - nextsn = makesimplesubtree(snodes, nextsn, dhnodes[dhnode.rgt]); - int subtree1 = nextsn-1; - snodes[nextsn].addChild(snodes[subtree0]); - snodes[nextsn].addChild(snodes[subtree1]); - } - snodes[nextsn].setHeight(dhnode.height); - return nextsn+1; - } - - - // for testing - private void simpletree2dhtesttree(SimpleNode snode) { - if (snode.getChildCount() == 2) { - simpletree2dhtesttree(snode.getChild(0)); - int lft = nextn - 1; - simpletree2dhtesttree(snode.getChild(1)); - int rgt = nextn - 1; - dhnodes[nextn].lft = lft; dhnodes[lft].anc = nextn; - dhnodes[nextn].rgt = rgt; dhnodes[rgt].anc = nextn; - } - dhnodes[nextn].height = snode.getHeight(); - dhnodes[nextn].taxon = new Taxon(snode.getTaxon().getId()); - dhnodes[nextn].union = apsp.speciesseqEmptyUnion(); - nextn++; - } - - - - - - - - - -} diff --git a/src/dr/evomodel/alloppnet/speciation/AlloppLeggedTree.java b/src/dr/evomodel/alloppnet/speciation/AlloppLeggedTree.java deleted file mode 100644 index 4500cff709..0000000000 --- a/src/dr/evomodel/alloppnet/speciation/AlloppLeggedTree.java +++ /dev/null @@ -1,656 +0,0 @@ -/* - * AlloppLeggedTree.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.alloppnet.speciation; - -import java.util.ArrayList; -import java.util.Formatter; -import java.util.Locale; -import java.util.Stack; - - -import dr.evomodel.alloppnet.util.AlloppMisc; -import jebl.util.FixedBitSet; - -import dr.evolution.tree.NodeRef; -import dr.evomodel.alloppnet.tree.SlidableTree; -import dr.evolution.util.Taxon; -import dr.math.MathUtils; - - -/** - * - * A 'tree with legs' for a single ploidy level in an allopolyploid network. - * - * @author Graham Jones - * Date: 01/05/2011 - */ - - - -/* - * class AlloppLeggedTree - * - * This is a `tree with legs', which is a homoploid - * species tree which is attached to a tree of lower ploidy - * via its legs, as part of a AlloppSpeciesNetworkModel. - * - * altnodes is an array of ALTNode's which implements the homoploid species tree. - * rootn is the index of the root node. - * - * The fields diphistlftleg, diphistrgtleg are indices giving the - * hyb-tips in the AlloppDiploidHistory. - * - */ - - - - -public class AlloppLeggedTree implements SlidableTree { - - private ALTNode[] altnodes; - private int rootn; - - private int diphistlftleg; - private int diphistrgtleg; - - - - /* - * parent, child[] implement the tree topology. - * - * height is the node height; can be > 0 for hyb-tips. - * - * union is a spseq-union. At diploid tips they are used normally. - * Hyb-tips have unions derived from the tetratree and leg index (0 or 1). - * Unions are taken towards the root. - * - * For a hyb-tip, tettree specifies the index of the tetratree whose - * root comes from it. It is not used for other nodes. - */ - private class ALTNode extends AlloppNode.Abstract implements AlloppNode, NodeRef { - private int anc; - private int lft; - private int rgt; - private double height; - private Taxon taxon; - private FixedBitSet union; - private int nodeNumber; - - // dud constuctor - ALTNode(int nn) { - anc = -1; - lft = -1; - rgt = -1; - height = -1.0; - taxon = new Taxon(""); - union = null; - nodeNumber = nn; - } - - // copy constructor - public ALTNode(ALTNode node) { - anc = node.anc; - lft = node.lft; - rgt = node.rgt; - nodeNumber = node.nodeNumber; - copyNonTopologyFields(node); - } - - // no-topology constructor. Copies all fields of argument node, - // except the anc, lft, rgt fields which are set to `unknown', - // and the index field, which is set to nn - public ALTNode(int nn, ALTNode node) { - anc = -1; - lft = -1; - rgt = -1; - nodeNumber = nn; - copyNonTopologyFields(node); - } - - - - private void copyNonTopologyFields(ALTNode node) { - height = node.height; - taxon = new Taxon(node.taxon.getId()); - if (node.union == null) { - union = null; - } else { - union = new FixedBitSet(node.union); - } - } - - @Override - public AlloppNode getChild(int ch) { - return ch==0 ? altnodes[lft] : altnodes[rgt]; - } - - @Override - public AlloppNode getAnc() { - return altnodes[anc]; - } - - - @Override - public double getHeight() { - return height; - } - - @Override - public Taxon getTaxon() { - return taxon; - } - - @Override - public FixedBitSet getUnion() { - return union; - } - - @Override - public void setChild(int ch, AlloppNode newchild) { - int newch = ((ALTNode)newchild).nodeNumber; - if (ch == 0) { - lft = newch; - } else { - rgt = newch; - } - } - - @Override - public void setAnc(AlloppNode anc) { - this.anc = ((ALTNode)anc).nodeNumber; - } - - @Override - public void setTaxon(String name) { - this.taxon = new Taxon(name); - - } - - - @Override - public void setHeight(double height) { - this.height = height; - - } - - @Override - public void setUnion(FixedBitSet union) { - this.union = union; - } - - @Override - public void addChildren(AlloppNode c0, AlloppNode c1) { - lft = ((ALTNode)c0).nodeNumber; - altnodes[lft].anc = nodeNumber; - rgt = ((ALTNode)c1).nodeNumber; - altnodes[rgt].anc = nodeNumber; - } - - @Override - public String asText(int indentlen) { - StringBuilder s = new StringBuilder(); - Formatter formatter = new Formatter(s, Locale.US); - if (lft < 0) { - formatter.format("%s ", taxon.getId()); - } else { - formatter.format("%s ", "+"); - } - while (s.length() < 20-indentlen) { - formatter.format("%s", " "); - } - formatter.format("%s ", AlloppMisc.nonnegIn8Chars(height)); - return s.toString(); - } - - - @Override - public int nofChildren() { - return (lft < 0) ? 0 : 2; - } - - @Override - public int getNumber() { - return nodeNumber; - } - - @Override - public void setNumber(int n) { - nodeNumber = n; - - } - - - - } - - - /* - * Constructor makes a random starting (homoploid) tree. - * Legs are left to AlloppDiploidHistory to do. - */ - public AlloppLeggedTree(Taxon[] taxa, double rate) { - int noftets = taxa.length; - - // Make array of dud nodes - altnodes = new ALTNode[2 * noftets - 1]; - for (int i = 0; i < altnodes.length; i++) { - altnodes[i] = new ALTNode(i); - } - ArrayList tojoin = new ArrayList(noftets); - for (int n = 0; n < noftets; n++) { - altnodes[n].setTaxon(taxa[n].getId()); - altnodes[n].setHeight(0.0); - tojoin.add(n); - } - double treeheight = 0.0; - for (int i = 0; i < noftets-1; i++) { - int numtojoin = tojoin.size(); - int j = MathUtils.nextInt(numtojoin); - Integer child0 = tojoin.get(j); - tojoin.remove(j); - int k = MathUtils.nextInt(numtojoin-1); - Integer child1 = tojoin.get(k); - tojoin.remove(k); - altnodes[noftets+i].addChildren(altnodes[child0], altnodes[child1]); - altnodes[noftets+i].setHeight(treeheight + randomnodeheight(numtojoin*rate)); - treeheight = altnodes[noftets+i].getHeight(); - tojoin.add(noftets+i); - } - diphistlftleg = -1; - diphistrgtleg = -1; - rootn = altnodes.length - 1; - } - - - - /** - * copy constructor - */ - public AlloppLeggedTree(AlloppLeggedTree x) { - altnodes = new ALTNode[x.altnodes.length]; - for (int n = 0; n < altnodes.length; n++) { - altnodes[n] = new ALTNode(x.altnodes[n]); - } - rootn = x.rootn; - this.diphistlftleg = x.diphistlftleg; - this.diphistrgtleg = x.diphistrgtleg; - - } - - - /* - * Constructor. Makes a merged tree from two trees. ttree2 has the more ancient hyb time, - * so the merged tree gets its legs. - */ - public AlloppLeggedTree(AlloppLeggedTree ttree1, AlloppLeggedTree ttree2, double hybHeight) { - altnodes = new ALTNode[1 + ttree1.altnodes.length + ttree2.altnodes.length]; - diphistlftleg = ttree2.diphistlftleg; - diphistrgtleg = ttree2.diphistrgtleg; - int nextn = copySubtree(0, (ALTNode)ttree1.getSlidableRoot()); - int lft = nextn - 1; - nextn = copySubtree(nextn, (ALTNode)ttree2.getSlidableRoot()); - int rgt = nextn - 1; - assert nextn == altnodes.length - 1; - altnodes[nextn] = new ALTNode(nextn); - altnodes[nextn].addChildren(altnodes[lft], altnodes[rgt]); - altnodes[nextn].setHeight(hybHeight); - rootn = nextn; - } - - - /* - * Constructor. Makes a tree from subtree of tetTree - * does not fill in legs - */ - public AlloppLeggedTree(AlloppLeggedTree tetTree, AlloppNode sub) { - ALTNode node = (ALTNode)sub; - int ntips = tetTree.noftipsSubtree(node); - altnodes = new ALTNode[2*ntips-1]; - for (int n = 0; n < altnodes.length; n++) { - altnodes[n] = new ALTNode(n); - } - int nextn = copySubtree(0, node); - rootn = nextn - 1; - } - - - /* - * Constructor for testing. - */ - public AlloppLeggedTree(Taxon[] taxa) { - int nTaxa = taxa.length; - assert(nTaxa <= 4); - int nNodes = 2 * nTaxa - 1; - altnodes = new ALTNode[nNodes]; - for (int n = 0; n < nNodes; n++) { - altnodes[n] = new ALTNode(n); - } - - for (int t = 0; t= 0; - altnodes[nn].lft = lftn; - altnodes[nn].rgt = rgtn; - altnodes[lftn].anc = altnodes[nn].nodeNumber; - altnodes[rgtn].anc = altnodes[nn].nodeNumber; - } - - - - String asText(int tt) { - String header = "Tetraploid tree " + String.valueOf(tt) + " height" + System.getProperty("line.separator"); - String s = ""; - Stack x = new Stack(); - return header + AlloppNode.Abstract.subtreeAsText(altnodes[rootn], s, x, 0, ""); - - } - - - - - boolean leggedtreeOK() { - int nroots = 0; - for (int i = 0; i < altnodes.length; i++) { - if (altnodes[i].anc < 0) { - nroots++; - } - } - if (nroots != 1) { - return false; - } - for (int i = 0; i < altnodes.length; i++) { - int nparents = 0; - for (int j = 0; j < altnodes.length; j++) { - if (altnodes[j].lft == i) { nparents++; } - if (altnodes[j].rgt == i) { nparents++; } - } - if (altnodes[i].anc < 0 && nparents != 0) { - return false; - } - if (altnodes[i].anc >= 0 && nparents != 1) { - return false; - } - } - for (int i = 0; i < altnodes.length; i++) { - if (altnodes[i].getNumber() != i) { - return false; - } - } - for (int i = 0; i < altnodes.length; i++) { - if (altnodes[i].lft >= 0) { - if (altnodes[i].rgt < 0) { - return false; - } - int lft = altnodes[i].lft; - int rgt = altnodes[i].rgt; - if (altnodes[lft].anc != i) { - return false; - } - if (altnodes[rgt].anc != i) { - return false; - } - if (altnodes[i].height <= altnodes[lft].height) { - return false; - } - if (altnodes[i].height <= altnodes[rgt].height) { - return false; - } - } else { - if (altnodes[i].height != 0) { - return false; - } - } - } - if (altnodes[rootn].anc >= 0) { - return false; - } - return true; - } - - - - - - public int scaleAllHeights(double scale) { - int count = 0; - for (int n = 0; n < altnodes.length; n++) { - if (altnodes[n].nofChildren() > 0) { - altnodes[n].height *= scale; - count++; - } - } - return count; - } - - - public ArrayList getSpeciesTaxons() { - ArrayList sptxs = new ArrayList(); - for (int n = 0; n < altnodes.length; n++) { - if (altnodes[n].nofChildren() == 0) { - Taxon taxon = altnodes[n].getTaxon(); - sptxs.add(taxon); - } - } - assert sptxs.size() == getExternalNodeCount(); - return sptxs; - } - - - - - public void fillinTipUnions(AlloppSpeciesBindings apsp, int leg) { - for (int n = 0; n < altnodes.length; n++) { - if (altnodes[n].nofChildren() == 0) { - altnodes[n].setUnion(apsp.taxonseqToTipUnion(altnodes[n].taxon, leg)); - } - } - } - - public double getRootHeight() { - return altnodes[rootn].height; - } - - - - public int getExternalNodeCount() { - return (altnodes.length + 1) / 2; - } - - public int getInternalNodeCount() { - return (altnodes.length - 1) / 2; - } - - - - - public void collectInternalHeights(ArrayList heights) { - for (int n = 0; n < altnodes.length; n++) { - if (altnodes[n].nofChildren() > 0) { - heights.add(altnodes[n].height); - } - } - } - - - public void setDiphistLftLeg(int lftleg) { - diphistlftleg = lftleg; - } - - public void setDiphistRgtLeg(int rgtleg) { - diphistrgtleg = rgtleg; - } - - public int getDiphistLftLeg() { - return diphistlftleg; - } - - public int getDiphistRgtLeg() { - return diphistrgtleg; - } - - - - - /***********************************************************************/ - /************************** private ************************************/ - /***********************************************************************/ - - private int copySubtree(int nextn, ALTNode node) { - if (node.nofChildren() == 0) { - altnodes[nextn] = new ALTNode(nextn, node); - nextn++; - } else { - nextn = copySubtree(nextn, (ALTNode)node.getChild(0)); - int lft = nextn - 1; - nextn = copySubtree(nextn, (ALTNode)node.getChild(1)); - int rgt = nextn - 1; - altnodes[nextn] = new ALTNode(nextn, node); - altnodes[nextn].anc = -1; - altnodes[nextn].nodeNumber = nextn; - altnodes[nextn].addChildren(altnodes[lft], altnodes[rgt]); - nextn++; - } - return nextn; - } - - private int noftipsSubtree(ALTNode node) { - int ntips = 0; - if (node.lft >= 0) { - int lftntips = noftipsSubtree(altnodes[node.lft]); - int rgtntips = noftipsSubtree(altnodes[node.rgt]); - ntips = lftntips + rgtntips; - } else { - ntips = 1; - } - return ntips; - } - - - private double randomnodeheight(double rate) { - return MathUtils.nextExponential(rate) + 1e-6/rate; - // 1e-6/rate to avoid very tiny heights - } - - - - - - - - - - -} diff --git a/src/dr/evomodel/alloppnet/speciation/AlloppMSCoalescent.java b/src/dr/evomodel/alloppnet/speciation/AlloppMSCoalescent.java deleted file mode 100644 index a10c109b01..0000000000 --- a/src/dr/evomodel/alloppnet/speciation/AlloppMSCoalescent.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * AlloppMSCoalescent.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.alloppnet.speciation; - - -import dr.evolution.util.Units; -import dr.inference.model.Likelihood; - - -/** - * Computes coalescent log-likelihood of a set of gene trees embedded inside a - * allopolyploid species network. - * - * @author Graham Jones - * Date: 03/06/2011 - */ - - -/* - * AlloppMSCoalescent, AlloppSpeciesNetworkModel, AlloppLeggedTree, - * AlloppDiploidHistory, and AlloppSpeciesBindings collaborate closely. - * - * AlloppSpeciesNetworkModel contains an AlloppDiploidHistory and an array of - * AlloppLeggedTree's for representing the tetraploid trees. It also contains a - * multiply labelled tree as an alternative representation. - * - * AlloppSpeciesBindings represents the species-individual-genome structure - * of the data, and contains the gene trees. - * - * This module, AlloppMSCoalescent, uses AlloppSpeciesNetworkModel and - * AlloppSpeciesBindings to calculate P(g_i|S) = probability that gene tree - * g_i fits into network S. - * - * apsp.geneTreeFitsInNetwork calls - * FitsInNetwork (inside a gene tree) calls - * subTreeFitsInNetwork (recursive, inside a gene tree) calls - * CoalescenceIsCompatible to test a single coalescence against mullab tree - * - * apsp.geneTreeLogLikelihood calls - * TreeLogLikelihood (inside a gene tree) calls - * clearCoalescences (in mullab tree) and - * recordCoalescence (in mullab tree) and - * recordLineageCounts (in mullab tree) and - * to set up data in mullab tree nodes, then - * mullabTreeLogLikelihood which calls - * mullabSubTreeLogLikelihood (recursive, in mullab tree) calls - * limbLogLike calls - * limbLinPopIntegral - * - */ - - - - -public class AlloppMSCoalescent extends Likelihood.Abstract implements Units { - private final AlloppSpeciesNetworkModel asnetwork; - private final AlloppSpeciesBindings apsp; - - - - public AlloppMSCoalescent(AlloppSpeciesBindings apspecies, AlloppSpeciesNetworkModel apspnetwork) { - super(apspnetwork); - apsp = apspecies; - asnetwork = apspnetwork; - - asnetwork.addModelListener(this); - apsp.addModelListeners(this); - } - - - - @Override - protected double calculateLogLikelihood() { - for (int i = 0; i < apsp.numberOfGeneTrees(); i++) { - if (!apsp.geneTreeFitsInNetwork(i, asnetwork)) { - return Double.NEGATIVE_INFINITY; - } - } - // grjtodo-oneday JH has compatible flags for efficiency. I'm checking - // every time. - - double logl = 0; - for(int i = 0; i < apsp.numberOfGeneTrees(); i++) { - final double v = apsp.geneTreeLogLikelihood(i, asnetwork); - assert ! Double.isNaN(v); - logl += v; - } - return logl; - } - - - @Override - protected boolean getLikelihoodKnown() { - return false; - } - - - public Type getUnits() { - return asnetwork.getUnits(); - } - - public void setUnits(Type units) { - // TODO Auto-generated method stub - // one day may allow units other than substitutions - - } - - - -} diff --git a/src/dr/evomodel/alloppnet/speciation/AlloppMulLabTree.java b/src/dr/evomodel/alloppnet/speciation/AlloppMulLabTree.java deleted file mode 100644 index dc71003b82..0000000000 --- a/src/dr/evomodel/alloppnet/speciation/AlloppMulLabTree.java +++ /dev/null @@ -1,1050 +0,0 @@ - - -/* - * AlloppMulLabTree.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.alloppnet.speciation; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.Formatter; -import java.util.Locale; -import java.util.Stack; - -import dr.evolution.tree.*; -import jebl.util.FixedBitSet; -import dr.evolution.util.Taxon; -import dr.inference.model.Parameter; -import dr.evomodel.alloppnet.util.AlloppMisc; - - - - - -/** - * An AlloppMulLabTree represents the species network as single - * binary tree with tips that can be multiply labelled with species. - * - * @author Graham Jones - * Date: 13/09/2011 - */ - - -/* - * An AlloppMulLabTree represents the species network as single - * binary tree with tips that can be multiply labelled with species. - * - * classes LegLink and FootLinks are for gathering and organising - * the links between trees of different ploidy, so that the - * rootward-pointing legs can become tipward-pointing branches. - * - * SpSqUnion is used for sorting the nodes in an AlloppMulLabTree. It is - * used by Comparator SPUNION_ORDER, and hence indirectly by - * fillinpopvals(). - * - * class BranchPopulationAndLineages records the information needed - * to calculate the probability of coalescences in a single branch of the - * AlloppMulLabTree. - * - */ - - -/* mlnodes[], rootn implement the tree; nextn is for building it - * - * apsp references the (species, indivs, sequences) structure. - * - * popvals references the population parameters. fillinpopvals() assigns - * them to branches. - * - * simptree is so that AlloppSpeciesNetworkModel, which contains a AlloppMulLabTree, - * can implement the Tree interface. - */ -public class AlloppMulLabTree { - private MulLabNode[] mlnodes; - private int rootn; - private int nextn; - private AlloppSpeciesBindings apsp; - private Parameter tippopvals; - private Parameter rootpopvals; - private double [] hybpopvals; - private int nofhybpopvals; - public SimpleTree simptree; - - - - - /* - * parent, child[] join the nodes into a binary tree. - * - * height is time into past - * - * popsize is population at start of branch, and for tips, also at end. - * - * union is a set of species for a single choice of sequence copy from - * each individual of the species. There is one bit for each Taxon like - * "c0" or "c1" - */ - private class MulLabNode extends AlloppNode.Abstract implements AlloppNode, NodeRef { - private int nodeNumber; - private int anc; - private int lft; - private int rgt; - private double height; - private boolean tetraroot; // true iff this node is root of a teraploid subtree - private boolean intetratree; // true iff this is in a tetratree - private boolean tetraancestor; // true iff this is a node with no diploid tip descendants - private int ttreeindex; - private double hybridheight; - private FixedBitSet union; - private ArrayList coalheights; - private int nlineages; - private Taxon taxon; - private int tippopindex; - private int hybpopindex; - private int rootpopindex; - - // dud constuctor - MulLabNode(int nn) { - nodeNumber = nn; - anc = -1; - lft = -1; - rgt = -1; - height = -1.0; - tetraroot = false; - intetratree = false; - tetraancestor = false; - ttreeindex = -1; - hybridheight = -1.0; - coalheights = new ArrayList(); - taxon = new Taxon(""); - tippopindex = -1; - hybpopindex = -1; - rootpopindex = -1; - } - - - public double tippop() { - return tippopvals.getParameterValue(tippopindex); - } - - public double hybpop() { - return hybpopvals[hybpopindex]; - } - - public double rootpop() { - return rootpopvals.getParameterValue(rootpopindex); - } - - @Override - public String asText(int indentlen) { - StringBuilder s = new StringBuilder(); - Formatter formatter = new Formatter(s, Locale.US); - if (lft < 0) { - formatter.format("%s ", taxon.getId()); - } else { - formatter.format("%s ", "+"); - } - while (s.length() < 20-indentlen) { - formatter.format("%s", " "); - } - formatter.format("%s ", AlloppMisc.nonnegIn8Chars(height)); - formatter.format("%60s ", AlloppMisc.FixedBitSetasText(union)); - double tippop = (tippopindex >= 0) ? tippop() : -1.0; - formatter.format("%s %s ", AlloppMisc.nonnegIntIn2Chars(tippopindex), AlloppMisc.nonnegIn8Chars(tippop)); - double hybpop = (hybpopindex >= 0) ? hybpop() : -1.0; - formatter.format("%s %s ", AlloppMisc.nonnegIntIn2Chars(hybpopindex), AlloppMisc.nonnegIn8Chars(hybpop)); - double rootpop = (rootpopindex >= 0) ? rootpop() : -1.0; - formatter.format("%s %s ", AlloppMisc.nonnegIntIn2Chars(rootpopindex), AlloppMisc.nonnegIn8Chars(rootpop)); - formatter.format("%s ", tetraroot ? "tetroot" : " "); - formatter.format("%s ", AlloppMisc.nonnegIn8Chars(hybridheight)); - formatter.format("%3d ", nlineages); - for (int c = 0; c < coalheights.size(); c++) { - formatter.format(AlloppMisc.nonnegIn8Chars(coalheights.get(c)) + ","); - } - return s.toString(); - } - - - @Override - public int nofChildren() { - return ((lft < 0) ? 0 : 2); - } - - - @Override - public AlloppNode getChild(int ch) { - return ch==0 ? mlnodes[lft] : mlnodes[rgt]; - } - - - @Override - public AlloppNode getAnc() { - return mlnodes[anc]; - } - - - - @Override - public double getHeight() { - return height; - } - - - @Override - public FixedBitSet getUnion() { - return union; - } - - - @Override - public void setChild(int ch, AlloppNode newchild) { - int newch = ((MulLabNode)newchild).nodeNumber; - if (ch == 0) { - lft = newch; - } else { - rgt = newch; - } - } - - - @Override - public void setAnc(AlloppNode anc) { - this.anc = ((MulLabNode)anc).nodeNumber; - } - - @Override - public Taxon getTaxon() { - return taxon; - } - - - @Override - public void setTaxon(String name) { - taxon = new Taxon(name); - } - - - @Override - public void setHeight(double height) { - this.height = height; - } - - - @Override - public void setUnion(FixedBitSet union) { - this.union = union; - - } - - - @Override - public void addChildren(AlloppNode c0, AlloppNode c1) { - lft = ((MulLabNode)c0).nodeNumber; - mlnodes[lft].anc = nodeNumber; - rgt = ((MulLabNode)c1).nodeNumber; - mlnodes[rgt].anc = nodeNumber; - } - - - @Override - public int getNumber() { - return nodeNumber; - } - - @Override - public void setNumber(int nn) { - nodeNumber = nn; - } - } - - - private class SpSqUnion { - public FixedBitSet spsqunion; - public FixedBitSet spunion; - public SpSqUnion(FixedBitSet spsqunion) { - this.spsqunion = spsqunion; - spunion = apsp.spsqunion2spunion(spsqunion); - } - } - - - private class PopulationAndLineages { - public double t[]; - public double tippop; - public double rootpop; - public int tipnlin; - - public PopulationAndLineages(double[] t2, double tippop, double rootpop, - int tipnlin) { - this.t = t2; - this.tippop = tippop; - this.rootpop = rootpop; - this.tipnlin = tipnlin; - } - - public double populationAt(double x) { - final double begt = t[0]; - final double endt = t[t.length - 1]; - return ((endt-x)*tippop + (x-begt)*rootpop) / (endt-begt); - } - } - - - - - /* - * This constructor makes a single multiply labelled tree from the diploid - * history and set of tetraploid AlloppLeggedTrees which is passed to it. It is called directly - * by testing code. - */ - AlloppMulLabTree(AlloppDiploidHistory adhist, ArrayList tettrees, - AlloppSpeciesBindings apsp, Parameter tippopvals, Parameter rootpopvals, double [] hybpopvals) { - this.apsp = apsp; - this.tippopvals = tippopvals; - this.rootpopvals = rootpopvals; - this.hybpopvals = hybpopvals; - nofhybpopvals = tettrees.size(); - // Count tips for the tree to be made - int ntips = 0; - ntips += adhist.getDiploidTipCount(); - for (AlloppLeggedTree ttree : tettrees) { - ntips += 2 * ttree.getExternalNodeCount(); - } - // Make array of dud nodes - mlnodes = new MulLabNode[2 * ntips - 1]; - for (int i = 0; i < mlnodes.length; i++) { - mlnodes[i] = new MulLabNode(i); - mlnodes[i].tetraancestor = true; - } - // get dip hist and tetratrees into array; unions are filled at tips - nextn = 0; - nextn = subtree2MulLabNodes(adhist, adhist.getRootIndex(), tettrees, apsp); - rootn = nextn - 1; - // fill unions from tips - mlnodes[rootn].fillinUnionsInSubtree(apsp.numberOfSpSeqs()); - // The tetraroot flags were initialised false, set to final values by subtree2MulLabNodes() - // The tetraancestor flags were initialised true, diploid tips later set false by subtree2MulLabNodes() - // The intetratree flags were initialised false, tetraploid tips later set true by allopptree2MulLabNodes() - // Now fill in tetraancestor and intetratree flags from tips. - fillinTetraFlagsInSubtree(mlnodes[rootn]); - makesimpletree(); - } - - - - - - // constructor for testing conversion of diploid history plus tetraploid trees to MUL-tree - public AlloppMulLabTree(AlloppDiploidHistory adhist, ArrayList tettrees, AlloppSpeciesBindings apsp, - Parameter testtippopvalues, Parameter testrootpopvalues, double [] testhybpopvalues, int testcase) { - this(adhist, tettrees, apsp, testtippopvalues, testrootpopvalues, testhybpopvalues); - assert testcase >= 1; - assert testcase <= 5; - fillinpopvals(); - } - - - // constructor for testing likelihood calculations. - // Makes a particular multree with nlineages, coalheights so test can call - // geneTreeInMULTreeLogLikelihood() - public AlloppMulLabTree(AlloppSpeciesBindings apsp) { - this.apsp = apsp; - nofhybpopvals = 1; - tippopvals = new Parameter.Default(3, .003); - rootpopvals = new Parameter.Default(4, .001); - hybpopvals = new double[1]; - hybpopvals[0] = .001; - fillmlnodesforlhoodtest1(); - fillinTetraFlagsInSubtree(mlnodes[rootn]); - mlnodes[rootn].fillinUnionsInSubtree(4); - } - - - public double testGeneTreeInMULTreeLogLikelihood() { - return geneTreeInMULTreeLogLikelihood(); - } - - private void fillmlnodesforlhoodtest1() { - mlnodes = new MulLabNode[7]; - for (int i = 0; i < mlnodes.length; i++) { - mlnodes[i] = new MulLabNode(i); - } - // 4 tips, 2 dips, 1 tet - mlnodes[0].taxon = new Taxon("a"); - mlnodes[1].taxon = new Taxon("b"); - mlnodes[2].taxon = new Taxon("z0"); - mlnodes[3].taxon = new Taxon("z1"); - mlnodes[2].tetraancestor = true; - mlnodes[3].tetraancestor = true; - mlnodes[2].intetratree = true; - mlnodes[3].intetratree = true; - mlnodes[2].tetraroot = true; - mlnodes[3].tetraroot = true; - mlnodes[0].union = new FixedBitSet(4); mlnodes[0].union.set(0); - mlnodes[1].union = new FixedBitSet(4); mlnodes[1].union.set(1); - mlnodes[2].union = new FixedBitSet(4); mlnodes[2].union.set(2); - mlnodes[3].union = new FixedBitSet(4); mlnodes[3].union.set(3); - // toplogy and times - mlnodes[4].addChildren(mlnodes[0], mlnodes[2]); - mlnodes[5].addChildren(mlnodes[1], mlnodes[3]); - mlnodes[6].addChildren(mlnodes[4], mlnodes[5]); - rootn = 6; - mlnodes[0].height = 0.0; - mlnodes[1].height = 0.0; - mlnodes[2].height = 0.0; - mlnodes[3].height = 0.0; - mlnodes[4].height = 0.01; - mlnodes[5].height = 0.02; - mlnodes[6].height = 0.03; - mlnodes[2].hybridheight = 0.005; - mlnodes[3].hybridheight = 0.005; - // nlineages and coalheights - mlnodes[0].nlineages = 1; - mlnodes[1].nlineages = 2; - mlnodes[2].nlineages = 1; - mlnodes[3].nlineages = 1; - mlnodes[4].nlineages = 2; - mlnodes[4].coalheights.add(0.015); - mlnodes[5].nlineages = 3; - mlnodes[5].coalheights.add(0.025); - mlnodes[6].nlineages = 3; - mlnodes[6].coalheights.add(0.035); - mlnodes[6].coalheights.add(0.045); - } - - - - // For testing. - boolean mullabtreeOK() { - int nroots = 0; - for (int i = 0; i < mlnodes.length; i++) { - if (mlnodes[i].anc < 0) { - nroots++; - } - } - if (nroots != 1) { - return false; - } - for (int i = 0; i < mlnodes.length; i++) { - int nparents = 0; - for (int j = 0; j < mlnodes.length; j++) { - if (mlnodes[j].lft == i) { nparents++; } - if (mlnodes[j].rgt == i) { nparents++; } - } - if (mlnodes[i].anc < 0 && nparents != 0) { - return false; - } - if (mlnodes[i].anc >= 0 && nparents != 1) { - return false; - } - } - for (int i = 0; i < mlnodes.length; i++) { - if (mlnodes[i].getNumber() != i) { - return false; - } - } - for (int i = 0; i < mlnodes.length; i++) { - if (mlnodes[i].lft >= 0) { - if (mlnodes[i].rgt < 0) { - return false; - } - int lft = mlnodes[i].lft; - int rgt = mlnodes[i].rgt; - if (mlnodes[lft].anc != i) { - return false; - } - if (mlnodes[rgt].anc != i) { - return false; - } - if (mlnodes[i].height <= mlnodes[lft].height) { - return false; - } - if (mlnodes[i].height <= mlnodes[rgt].height) { - return false; - } - } else { - if (mlnodes[i].height != 0) { - return false; - } - } - } - if (mlnodes[rootn].anc >= 0) { - return false; - } - return true; - } - - - - String mullabTreeAsNewick() { - String s = TreeUtils.uniqueNewick(simptree, simptree.getRoot()); - return s; - } - - String asText() { - String header = "MUL-tree height union [] tippop [] hybpop [] rootpop tetroot hybhgt nlin coalheights" + System.getProperty("line.separator"); - - String s = ""; - Stack x = new Stack(); - return header + AlloppNode.Abstract.subtreeAsText(mlnodes[rootn], s, x, 0, ""); - } - - - void clearCoalescences() { - clearSubtreeCoalescences(mlnodes[rootn]); - } - - void recordLineageCounts() { - recordSubtreeLineageCounts(mlnodes[rootn]); - } - - boolean coalescenceIsCompatible(double height, FixedBitSet union) { - MulLabNode node = (MulLabNode) mlnodes[rootn].nodeOfUnionInSubtree(union); - return (node.height <= height); - } - - - void recordCoalescence(double height, FixedBitSet union) { - MulLabNode node = (MulLabNode) mlnodes[rootn].nodeOfUnionInSubtree(union); - assert (node.height <= height); - while (node.anc >= 0 && mlnodes[node.anc].height <= height) { - node = mlnodes[node.anc]; - } - node.coalheights.add(height); - } - - void sortCoalescences() { - for (MulLabNode node : mlnodes) { - Collections.sort(node.coalheights); - } - } - - - double geneTreeInMULTreeLogLikelihood() { - fillinpopvals(); - //System.out.println(asText()); - return geneTreeInMULSubtreeLogLikelihood(mlnodes[rootn]); - } - - - - - -/* -* -* *************************************************** -* Private -*/ - - - - private void fillinTetraFlagsInSubtree(AlloppNode node) { - if (node.nofChildren() == 2) { - MulLabNode mnode = (MulLabNode)node; - MulLabNode ch0 = (MulLabNode)node.getChild(0); - MulLabNode ch1 = (MulLabNode)node.getChild(1); - fillinTetraFlagsInSubtree(node.getChild(0)); - fillinTetraFlagsInSubtree(node.getChild(1)); - mnode.tetraancestor = (ch0.tetraancestor && ch1.tetraancestor); - mnode.intetratree = (ch0.intetratree && !ch0.tetraroot && ch1.intetratree && !ch1.tetraroot); - } - } - - - private int subtree2MulLabNodes(AlloppDiploidHistory adhist, int dhni, ArrayList tettrees, AlloppSpeciesBindings apsp) { - if (adhist.getLftFromIndex(dhni) < 0) { - int tt = adhist.getNodeTettree(dhni); - if (tt < 0) { - mlnodes[nextn].setTaxon(adhist.getTaxonFromIndex(dhni).getId()); - mlnodes[nextn].setUnion(apsp.taxonseqToTipUnion(mlnodes[nextn].taxon, 0)); - mlnodes[nextn].setHeight(adhist.getHeightFromIndex(dhni)); - mlnodes[nextn].tetraancestor = false; - nextn++; - } else { - AlloppNode troot = (AlloppNode)tettrees.get(tt).getSlidableRoot(); - int seq = (adhist.getNodeLeg(dhni) == AlloppDiploidHistory.LegLorR.left) ? 0 : 1; - nextn = allopptree2MulLabNodes(apsp, troot, seq); - mlnodes[nextn-1].hybridheight = adhist.getHeightFromIndex(dhni); - mlnodes[nextn-1].tetraroot = true; - mlnodes[nextn-1].ttreeindex = tt; - } - } else { - nextn = subtree2MulLabNodes(adhist, adhist.getLftFromIndex(dhni), tettrees, apsp); - int c0 = nextn - 1; - nextn = subtree2MulLabNodes(adhist, adhist.getRgtFromIndex(dhni), tettrees, apsp); - int c1 = nextn - 1; - mlnodes[nextn].addChildren(mlnodes[c0], mlnodes[c1]); - mlnodes[nextn].setHeight(adhist.getHeightFromIndex(dhni)); - nextn++; - } - return nextn; - } - - - - private int allopptree2MulLabNodes(AlloppSpeciesBindings apsp, - AlloppNode snode, int seq) { - if (snode.nofChildren() == 0) { - mlnodes[nextn].setTaxon(snode.getTaxon().getId() + seq); - mlnodes[nextn].setUnion(apsp.taxonseqToTipUnion(snode.getTaxon(), seq)); - mlnodes[nextn].intetratree = true; - } else { - nextn = allopptree2MulLabNodes(apsp, snode.getChild(0), seq); - int c0 = nextn - 1; - nextn = allopptree2MulLabNodes(apsp, snode.getChild(1), seq); - int c1 = nextn - 1; - mlnodes[nextn].addChildren(mlnodes[c0], mlnodes[c1]); - } - mlnodes[nextn].setHeight(snode.getHeight()); - nextn++; - return nextn; - } - - - - - - private void makesimpletree() { - SimpleNode[] snodes = new SimpleNode[mlnodes.length]; - for (int n = 0; n < mlnodes.length; n++) { - snodes[n] = new SimpleNode(); - } - makesimplesubtree(snodes, 0, mlnodes[rootn]); - simptree = new SimpleTree(snodes[mlnodes.length-1]); - } - - - private int makesimplesubtree(SimpleNode[] snodes, int nextsn, MulLabNode mnode) { - if (mnode.lft < 0) { - snodes[nextsn].setTaxon(new Taxon(mnode.taxon.getId())); - } else { - nextsn = makesimplesubtree(snodes, nextsn, mlnodes[mnode.lft]); - int subtree0 = nextsn-1; - nextsn = makesimplesubtree(snodes, nextsn, mlnodes[mnode.rgt]); - int subtree1 = nextsn-1; - snodes[nextsn].addChild(snodes[subtree0]); - snodes[nextsn].addChild(snodes[subtree1]); - } - snodes[nextsn].setHeight(mnode.height); - String tti; - if (mnode.ttreeindex < 0) { - tti = "X"; - } else { - tti = "T" + mnode.ttreeindex; - } - snodes[nextsn].setAttribute("tti", tti); - if (mnode.hybridheight >= 0.0) { - snodes[nextsn].setAttribute("hybhgt", mnode.hybridheight); - } - return nextsn+1; - } - - - private void clearSubtreeCoalescences(MulLabNode node) { - if (node.lft >= 0) { - clearSubtreeCoalescences(mlnodes[node.lft]); - clearSubtreeCoalescences(mlnodes[node.rgt]); - } - node.coalheights.clear(); - } - - - private void recordSubtreeLineageCounts(MulLabNode node) { - if (node.lft < 0) { - node.nlineages = apsp.nLineages(apsp.spseqindex2sp(union2spseqindex(node.union))); - } else { - node.nlineages = 0; - recordSubtreeLineageCounts(mlnodes[node.lft]); - recordSubtreeLineageCounts(mlnodes[node.rgt]); - node.nlineages += mlnodes[node.lft].nlineages - mlnodes[node.lft].coalheights.size(); - node.nlineages += mlnodes[node.rgt].nlineages - mlnodes[node.rgt].coalheights.size(); - } - } - - - - /* - * This copies population values in the Parameter popvalues - * to nodes in the AlloppMulLabTree. The population values are - * per-species-clade (per-branch in network), but of course more than - * one node in AlloppMulLabTree may correspond to the same species. - * - * The other complications are that tips are different from internal - * nodes, and that nodes which roots of tetratrees or just below, - * as well as the root are special cases. - * - * It collects unions (which represent sets whose elements - * identify a species and a sequence) from the nodes and then - * sorts them primarily using identities of the species, so - * that sets of node with same species clade are grouped together. The sort - * also puts the node sets corresponding to tips first in the array and sorts - * nodes within node sets in a well-defined way. - * This mainly does what is required, since nodes with the same - * species clade are treated the same. - * - * fillinpopvalsforspunion() deals with a set of nodes - * with same species clade. - */ - private void fillinpopvals() { - ArrayList unionarraylist = new ArrayList(); - for (int n = 0; n < mlnodes.length; n++) { - unionarraylist.add(new SpSqUnion(mlnodes[n].union)); - } - Collections.sort(unionarraylist, SPUNION_ORDER); - SpSqUnion[] unionarray = new SpSqUnion[unionarraylist.size()]; - unionarray = unionarraylist.toArray(unionarray); - PopValIndices pvis = new PopValIndices(0,0,0); - // set all pop indices to dud values - for (int n = 0; n < mlnodes.length; n++) { - mlnodes[n].tippopindex = -1; - mlnodes[n].rootpopindex = -1; - mlnodes[n].hybpopindex = -1; - } - int noftippopvals = tippopvals.getDimension(); - int nofrootpopvals = rootpopvals.getDimension(); - for (int n0 = 0; n0 < unionarray.length; ) { - int n1 = n0+1; - while (n1 < unionarray.length && unionarray[n1].spunion.equals(unionarray[n0].spunion)) { - n1++; - } - assert pvis.tipp <= noftippopvals; - if (!(pvis.rootp <= nofrootpopvals)) { - System.out.println("BUG in fillinpopvals()"); - } - assert pvis.rootp <= nofrootpopvals; - assert pvis.hybp <= nofhybpopvals; - pvis = fillinpopvalsforspunion(unionarray, n0, n1, pvis); - n0 = n1; - } - if (pvis.tipp != noftippopvals || pvis.rootp != nofrootpopvals || pvis.hybp != nofhybpopvals) { - System.out.println("BUG in fillinpopvals()"); - } - assert pvis.tipp == noftippopvals; - assert pvis.rootp == nofrootpopvals; - assert pvis.hybp == nofhybpopvals; - } - - - private class PopValIndices { - public int tipp; - public int rootp; - public int hybp; - PopValIndices(int tipp, int rootp, int hybp) { - this.tipp = tipp; - this.rootp = rootp; - this.hybp = hybp; - } - } - - - private PopValIndices fillinpopvalsforspunion(SpSqUnion[] unionarray, int n0, int n1, PopValIndices pvis) { - int n = n1-n0; - MulLabNode nodeset[] = new MulLabNode[n]; - // get set of nodes with same species clade - for (int i = n0; i < n1; i++) { - nodeset[i-n0] = (MulLabNode) mlnodes[rootn].nodeOfUnionInSubtree(unionarray[i].spsqunion); - } - // Hybridization pops. Nodes in pairs, shared pop. - if (nodeset[0].tetraroot) { - assert n >= 2; - assert nodeset[1].tetraroot; - for (int i = 0; i < 2; i++) { - nodeset[i].hybpopindex = pvis.hybp; - } - pvis.hybp++; - } - // Tip pops. Either dip or tet; in latter case shared pop. - int ntips = 0; - for (int i = 0; i < n; i++) { - if (nodeset[i].lft < 0) { - nodeset[i].tippopindex = pvis.tipp; - ntips++; - } - } - assert ntips <= 2; - if (ntips > 0) { - pvis.tipp++; - } - - // Root pops within tetra trees. Nodes in pairs. - if (nodeset[0].intetratree && !nodeset[0].tetraroot) { - if (n != 2) { - System.out.println("BUG in fillinpopvalsforspunion() 2"); - } - assert n == 2; - assert (nodeset[1].intetratree && !nodeset[1].tetraroot); - for (int i = 0; i < 2; i++) { - nodeset[i].rootpopindex = pvis.rootp; - } - pvis.rootp++; - } else { - // Root pops NOT within tetra trees. Here the nodeset[] structure is not useful. - // Here, pop is shared with sibling if either is ancestor to tetraploids only - for (int i = 0; i < n; i++) { - MulLabNode node = nodeset[i]; - if (node.anc >= 0) { - MulLabNode sibling = siblingOfNode(node); - if (node.tetraancestor || sibling.tetraancestor) { - if (sibling.rootpopindex >= 0) { - node.rootpopindex = sibling.rootpopindex; - } else { - node.rootpopindex = pvis.rootp; - pvis.rootp++; - } - } else { - node.rootpopindex = pvis.rootp; - pvis.rootp++; - } - } - } - } - - return pvis; - } - - - - private MulLabNode siblingOfNode(MulLabNode node) { - assert node.anc >= 0; - MulLabNode sibling; - if (mlnodes[ mlnodes[node.anc].lft ] == node) { - sibling = mlnodes[ mlnodes[node.anc].rgt ]; - } else { - assert mlnodes[ mlnodes[node.anc].rgt ] == node; - sibling = mlnodes[ mlnodes[node.anc].lft ]; - } - return sibling; - } - - - - /* - * Visits each node in MULtree and accumulates LogLikelihood - */ - private double geneTreeInMULSubtreeLogLikelihood(MulLabNode node) { - double loglike = 0.0; - if (node.lft >= 0) { - loglike += geneTreeInMULSubtreeLogLikelihood(mlnodes[node.lft]); - loglike += geneTreeInMULSubtreeLogLikelihood(mlnodes[node.rgt]); - } - loglike += branchLLInMULtree(node); - - return loglike; - } - - - /* - * Does likelihood calculation for a single node in the case - * of two diploids. - */ - private double branchLLInMULtree(MulLabNode node) { - double loglike = 0.0; - - double tippop = 0.0; - if (node.lft < 0) { - tippop = node.tippop(); - } else { - tippop = mlnodes[node.lft].rootpop() + mlnodes[node.rgt].rootpop(); - } - - PopulationAndLineages pal; - double t[]; - if (node.tetraroot) { - // since hybridization - int nsince = 0; - for ( ; nsince < node.coalheights.size() && - node.coalheights.get(nsince) < node.hybridheight; nsince++) {} - t = new double[nsince + 2]; - t[0] = node.height; - for (int i = 0; i < nsince; i++) { - t[i+1] = node.coalheights.get(i); - } - t[t.length-1] = node.hybridheight; - pal = new PopulationAndLineages(t, tippop, node.hybpop(), node.nlineages); - loglike += limbLogLike(pal); - if (Double.isNaN(loglike)) { - System.out.println("BUG in branchLLInMULtree"); - } - // before hybridization - int nbefore = node.coalheights.size() - nsince; - t = new double[nbefore + 2]; - t[0] = node.hybridheight; - for (int i = 0; i < nbefore; i++) { - t[i+1] = node.coalheights.get(nsince+i); - } - t[t.length-1] = mlnodes[node.anc].height; - - pal = new PopulationAndLineages(t, node.rootpop(), node.rootpop(), node.nlineages - nsince); - loglike += limbLogLike(pal); - } else if (node.anc < 0) { - t = new double[node.coalheights.size() + 2]; - t[0] = node.height; - t[t.length-1] = apsp.maxGeneTreeHeight(); - for (int i = 0; i < node.coalheights.size(); i++) { - t[i+1] = node.coalheights.get(i); - } - pal = new PopulationAndLineages(t, tippop, tippop, node.nlineages); - loglike += limbLogLike(pal); - } else { - t = new double[node.coalheights.size() + 2]; - t[0] = node.height; - t[t.length-1] = mlnodes[node.anc].height; - for (int i = 0; i < node.coalheights.size(); i++) { - t[i+1] = node.coalheights.get(i); - } - pal = new PopulationAndLineages(t, tippop, node.rootpop(), node.nlineages); - loglike += limbLogLike(pal); - } - if (Double.isNaN(loglike)) { - System.out.println("BUG in branchLLInMULtree"); - } - return loglike; - } - - - - - /* - * limbLogLike calculates the log-likelihood for - * the coalescences at t[1],t[2],...t[k] within a limb - * from t[0] to t[k+1]. ('limb' means a branch or part of one.) - */ - private double limbLogLike(PopulationAndLineages pal) { - double loglike = 0.0; - int k = pal.t.length - 2; - for (int i = 1; i <= k; i++) { - loglike -= Math.log(pal.populationAt(pal.t[i])); - } - for (int i = 0; i <= k; i++) { - final double y = (pal.tipnlin-i) * (pal.tipnlin-i-1) / 2 ; - final double z = limbLinPopIntegral(pal, pal.t[i], pal.t[i+1]); - loglike -= y * z; - } - if (Double.isNaN(loglike)) { - System.out.println("BUG in limbLogLike"); - } - return loglike; - } - - - - // integral from t0 to t1 of (endt-begt)/((endt-x)begPop + (x-begt)endPop) - // with respect to x - private double limbLinPopIntegral(PopulationAndLineages b, double t0, double t1) { - final double begt = b.t[0]; - final double endt = b.t[b.t.length-1]; - if (b.rootpop < 1E-20) { - System.out.println("Underflow in limbLinPopIntegral()"); - } - final double d = b.rootpop - b.tippop; - final double c = endt * b.tippop - begt * b.rootpop; - final double x = Math.abs(d / b.tippop); - if (x > 0.001) { - return ((endt - begt) / d) * Math.log((c + d * t1) / (c + d * t0)); - } else { - double y = d * (t1 - t0) / (c + d * t0); - double ys = (1.0 - y/2.0 + y*y * (1.0/3.0 - y/4.0 + y*y * (1.0/5.0 - y/6.0))); - return ((endt - begt) * (t1 - t0) / (c + d * t0)) * ys; - } - } - - - - - private static int union2spseqindex(FixedBitSet union) { - assert union.cardinality() == 1; - return union.nextOnBit(0); - } - - - - - /* - * This is for ordering the unions in the nodes of the AlloppMulLabTree. - * Those unions are of (species, sequence) pairs. - * - * The comparator sorts the unions of (species, sequence) pairs (SpSqUnions) - * so that all unions containing the same set of species (ignoring sequence) - * are grouped together. Call the sets of SpSqUnions for the same species a - * `group'. There can be 1,2 or 3 SpSqUnions in a group. - * - * The groups are sorted in order of increasing number of species (clade size). - * All groups for a single species (a tip in the network) come first, then - * those groups for two species, and so on to the root for all species. - * For groups that have equal numbers of species, a lexicographical - * ordering using species indices is used. - * - * Within each group, species and sequence information is used to sort the 1 to 3 - * SpSqUnions. The size of the `clade' of (species, sequence) pairs is used - * first in the comparison, which ensures that the three nodes with the same species - * - corresponding to two roots of tetratrees in the AlloppMulLabTree plus a leg-join - - * are ordered so that the two roots come first. - * - */ - - static final Comparator SPUNION_ORDER = new Comparator() { - public int compare(SpSqUnion a, SpSqUnion b) { - int ac = a.spunion.cardinality(); - int bc = b.spunion.cardinality(); - if (ac != bc) { - return ac-bc; - } else { - int an = a.spunion.nextOnBit(0); - int bn = b.spunion.nextOnBit(0); - while (an >= 0 || bn >= 0) { - if (an != bn) { - return an-bn; - } - an = a.spunion.nextOnBit(an+1); - bn = b.spunion.nextOnBit(bn+1); - } - // spunions compare equal; do spsqunions - ac = a.spsqunion.cardinality(); - bc = b.spsqunion.cardinality(); - if (ac != bc) { - return ac-bc; - } else { - an = a.spsqunion.nextOnBit(0); - bn = b.spsqunion.nextOnBit(0); - while (an >= 0 || bn >= 0) { - if (an != bn) { - return an-bn; - } - an = a.spsqunion.nextOnBit(an+1); - bn = b.spsqunion.nextOnBit(bn+1); - } - return 0; - } - } - } - }; - - - - -} diff --git a/src/dr/evomodel/alloppnet/speciation/AlloppNetworkPrior.java b/src/dr/evomodel/alloppnet/speciation/AlloppNetworkPrior.java deleted file mode 100644 index 65512453f1..0000000000 --- a/src/dr/evomodel/alloppnet/speciation/AlloppNetworkPrior.java +++ /dev/null @@ -1,148 +0,0 @@ -/* - * AlloppNetworkPrior.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.alloppnet.speciation; - -import dr.inference.distribution.ParametricDistributionModel; -import dr.inference.model.Likelihood; -import dr.inference.model.Parameter; - -import java.util.ArrayList; - - -/** - * - * Calculates prior likelihood for an allopolyploid network. - * - * @author Graham Jones - * Date: 01/07/2011 - */ - - - - - -public class AlloppNetworkPrior extends Likelihood.Abstract { - AlloppSpeciesNetworkModel asnm; - AlloppNetworkPriorModel prior; - double numHybsLogL[]; - - - - public AlloppNetworkPrior(AlloppNetworkPriorModel prior, AlloppSpeciesNetworkModel asnm) { - super(prior); - this.asnm = asnm; - this.prior = prior; - asnm.setHybPopModel(prior.getHybridPopModel()); - - int ndips = asnm.getNofDiploids(); - numHybsLogL = new double[asnm.maxNumberOfHybPopParameters()+1]; - for (int h = 0; h < numHybsLogL.length; h++) { - numHybsLogL[h] = -h * Math.log(7.0*Math.sqrt(ndips)); - // grjtodo-soon the form of the function is experimental - } - - - } - - - - @Override - protected boolean getLikelihoodKnown() { - return false; - } - - @Override - protected double calculateLogLikelihood() { - double llhood = 0.0; - //network topology and times prior - llhood += loglikelihoodEvents(); - //System.out.print(llhood); System.out.print(" "); - llhood += loglikeNumHybridizations(); - //System.out.print(llhood); System.out.print(" "); - // population prior for tips - Parameter tippvals = asnm.getTipPopValues(); - ParametricDistributionModel tipmodel = prior.getTipPopModel(); - for (int i = 0; i < tippvals.getDimension(); i++) { - llhood += tipmodel.logPdf(tippvals.getParameterValue(i)); - } - // population prior for root ends - Parameter rootpvals = asnm.getRootPopValues(); - ParametricDistributionModel rootmodel = prior.getRootPopModel(); - for (int i = 0; i < rootpvals.getDimension(); i++) { - llhood += rootmodel.logPdf(rootpvals.getParameterValue(i)); - } - // population prior for new hybrids - ParametricDistributionModel hybmodel = prior.getHybridPopModel(); - for (int i = 0; i < asnm.getNumberOfTetraTrees(); i++) { - llhood += hybmodel.logPdf(asnm.getOneHybPopValue(i)); - } - //System.out.println(llhood); - return llhood; - } - - - - - - private double loglikeNumHybridizations() { - int nhybs = asnm.getNumberOfTetraTrees(); - //System.out.print(nhybs); System.out.print(" "); - return numHybsLogL[nhybs]; - } - - - /* - * Going backwards in time this gives probabilities to three types - * of events: diploid-diploid joins, tet-tet joins, and hybridization events. - */ - private double loglikelihoodEvents() { - - double lambda = prior.getRate().getParameterValue(0); - - ArrayList heights = new ArrayList(); - - AlloppDiploidHistory adhist = asnm.getDiploidHistory(); - adhist.collectInternalAndHybHeights(heights); - int nttrees = asnm.getNumberOfTetraTrees(); - for (int tt = 0; tt < nttrees; tt++) { - AlloppLeggedTree ttree = asnm.getTetraploidTree(tt); - ttree.collectInternalHeights(heights); - } - double loglhood = 0.0; - for (double t : heights) { - loglhood += logexpPDF(t, lambda); - } - return loglhood; - } - - - private double logexpPDF(double x, double rate) { - return Math.log(rate) - rate*x; - } - -} diff --git a/src/dr/evomodel/alloppnet/speciation/AlloppNetworkPriorModel.java b/src/dr/evomodel/alloppnet/speciation/AlloppNetworkPriorModel.java deleted file mode 100644 index 5e1cc44b0e..0000000000 --- a/src/dr/evomodel/alloppnet/speciation/AlloppNetworkPriorModel.java +++ /dev/null @@ -1,146 +0,0 @@ -/* - * AlloppNetworkPriorModel.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.alloppnet.speciation; - -import dr.evolution.util.Units; -import dr.evomodel.alloppnet.parsers.AlloppNetworkPriorModelParser; -import dr.inference.distribution.ParametricDistributionModel; -import dr.inference.model.AbstractModel; -import dr.inference.model.Model; -import dr.inference.model.Parameter; -import dr.inference.model.Variable; -import dr.inference.model.Variable.ChangeType; - - - -/** - * - * Model for prior of an allopolyploid network. - * - * @author Graham Jones - * Date: 01/07/2011 - */ - - -/* - - - - - - */ - -public class AlloppNetworkPriorModel extends AbstractModel implements Units { - private Parameter rate; - private Parameter popsf; - private ParametricDistributionModel tpmodel; - private ParametricDistributionModel rpmodel; - private ParametricDistributionModel hpmodel; - private Units.Type units; - - - public AlloppNetworkPriorModel(Parameter eventrate, Parameter popscalingfactor, - ParametricDistributionModel tippopmodel, ParametricDistributionModel rootpopmodel, - ParametricDistributionModel hybpopmodel, Units.Type units) { - super(AlloppNetworkPriorModelParser.ALLOPPNETWORKPRIORMODEL); - this.rate = eventrate; - this.popsf = popscalingfactor; - this.tpmodel = tippopmodel; - this.rpmodel = rootpopmodel; - this.hpmodel = hybpopmodel; - this.units = units; - addVariable(rate); - addVariable(popsf); - } - - - Parameter getRate() { - return rate; - } - - - Parameter getPopScalingFactor() { - return popsf; - } - - ParametricDistributionModel getTipPopModel() { - return tpmodel; - } - - ParametricDistributionModel getRootPopModel() { - return rpmodel; - } - - ParametricDistributionModel getHybridPopModel() { - return hpmodel; - } - - - @Override - protected void handleModelChangedEvent(Model model, Object object, int index) { - if (AlloppSpeciesNetworkModel.DBUGTUNE) - System.out.println("AlloppNetworkPriorModel.handleModelChangedEvent() " + model.getId()); - } - - @Override - protected void handleVariableChangedEvent(Variable variable, int index, - ChangeType type) { - if (AlloppSpeciesNetworkModel.DBUGTUNE) - System.out.println("AlloppNetworkPriorModel.handleModelChangedEvent() " + variable.getId()); - } - - @Override - protected void storeState() { - // addVariable(rate), addVariable(popsf) deal with this - if (AlloppSpeciesNetworkModel.DBUGTUNE) - System.out.println("AlloppNetworkPriorModel.storeState()"); - - } - - @Override - protected void restoreState() { - // addVariable(rate), addVariable(popsf) deal with this - if (AlloppSpeciesNetworkModel.DBUGTUNE) - System.out.println("AlloppNetworkPriorModel.restoreState()"); - - } - - @Override - protected void acceptState() { - } - - public Type getUnits() { - return units; - } - - public void setUnits(Type units) { - // grjtodo-oneday allow units other than substitutions - - } - -} diff --git a/src/dr/evomodel/alloppnet/speciation/AlloppNode.java b/src/dr/evomodel/alloppnet/speciation/AlloppNode.java deleted file mode 100644 index 216604b44d..0000000000 --- a/src/dr/evomodel/alloppnet/speciation/AlloppNode.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * AlloppNode.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.alloppnet.speciation; - - - -import java.util.Stack; - -import dr.evolution.tree.SimpleNode; -import dr.evolution.util.Taxon; - -import jebl.util.FixedBitSet; - - -/** - * An AlloppNode is an interface implemented by DipHistNode in AlloppDiploidHistory, - * and MulLabNode in AlloppMulLabTree. - * The ABC AlloppNode.Abstract contains some common functionality. - * - * @author Graham Jones - * Date: 20/03/2012 - */ - - -public interface AlloppNode { - int nofChildren(); - AlloppNode getChild(int ch); - AlloppNode getAnc(); - Taxon getTaxon(); - double getHeight(); - FixedBitSet getUnion(); - - void setChild(int ch, AlloppNode newchild); - void setAnc(AlloppNode anc); - void setTaxon(String name); - void setHeight(double height); - void setUnion(FixedBitSet union); - void addChildren(AlloppNode c0, AlloppNode c1); - - String asText(int indentlen); - - void fillinUnionsInSubtree(int unionsize); - AlloppNode nodeOfUnionInSubtree(FixedBitSet x); - - - public abstract class Abstract implements AlloppNode { - - - public void fillinUnionsInSubtree(int unionsize) { - if (nofChildren() > 0) { - getChild(0).fillinUnionsInSubtree(unionsize); - getChild(1).fillinUnionsInSubtree(unionsize); - FixedBitSet union = new FixedBitSet(unionsize); - union.union(getChild(0).getUnion()); - union.union(getChild(1).getUnion()); - setUnion(union); - } - } - - - /* - * For constructor of AlloppDiploidHistory, AlloppMulLabTree. - * Searches subtree rooted at node for most tipward node - * whose union contains x. If x is known to be a union of one of the nodes, - * it finds that node, so acts as a map union -> node - */ - public AlloppNode nodeOfUnionInSubtree(FixedBitSet x) { - if (nofChildren() == 0) { - return this; - } - if (x.setInclusion(getChild(0).getUnion())) { - return getChild(0).nodeOfUnionInSubtree(x); - } else if (x.setInclusion(getChild(1).getUnion())) { - return getChild(1).nodeOfUnionInSubtree(x); - } else { - return this; - } - } - - public static String subtreeAsText(AlloppNode node, String s, Stack x, int depth, String b) { - Integer[] y = x.toArray(new Integer[x.size()]); - StringBuffer indent = new StringBuffer(); - for (int i = 0; i < depth; i++) { - indent.append(" "); - } - for (int i = 0; i < y.length; i++) { - indent.replace(2*y[i], 2*y[i]+1, "|"); - } - if (b.length() > 0) { - indent.replace(indent.length()-b.length(), indent.length(), b); - } - s += indent; - s += node.asText(indent.length()); - s += System.getProperty("line.separator"); - String subs = ""; - if (node.nofChildren() > 0) { - x.push(depth); - subs += subtreeAsText(node.getChild(0), "", x, depth+1, "-"); - x.pop(); - subs += subtreeAsText(node.getChild(1), "", x, depth+1, "`-"); - } - return s + subs; - } - - } - - -} diff --git a/src/dr/evomodel/alloppnet/speciation/AlloppNumHybsStatistic.java b/src/dr/evomodel/alloppnet/speciation/AlloppNumHybsStatistic.java deleted file mode 100644 index e26cb98949..0000000000 --- a/src/dr/evomodel/alloppnet/speciation/AlloppNumHybsStatistic.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * AlloppNumHybsStatistic.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.alloppnet.speciation; - -import dr.inference.model.Statistic; - - -/** - * @author Graham Jones - * Date: 08/10/12 - */ - -public class AlloppNumHybsStatistic extends Statistic.Abstract { - AlloppSpeciesNetworkModel aspnet; - - public AlloppNumHybsStatistic(AlloppSpeciesNetworkModel aspnet) { - super("NumHybs"); - this.aspnet = aspnet; - } - - - @Override - public int getDimension() { - return 1; - } - - @Override - public double getStatisticValue(int dim) { - return aspnet.getNumberOfTetraTrees(); - } -} diff --git a/src/dr/evomodel/alloppnet/speciation/AlloppSpeciesBindings.java b/src/dr/evomodel/alloppnet/speciation/AlloppSpeciesBindings.java deleted file mode 100644 index f8c2aaa53d..0000000000 --- a/src/dr/evomodel/alloppnet/speciation/AlloppSpeciesBindings.java +++ /dev/null @@ -1,1046 +0,0 @@ -/* - * AlloppSpeciesBindings.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.alloppnet.speciation; - - - - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Formatter; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Locale; -import java.util.Map; -import java.util.Set; -import java.util.Stack; - -import jebl.util.FixedBitSet; - -import dr.evolution.tree.NodeRef; -import dr.evolution.util.Taxon; -import dr.evomodel.tree.TreeModel; -import dr.evomodel.alloppnet.parsers.AlloppSpeciesBindingsParser; -import dr.inference.loggers.LogColumn; -import dr.inference.loggers.Loggable; -import dr.inference.model.AbstractModel; -import dr.inference.model.Model; -import dr.inference.model.ModelListener; -import dr.inference.model.Variable; -import dr.inference.model.Variable.ChangeType; -import dr.math.MathUtils; -import dr.evomodel.alloppnet.util.AlloppMisc; - -/** - * - * Knows how species (diploid and allopolyploid species) are made of individuals - * and individuals are made of taxa (=sequences). - * - * @author Graham Jones - * Date: 30/04/2011 - */ - - - -/* - * - * AlloppSpeciesBindings knows how species are made of individuals - * and how individuals are made of taxa (= diploid genomes within individuals). - * - * It also contains the list of gene trees - tree topologies and node - * times, plus popfactors. Given a AlloppSpeciesNetworkModel - * it can say if a gene tree is compatible. - * - * It is here that assignments of sequence copies within individuals - * get permuted. - * - * The class GeneUnionTree, defined here, is used during calculations. - * - * ****************************** - * - * geneTreeInfos. The array of gene trees. Each one has an array of - * sequence assignments. - * - * apspecies. List of species containing Individuals - * - * indivs. A 'flattened' array of all Individuals from all species - * - * taxa. A 'flattened' array of all Taxons from all Individuals - * - * taxon2index, apspecies2index: maps to indices - * - * spsq used to map (species index, sequence index) to a single index. - * - * Eg of two individuals from a diploid "a" and two individuals from a tetraploid "b" - * apspecies: a(01,02), b(03,04) - * indivs: 01_a(0), 02_a(0), 03_b(0,1), 04_b(0,1) - * taxa: 01_a0, 02_a0, 03_b0, 03_b1, 04_b0, 04_b1 - * - */ -public class AlloppSpeciesBindings extends AbstractModel implements Loggable { - - private final GeneTreeInfo[] geneTreeInfos; - - private final ApSpInfo[] apspecies; - private final Taxon[] taxa; - private final Map taxon2index = new HashMap(); - private final int spsq[][]; - private final int numberOfSpSeqs; - private final double initialmingenenodeheight; // for starting network - - - - /* ************ subclasses ********************/ - - /* class AlloppSpeciesBindings.Individual - * - * Individual is a list of Taxons. One for diploid individual, two for - * tetraploid, etc. - */ - public static class Individual extends Taxon { - final public String id; // individual ID, such as "02_Alpha" in AlloppSpeciesInfoParser XML example - public final Taxon[] taxa; - - public Individual(String id, Taxon[] taxa) { - super(id); - this.id = id; - this.taxa = taxa; - } - } - - - private class SpeciesIndivPair { - public int spIndex; - public int ivIndex; - - public SpeciesIndivPair(int spIndex, int ivIndex) { - this.spIndex = spIndex; - this.ivIndex = ivIndex; - } - } - - - /* class AlloppSpeciesBindings.ApSpInfo - * - * Information on one allopolyploid species - * - * name is species name, such as "Alpha" in AlloppSpeciesInfoParser XML example - * - * ploidylevel; 2 means diploid, 4 means allotetraploid, etc - * - * individuals[] - */ - public static class ApSpInfo extends Taxon { - - final public String name; - final public int ploidylevel; // 2 means diploid, 4 means allotetraploid, etc - final Individual[] individuals; - - public ApSpInfo(String name, int ploidylevel, Individual[] individuals) { - super(name); - this.name = name; - this.individuals = individuals; - this.ploidylevel = ploidylevel; - - // check - if (individuals != null) { - int ntaxaperindiv = ploidylevel / 2; - for (int ii = 0; ii < individuals.length; ++ii) { - assert(individuals[ii].taxa.length == ntaxaperindiv); - // may want to allow 3 as well as 2 for tetraploid for organelle DNA - } - } - } - - - public Taxon taxonFromIndSeq(int i, int sq) { - return individuals[i].taxa[sq]; - } - } - - - /* class AlloppSpeciesBindings.GeneTreeInfo - * - * Adapted from SpeciesBindings - * - * tree is the gene tree - * - * seqassigns[] is species index and sequence index. The latter - * is what MCMC acts on when permute sequence assignments - * - * lineagesCount[] is count for each species, and applies to one or - * more tips in MulLabTree. I assume this is the same for all genes - * though the info is stored per gene tree - * - * popFactor (normal diploid=2, X chromosome=1.5, chloroplast=.5, etc) - * - * I don't like the CoalInfo method of determining compatibility. - * Instead I copy the gene tree topology and heights into a new - * tree with unions in nodes. Maybe I'll find out why JH used CoalInfos... - */ - private class GeneTreeInfo { - private final TreeModel tree; - private SequenceAssignment seqassigns[]; - private SequenceAssignment oldseqassigns[]; - private final int[] lineagesCount; - private final double popFactor; // grjtodo-oneday will mul pops by this, eg for chloroplast data. - - - /* class GeneTreeInfo.SequenceAssignments - * - * spIndex is an index for an allopolyploid species. For example, it identifies - * a bit in a FixedBitSet (union) in a MulLabTree - * - * seqIndex identifies a sequence copy for this gene and for each individual. - * seqIndex is 0 or 1 for tetraploids and it is these that get flipped to change - * assignments of sequence copies to legs in AlloppSpeciesNetworkModel (or - * equivalently to tips in a MulLabTree). - * - * 2011-06-23 spIndex is the same for all gene trees. Maybe - * allow non-rectangular data later. - */ - private class SequenceAssignment { - public int spIndex; - public int seqIndex; - - public SequenceAssignment(int spIndex, int seqIndex) { - this.spIndex = spIndex; - this.seqIndex = seqIndex; - } - - public String toString() { - String s = "" + seqIndex; - return s; - } - } - - - - - /* class GeneTreeInfo.GeneUnionNode - * - * Node for GeneTreeInfo.GeneUnionTree. - */ - private class GeneUnionNode { - private GeneUnionNode child[]; - private double height; - private FixedBitSet union; - private String name; // for debugging - - // Constructor makes a half-formed tip node. Tips need unions - // and internal nodes need all fields filling in. - public GeneUnionNode() { - child = new GeneUnionNode[0]; - height = 0.0; - union = new FixedBitSet(numberOfSpSeqs()); - name = ""; - } - - - - public String asText(int indentlen) { - StringBuilder s = new StringBuilder(); - Formatter formatter = new Formatter(s, Locale.US); - if (child.length == 0) { - formatter.format("%s ", name); - } else { - formatter.format("%s ", "+"); - } - while (s.length() < 30-indentlen) { - formatter.format("%s", " "); - } - formatter.format("%s ", AlloppMisc.nonnegIn8Chars(height)); - formatter.format("%20s ", AlloppMisc.FixedBitSetasText(union)); - - return s.toString(); - } - - } - - /* class GeneTreeInfo.GeneUnionTree - * - * Copy of gene tree topology and heights with unions, - * implemented as an array of GeneUnionNodes. This is - * used during calculations fitsInNetwork(), treeLogLikelihood() - * for one gene tree at a time, then discarded. - */ - private class GeneUnionTree { - private GeneUnionNode[] nodes; - private int nextn; - - - public GeneUnionTree() { - nodes = new GeneUnionNode[tree.getNodeCount()]; - for (int i = 0; i < nodes.length; i++) { - nodes[i] = new GeneUnionNode(); - } - genetree2geneuniontree(tree.getRoot()); - } - - - public GeneUnionNode getRoot() { - return nodes[nodes.length-1]; - } - - - - private boolean subtreeFitsInNetwork(GeneUnionNode node, - final AlloppSpeciesNetworkModel asnm) { - for (int i = 0; i < node.child.length; i++) { - if (!subtreeFitsInNetwork(node.child[i], asnm)) { - return false; - } - } - return asnm.coalescenceIsCompatible(node.height, node.union); - } - - - private void subtreeRecordCoalescences(GeneUnionNode node, - final AlloppSpeciesNetworkModel asnm) { - for (int i = 0; i < node.child.length; i++) { - subtreeRecordCoalescences(node.child[i], asnm); - } - if (node.child.length > 0) { - asnm.recordCoalescence(node.height, node.union); - } - } - - - /* - * Recursively copies the topology from subtree rooted at node into - * GeneUnionTree implemented as array nodes[]. - * Fills in union fields. - * - */ - private void genetree2geneuniontree(NodeRef gnode) { - if (tree.isExternal(gnode)) { - nodes[nextn].child = new GeneUnionNode[0]; - int ti = taxon2index.get(tree.getNodeTaxon(gnode)); - int spseq = spsq[seqassigns[ti].spIndex][seqassigns[ti].seqIndex]; - nodes[nextn].union.set(spseq); - nodes[nextn].name = tree.getNodeTaxon(gnode).getId(); - } else { - genetree2geneuniontree(tree.getChild(gnode,0)); - int c0 = nextn - 1; - genetree2geneuniontree(tree.getChild(gnode,1)); - int c1 = nextn - 1; - nodes[nextn].child = new GeneUnionNode[2]; - nodes[nextn].child[0] = nodes[c0]; - nodes[nextn].child[1] = nodes[c1]; - nodes[nextn].union.union(nodes[c0].union); - nodes[nextn].union.union(nodes[c1].union); - } - nodes[nextn].height = tree.getNodeHeight(gnode); - nextn++; - } - - - - - - public String asText() { - String s = ""; - Stack x = new Stack(); - return subtreeAsText(getRoot(), s, x, 0, ""); - } - - - private String subtreeAsText(GeneUnionNode node, String s, Stack x, int depth, String b) { - Integer[] y = x.toArray(new Integer[x.size()]); - StringBuffer indent = new StringBuffer(); - for (int i = 0; i < depth; i++) { - indent.append(" "); - } - for (int i = 0; i < y.length; i++) { - indent.replace(2*y[i], 2*y[i]+1, "|"); - } - if (b.length() > 0) { - indent.replace(indent.length()-b.length(), indent.length(), b); - } - s += indent; - s += node.asText(indent.length()); - s += System.getProperty("line.separator"); - String subs = ""; - if (node.child.length > 0) { - x.push(depth); - subs += subtreeAsText(node.child[0], "", x, depth+1, "-"); - x.pop(); - subs += subtreeAsText(node.child[1], "", x, depth+1, "`-"); - } - return s + subs; - } - - } // end GeneTreeInfo.GeneUnionTree - - - /* - * GeneTreeInfo constructor - * - * JH's SpeciesBindings code has test - * if (tree.getTaxonIndex(t) >= 0) { add taxon to count } - * - * I am not clear about what happens if some gene trees don't have all taxa. - * I insist all gene trees have all taxa, and use missing data - * grjtodo-oneday make more efficient - */ - GeneTreeInfo(TreeModel tree, double popFactor, boolean permuteSequenceAssignments) { - this.tree = tree; - this.popFactor = popFactor; - seqassigns = new SequenceAssignment[taxa.length]; - oldseqassigns = new SequenceAssignment[taxa.length]; - - // This uses taxa list for *all* gene trees, not this gene tree. - for (int s = 0; s < apspecies.length; s++) { - for (int i = 0; i < apspecies[s].individuals.length; i++) { - int nseqs = apspecies[s].individuals[i].taxa.length; - int asgns[] = new int [nseqs]; - for (int x = 0; x < nseqs; x++) { - asgns[x] = x; - } - if (permuteSequenceAssignments) { MathUtils.permute(asgns); } - for (int x = 0; x < nseqs; x++) { - int t = taxon2index.get(apspecies[s].individuals[i].taxa[x]); - seqassigns[t] = new SequenceAssignment(s, asgns[x]); - oldseqassigns[t] = new SequenceAssignment(s, asgns[x]); - } - } - } - - lineagesCount = new int[apspecies.length]; - Arrays.fill(lineagesCount, 0); - - for (int nl = 0; nl < lineagesCount.length; ++nl) { - for (Individual indiv : apspecies[nl].individuals) { - boolean got = false; - for (Taxon t : indiv.taxa) { - if (tree.getTaxonIndex(t) >= 0) { - got = true; - } - } - for (Taxon t : indiv.taxa) { - assert (tree.getTaxonIndex(t) >= 0) == got; - } - assert got; - if (got) { - ++lineagesCount[nl]; - } - } - } - } - - - public String seqassignsAsText() { - String s = "Sequence assignments" + System.getProperty("line.separator"); - for (int tx = 0; tx < seqassigns.length; tx++) { - s += taxa[tx]; - s += ":"; - s += seqassigns[tx].seqIndex; - if (tx+1 < seqassigns.length && seqassigns[tx].spIndex != seqassigns[tx+1].spIndex) { - s += System.getProperty("line.separator"); - } else { - s += " "; - } - } - return s; - } - - - - public String genetreeAsText() { - GeneUnionTree gutree = new GeneUnionTree(); - return gutree.asText(); - } - - - public boolean fitsInNetwork(final AlloppSpeciesNetworkModel asnm) { - GeneUnionTree gutree = new GeneUnionTree(); - boolean fits = gutree.subtreeFitsInNetwork(gutree.getRoot(), asnm); - if (AlloppSpeciesNetworkModel.DBUGTUNE) { - if (!fits) { - System.err.println("INCOMPATIBLE"); - System.err.println(seqassignsAsText()); - System.err.println(gutree.asText()); - System.err.println(asnm.mullabTreeAsText()); - } - } - return fits; - } - - - // returns log(P(g_i|S)) = probability that gene tree fits into species network - public double treeLogLikelihood(final AlloppSpeciesNetworkModel asnm) { - GeneUnionTree gutree = new GeneUnionTree(); - asnm.clearCoalescences(); - gutree.subtreeRecordCoalescences(gutree.getRoot(), asnm); - asnm.sortCoalescences(); - asnm.recordLineageCounts(); - double llhood = asnm.geneTreeInNetworkLogLikelihood(); - if (AlloppSpeciesNetworkModel.DBUGTUNE) { - System.err.println("COMPATIBLE: log-likelihood = " + llhood); - System.err.println(seqassignsAsText()); - System.err.println(gutree.asText()); - System.err.println(asnm.mullabTreeAsText()); - } - return llhood; - } - - - public void storeSequenceAssignments() { - for (int i = 0; i < seqassigns.length; i++) { - oldseqassigns[i].seqIndex = seqassigns[i].seqIndex; - } - } - - public void restoreSequenceAssignments() { - for (int i = 0; i < seqassigns.length; i++) { - seqassigns[i].seqIndex = oldseqassigns[i].seqIndex; - } - } - - - - - public double spseqUpperBound(FixedBitSet spsq0, FixedBitSet spsq1) { - GeneUnionTree gutree = new GeneUnionTree(); - return subtreeSpseqUpperBound(gutree.getRoot(), spsq0, spsq1, Double.MAX_VALUE); - } - - - - public void permuteOneSpeciesOneIndiv() { - int sp = MathUtils.nextInt(apspecies.length); - int iv = MathUtils.nextInt(apspecies[sp].individuals.length); - flipOneAssignment(sp, iv); - } - - - /* grjtodo-oneday - * This is a bit odd. It collects individuals as (sp, iv) indices - * that `belong' to a node in the sense that any taxon (sequence) - * of an individual belongs to the clade of the node. - * I've used a set but not made SpeciesIndivPair's comparable - * so that if both sequences of an individual occurs in clade it appears - * twice. Then flipOneAssignment() flips everything so that those - * occurring twice get flipped twice and so not changed. - * - * Result is that individuals with one but not two sequences in - * the clade of the node get flipped. Sometimes all individuals - * are flipped, sometimes none, sometimes just one, the last is the - * same as permuteOneSpeciesOneIndiv(). - * - * 2011-07-29 it appears to work OK on minimal testing and I - * don't have a good idea for a more rational or efficient version. - * - */ - public void permuteSetOfIndivs() { - int num = tree.getInternalNodeCount(); - int i = MathUtils.nextInt(num); - NodeRef node = tree.getInternalNode(i); - Set spivs = new HashSet(); - collectIndivsOfNode(node, spivs); - for (SpeciesIndivPair spiv : spivs) { - flipOneAssignment(spiv.spIndex, spiv.ivIndex); - } - } - - - - - public SequenceAssignment getSeqassigns(int tx) { - return seqassigns[tx]; - } - - - // called when a gene tree has changed, which affects likelihood. - // 2011-08-12 I am not using dirty flags (yet). I return - // false from getLikelihoodKnown() in AlloppMSCoalescent - // and that seems to be sufficient. - public void wasChanged() { - } - - - - - - - private void collectIndivsOfNode(NodeRef node, Set spivs) { - if (tree.isExternal(node)) { - SpeciesIndivPair x = apspeciesId2speciesindiv(tree.getNodeTaxon(node).getId()); - spivs.add(x); - } else { - collectIndivsOfNode(tree.getChild(node, 0), spivs); - collectIndivsOfNode(tree.getChild(node, 1), spivs); - } - } - - - - - - // start at root of gutree and recurse. - // A node which has one child which contains some of species spp0 - // and where the other contains some of species spp1, imposes a limit - // on how early a speciation can occur. - private double subtreeSpseqUpperBound(GeneUnionNode node, - FixedBitSet spsq0, FixedBitSet spsq1, double bound) { - if (node.child.length == 0) { - return bound; - } - for (GeneUnionNode ch : node.child) { - bound = Math.min(bound, subtreeSpseqUpperBound(ch, spsq0, spsq1, bound)); - } - FixedBitSet genespp0 = node.child[0].union; - int int00 = genespp0.intersectCardinality(spsq0); - int int01 = genespp0.intersectCardinality(spsq1); - FixedBitSet genespp1 = node.child[1].union; - int int10 = genespp1.intersectCardinality(spsq0); - int int11 = genespp1.intersectCardinality(spsq1); - if ((int00 > 0 && int11 > 0) || (int10 > 0 && int01 > 0)) { - bound = Math.min(bound, node.height); - } - return bound; - } - - - - private void flipOneAssignment(int sp, int iv) { - // grjtodo-tetraonly - int tx; - if (apspecies[sp].individuals[iv].taxa.length == 2) { - tx = taxon2index.get(apspecies[sp].individuals[iv].taxa[0]); - seqassigns[tx].seqIndex = 1 - seqassigns[tx].seqIndex; - tx = taxon2index.get(apspecies[sp].individuals[iv].taxa[1]); - seqassigns[tx].seqIndex = 1 - seqassigns[tx].seqIndex; - } - } - - - - private void flipAssignmentsForSpecies(int sp) { - for (int iv = 0; iv < apspecies[sp].individuals.length; iv++) { - flipOneAssignment(sp, iv); - } - } - - - - } - // end of GeneTreeInfo - - - - - /* ******************** Constructor *****************************/ - - /* - * The standard constructor calls this with permuteSequenceAssignments==true. - * permuteSequenceAssignments==false is for testing. - */ - public AlloppSpeciesBindings(ApSpInfo[] apspecies, TreeModel[] geneTrees, - double minheight, double[] popFactors, boolean permuteSequenceAssignments) { - super(AlloppSpeciesBindingsParser.ALLOPPSPECIES); - - this.apspecies = apspecies; - initialmingenenodeheight = minheight; - // make the flattened arrays - int n = 0; - for (int s = 0; s < apspecies.length; s++) { - n += apspecies[s].individuals.length; - } - Individual [] indivs = new Individual[n]; - n = 0; - for (int s = 0; s < apspecies.length; s++) { - for (int i = 0; i < apspecies[s].individuals.length; i++, n++) { - indivs[n] = apspecies[s].individuals[i]; - } - } - int t = 0; - for (int i = 0; i < indivs.length; i++) { - t += indivs[i].taxa.length; - } - taxa = new Taxon[t]; - t = 0; - for (int i = 0; i < indivs.length; i++) { - for (int j = 0; j < indivs[i].taxa.length; j++, t++) { - taxa[t] = indivs[i].taxa[j]; - } - } - // set up maps to indices - for (int i = 0; i < taxa.length; i++) { - taxon2index.put(taxa[i], i); - } - spsq = new int[apspecies.length][]; - int spsqindex = 0; - for (int sp = 0; sp < apspecies.length; sp++) { - spsq[sp] = new int[apspecies[sp].ploidylevel/2]; - for (int seq = 0; seq < spsq[sp].length; seq++, spsqindex++) { - spsq[sp][seq] = spsqindex; - } - } - numberOfSpSeqs = spsqindex; - - geneTreeInfos = new GeneTreeInfo[geneTrees.length]; - for (int i = 0; i < geneTrees.length; i++) { - geneTreeInfos[i] = new GeneTreeInfo(geneTrees[i], popFactors[i], permuteSequenceAssignments); - } - - for (GeneTreeInfo gti : geneTreeInfos) { - NodeRef[] nodes = gti.tree.getNodes(); - for (NodeRef node : nodes) { - if (!gti.tree.isExternal(node)) { - double height = gti.tree.getNodeHeight(node); - gti.tree.setNodeHeight(node, minheight+height); - } - } - } - } - - - /* - * The normal constructor - */ - public AlloppSpeciesBindings(ApSpInfo[] apspecies, TreeModel[] geneTrees, - double minheight, double[] popFactors) { - this(apspecies, geneTrees, minheight, popFactors, true); - } - - /* - * Minimal constructor for testing conversions network -> multree, diphist - * and for testing likelihood in MUL tree. - */ - public AlloppSpeciesBindings(ApSpInfo[] apspecies) { - this(apspecies, new TreeModel[0], 0.0, new double[0]); - } - - - public double initialMinGeneNodeHeight() { - return initialmingenenodeheight; - } - - - - public FixedBitSet speciesseqEmptyUnion() { - FixedBitSet union = new FixedBitSet(numberOfSpSeqs()); - return union; - } - - - // Taxons vs species. - // Taxons may have a final "0", "1",... to distinguish sequences, while - // species do not. AlloppLeggedTree uses a SimpleTree, which only has - // Taxons, so same thing there. Multree needs distinguishable Taxons - // so has suffices. - public FixedBitSet taxonseqToTipUnion(Taxon tx, int seq) { - FixedBitSet union = speciesseqEmptyUnion(); - int sp = apspeciesId2index(tx.getId()); - int spseq = spandseq2spseqindex(sp, seq); - union.set(spseq); - return union; - } - - - public FixedBitSet spsqunion2spunion(FixedBitSet spsqunion) { - FixedBitSet spunion = new FixedBitSet(apspecies.length); - for (int sp = 0; sp < apspecies.length; sp++) { - boolean got = false; - for (int seq = 0; seq < spsq[sp].length; seq++) { - if (spsqunion.contains(spsq[sp][seq])) { - got = true; - } - } - if (got) { - spunion.set(sp); - } - } - return spunion; - } - - - public int numberOfGeneTrees() { - return geneTreeInfos.length; - } - - - public double maxGeneTreeHeight() { - if (geneTreeInfos.length == 0) { - return 999; // for test code only - } - double maxheight = 0.0; - for (GeneTreeInfo gti : geneTreeInfos) { - double height = gti.tree.getNodeHeight(gti.tree.getRoot()); - if (height > maxheight) { - maxheight = height; - } - } - return maxheight; - } - - - - - public boolean geneTreeFitsInNetwork(int i, final AlloppSpeciesNetworkModel asnm) { - return geneTreeInfos[i].fitsInNetwork(asnm); - } - - public double geneTreeLogLikelihood(int i, final AlloppSpeciesNetworkModel asnm) { - return geneTreeInfos[i].treeLogLikelihood(asnm); - } - - - public int numberOfSpecies() { - return apspecies.length; - } - - - - public String apspeciesName(int i) { - return apspecies[i].name; - } - - - - public Taxon[] SpeciesWithinPloidyLevel(int pl) { - ArrayList names = new ArrayList(); - for (int i = 0; i < apspecies.length; i++) { - if (apspecies[i].ploidylevel == pl) { - names.add(new Taxon(apspecies[i].name)); - } - } - Taxon[] spp = new Taxon[names.size()]; - names.toArray(spp); - return spp; - } - - - public int spandseq2spseqindex(int sp, int seq) { - return spsq[sp][seq]; - } - - - - public int spseqindex2sp(int spsqindex) { - return spseqindex2spandseq(spsqindex)[0]; - } - - public int spseqindex2seq(int spsqindex) { - return spseqindex2spandseq(spsqindex)[1]; - } - - - - public int apspeciesId2index(String apspId) { - int index = -1; - for (int i = 0; i < apspecies.length; i++) { - if (apspecies[i].name.compareTo(apspId) == 0) { - assert index == -1; - index = i; - } - } - if (index == -1) { - System.out.println("BUG in apspeciesId2index"); - } - assert index != -1; - return index; - } - - - public SpeciesIndivPair apspeciesId2speciesindiv(String apspId) { - int sp = -1; - int iv = -1; - for (int s = 0; s < apspecies.length; s++) { - for (int i = 0; i < apspecies[s].individuals.length; i++) { - for (int t = 0; t < apspecies[s].individuals[i].taxa.length; t++) { - Taxon taxon = apspecies[s].individuals[i].taxa[t]; - if (taxon.getId().compareTo(apspId) == 0) { - sp = s; - iv = i; - } - } - } - } - assert sp != -1; - SpeciesIndivPair x = new SpeciesIndivPair(sp, iv); - - return x; - } - - - public int numberOfSpSeqs() { - return numberOfSpSeqs; - } - - - int nLineages(int speciesIndex) { - int n = geneTreeInfos[0].lineagesCount[speciesIndex]; - for (GeneTreeInfo gti : geneTreeInfos) { - assert gti.lineagesCount[speciesIndex] == n; - } - return n; - } - - - - public double spseqUpperBound(FixedBitSet left, FixedBitSet right) { - double bound = Double.MAX_VALUE; - for (GeneTreeInfo gti : geneTreeInfos) { - bound = Math.min(bound, gti.spseqUpperBound(left, right)); - } - return bound; - } - - - - public void permuteOneSpeciesOneIndivForOneGene() { - int i = MathUtils.nextInt(geneTreeInfos.length); - geneTreeInfos[i].permuteOneSpeciesOneIndiv(); - } - - - public void permuteSetOfIndivsForOneGene() { - int i = MathUtils.nextInt(geneTreeInfos.length); - geneTreeInfos[i].permuteSetOfIndivs(); - } - - - public void flipAssignmentsForAllGenesOneSpecies(int sp) { - for (GeneTreeInfo gti : geneTreeInfos) { - gti.flipAssignmentsForSpecies(sp); - } - - } - - - - public String seqassignsAsText(int g) { - return geneTreeInfos[g].seqassignsAsText(); - } - - - public String genetreeAsText(int g) { - String s = "Gene tree " + g + " height union" + System.getProperty("line.separator"); - s += geneTreeInfos[g].genetreeAsText(); - return s; - } - - - @Override - protected void handleModelChangedEvent(Model model, Object object, int index) { - for (GeneTreeInfo g : geneTreeInfos) { - if (g.tree == model) { - g.wasChanged(); - break; - } - } - fireModelChanged(object, index); - if (AlloppSpeciesNetworkModel.DBUGTUNE) - System.err.println("AlloppSpeciesBindings.handleModelChangedEvent() " + model.getId()); - } - - @Override - protected void handleVariableChangedEvent(Variable variable, int index, - ChangeType type) { - assert false; // copies SpeciesBindings; not understood - if (AlloppSpeciesNetworkModel.DBUGTUNE) - System.err.println("AlloppSpeciesBindings.handleVariableChangedEvent() " + variable.getId()); - } - - @Override - protected void storeState() { - for (GeneTreeInfo gti : geneTreeInfos) { - gti.storeSequenceAssignments(); - } - if (AlloppSpeciesNetworkModel.DBUGTUNE) - System.err.println("AlloppSpeciesBindings.storeState()"); - } - - @Override - protected void restoreState() { - for (GeneTreeInfo gti : geneTreeInfos) { - gti.restoreSequenceAssignments(); - if (AlloppSpeciesNetworkModel.DBUGTUNE) - System.err.println("AlloppSpeciesBindings.restoreState()"); - } - - } - - @Override - protected void acceptState() { - } - - - public void addModelListeners(ModelListener listener) { - for (GeneTreeInfo gti : geneTreeInfos) { - gti.tree.addModelListener(listener); - } - addModelListener(listener); // for sequence assignments - } - - - - public LogColumn[] getColumns() { - int ncols = geneTreeInfos.length * taxa.length; - LogColumn[] columns = new LogColumn[ncols]; - for (int g = 0, i = 0; g < geneTreeInfos.length; g++) { - for (int tx = 0; tx < taxa.length; tx++, i++) { - GeneTreeInfo.SequenceAssignment sqa = geneTreeInfos[g].getSeqassigns(tx); - String header = "Gene" + g + "taxon" + tx; - columns[i] = new LogColumn.Default(header, sqa); - } - - } - - return columns; - } - - - - private int[] spseqindex2spandseq(int spsqindex) { - int indexp = -1; - int indexq = -1; - for (int p = 0; p < spsq.length; p++) { - for (int q = 0; q < spsq[p].length; q++) { - if (spsq[p][q] == spsqindex) { - assert indexp == -1; - assert indexq == -1; - indexp = p; - indexq = q; - } - } - } - assert indexp != -1; - assert indexq != -1; - int[] pq = new int[2]; - pq[0] = indexp; - pq[1] = indexq; - return pq; - } - -} - - - diff --git a/src/dr/evomodel/alloppnet/speciation/AlloppSpeciesNetworkModel.java b/src/dr/evomodel/alloppnet/speciation/AlloppSpeciesNetworkModel.java deleted file mode 100644 index fae80d0f4b..0000000000 --- a/src/dr/evomodel/alloppnet/speciation/AlloppSpeciesNetworkModel.java +++ /dev/null @@ -1,1245 +0,0 @@ -/* - * AlloppSpeciesNetworkModel.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.alloppnet.speciation; - - - -import dr.evolution.tree.*; -import dr.evolution.util.Taxon; -import dr.evolution.util.Units; -import dr.evomodel.tree.TreeLogger; -import dr.evomodel.alloppnet.parsers.AlloppSpeciesNetworkModelParser; -import dr.inference.distribution.ParametricDistributionModel; -import dr.inference.loggers.LogColumn; -import dr.inference.model.AbstractModel; -import dr.inference.model.Model; -import dr.inference.model.Parameter; -import dr.inference.model.Variable; -import dr.inference.operators.Scalable; -import dr.math.MathUtils; -import dr.util.Author; -import dr.util.Citable; -import dr.util.Citation; -import jebl.util.FixedBitSet; -import java.util.*; -import java.util.logging.Logger; - - -/** - * - * Implements an allopolyploid species network as a collection of `trees with legs'. - * - * @author Graham Jones - * Date: 19/04/2011 - */ - - -/* - * class AlloppSpeciesNetworkModel - * - * Implements the species network as a collection of `trees with legs'. - * and converts this representation into a multiply labelled - * binary tree. - * - * General idea is that the network is easiest to change (eg detach - * and re-attach tetraploid subtrees) while likelihood calculations - * are easiest to do in the multiply labelled tree. - * - * The individual `trees with legs' are implemented by AlloppLeggedTree's. - * The multiply labelled binary tree is implemented by AlloppMulLabTree. - * - * ********************* - * - * apsp is a reference to the AlloppSpeciesBindings which knows how - * species are made of individuals and individuals are made of taxa, - * and which contains the list of gene trees. - * - * trees[][] represents the network as a set of homoploid trees - * - * mullabtree represents the network as single tree with tips that - * can be multiply labelled with species. - * - */ -// grjtodo-oneday JH's SpeciesTreeModel implements -// MutableTree, TreeTraitProvider, TreeLogger.LogUpon, Scalable -// not clear how much of those sensible here. -// AlloppLeggedTree implements MutableTree, TreeLogger.LogUpon. -// Nothing so far does TreeTraitProvider. -public class AlloppSpeciesNetworkModel extends AbstractModel implements - Scalable, Units, Citable, Tree, TreeTraitProvider, TreeLogger.LogUpon { - - private final AlloppSpeciesBindings apsp; - private AlloppDiploidHistory adhist; - private AlloppDiploidHistory oldadhist; - private ArrayList tettrees; - private ArrayList oldtettrees; - private int nofdiploids; - private int noftetraploids; - private boolean onehybridization; - private boolean diploidrootisroot; - private TreeTrait tti; - private TreeTrait hh; - - private AlloppMulLabTree mullabtree; - - private ParametricDistributionModel hybridPopModel; - - // The Parameters are public, copying JH - is that necessary? TreeNodeSlide accesses it. - // 2011-06-30 parser accesses it too. - // Parameter or Parameter.Default ?? (a Java thing I don't get) - public final Parameter tippopvalues; - public final Parameter rootpopvalues; - - public final Parameter logginghybpopvalues; - private double [] hybpopvalues; - private double [] oldhybpopvalues; - - - public final static boolean DBUGTUNE = false; - - - - - private class TetTreeIndexTrait implements TreeTrait { - TetTreeIndexTrait() {} - - public String getTraitName() { - return "tti"; - } - - public TreeTrait.Intent getIntent() { - return Intent.BRANCH; - } - - @Override - public Class getTraitClass() { - return String.class; - } - - public String getTrait(Tree tree, NodeRef node) { - assert tree == mullabtree; - return (String)getNodeAttribute(node, "tti"); - } - - @Override - public String getTraitString(Tree tree, NodeRef node) { - return "" + getNodeAttribute(node, "tti"); - } - - @Override - public boolean getLoggable() { - return true; - } - } - - - - // grjtodo-soon hybheights in TreeAnnotator is not working as hoped. - // Nodes may or may not - // have hybheights, so means, medians, etc, combine -1 with valid values - // Omitting attributes from nodes results in some `null's in the tree log file - // which makes TreeAnnotator treat all values as discrete (as a set). - // For now, just don't add hh to list in getTreeTraits() - private class HybHeightTrait implements TreeTrait { - HybHeightTrait() {} - - public String getTraitName() { - return "hybhgt"; - } - - public TreeTrait.Intent getIntent() { - return TreeTrait.Intent.NODE; - } - - @Override - public Class getTraitClass() { - return Double.class; - } - - public Double getTrait(Tree tree, NodeRef node) { - assert tree == mullabtree; - return (Double)getNodeAttribute(node, "hybhgt"); - } - - @Override - public String getTraitString(Tree tree, NodeRef node) { - return "" + getNodeAttribute(node, "hybhgt"); - } - - @Override - public boolean getLoggable() { - return true; - } - } - - - - - /* - * Constructors. - * - */ - public AlloppSpeciesNetworkModel(AlloppSpeciesBindings apspecies, - double tippopvalue, double rootpopvalue, double hybpopvalue, - boolean onehyb, boolean diprootisroot) { - super(AlloppSpeciesNetworkModelParser.ALLOPPSPECIESNETWORK); - apsp = apspecies; - addModel(apsp); - tettrees = new ArrayList(); - Taxon[] dipspp = apsp.SpeciesWithinPloidyLevel(2); - nofdiploids = dipspp.length; - Taxon[] tetspp = apsp.SpeciesWithinPloidyLevel(4); - noftetraploids = tetspp.length; - onehybridization = onehyb; - diploidrootisroot = diprootisroot; - makeInitialNDipsNTetsNetwork(dipspp, tetspp); - - double maxrootheight = adhist.getRootHeight(); - for (int i = 0; i < tettrees.size(); i++) { - double height = tettrees.get(i).getRootHeight(); - if (height > maxrootheight) { maxrootheight = height; } - } - double scale = 0.99 * apsp.initialMinGeneNodeHeight() / maxrootheight; - scaleAllHeights(scale); - - int ntippopparams = numberOfTipPopParameters(); - int nrootpopparams = numberOfRootPopParameters(); - int maxnhybpopparams = maxNumberOfHybPopParameters(); - tippopvalues = new Parameter.Default(ntippopparams, tippopvalue); - rootpopvalues = new Parameter.Default(nrootpopparams, rootpopvalue); - addVariable(tippopvalues); - addVariable(rootpopvalues); - // hybridization pop sizes have to be done differently because they change in number. - hybpopvalues = new double[maxnhybpopparams]; - for (int hp = 0; hp < hybpopvalues.length; hp++) { - hybpopvalues[hp] = hybpopvalue; - } - - logginghybpopvalues = new Parameter.Default(hybpopvalues); - makeLoggingHybPopParam(); - - mullabtree = new AlloppMulLabTree(adhist, tettrees, apsp, tippopvalues, rootpopvalues, hybpopvalues); - - tti = new TetTreeIndexTrait(); - hh = new HybHeightTrait(); - - Logger.getLogger("dr.evomodel.speciation.allopolyploid").info("\tConstructing an allopolyploid network, please cite:\n" - + Citable.Utils.getCitationString(this)); - } - - - - /* - * This (partial) constructor is for testing conversion network to multree. - * Real work done by testExampleNetworkToMulLabTree() - */ - public AlloppSpeciesNetworkModel(AlloppSpeciesBindings apsp) { - super(AlloppSpeciesNetworkModelParser.ALLOPPSPECIESNETWORK); - this.apsp = apsp; - tippopvalues = null; - rootpopvalues = null; - hybpopvalues = null; - logginghybpopvalues = null; - } - - // This is called from AlloppNetworkPrior (which is created after network) - // to supply a ParametricDistributionModel for the prior on the - // hybrid population values. It completes the construction of the network. - public void setHybPopModel(ParametricDistributionModel pdm) { - hybridPopModel = pdm; - } - - - /***********************************************************************************/ - - - @Override - public Citation.Category getCategory() { - return Citation.Category.SPECIES_MODELS; - } - - @Override - public String getDescription() { - return "Allopolyploid Species Networks"; - } - - @Override - public List getCitations() { - return Collections.singletonList( - new Citation( - new Author[]{ - new Author("Graham", "Jones"), - new Author("Serik", "Sagitov"), - new Author("Bengt", "Oxelman") - }, - "Statistical Inference of Allopolyploid Species Networks in the Presence of Incomplete Lineage Sorting", - 2013, - "Systematic Biology", - 62, - 467, - 478, - Citation.Status.PUBLISHED - )); - } - - - public boolean alloppspeciesnetworkOK() { - for (AlloppLeggedTree tettree : tettrees) { - if (!tettree.leggedtreeOK()) { - return false; - } - } - for (int tt = 0; tt (); - for (int j=0; j(); - for (int j=0; j 0; - assert nDims <= 0; - if (nDims <= 0) { - beginNetworkEdit(); - int count = 0; - count += scaleAllHeights(scaleFactor); - count += scaleAllPopValues(scaleFactor); - endNetworkEdit(); - fireModelChanged(this, 1); - return count; - } else { - // grjtodo-oneday JH also has a internalTreeOP for nDims==1 case - if (nDims != 1) { - throw new UnsupportedOperationException("not implemented for count != 1"); - } - fireModelChanged(this, 1); - return nDims; - } - } - - @Override - public boolean testBounds() { - return true; - } - - // finds the union of a tip (diploid or hyb-tip) in the diploid history. - // Used by move that slides node in diploid history to check gene-tree compatibility. - public FixedBitSet calculateDipHistTipUnion(NodeRef node) { - if (node == null) { - System.out.println("BUG in calculateDipHistTipUnion()"); - } - assert node != null; - int tt = adhist.getNodeTettree(node.getNumber()); - AlloppDiploidHistory.LegLorR leg = adhist.getNodeLeg(node.getNumber()); - int seq = (leg == AlloppDiploidHistory.LegLorR.left) ? 0 : 1; - FixedBitSet union; - if (tt < 0) { // ordinary tip - union = apsp.taxonseqToTipUnion(adhist.getSlidableNodeTaxon(node), 0); - } else { - union = unionOfWholeTetTree(tt, seq); - } - return union; - } - - - - public FixedBitSet unionOfWholeTetTree(int tt, int leg) { - // fill in tips - tettrees.get(tt).fillinTipUnions(apsp, leg); - // fill in rest. could just take union of all, but have this function ready - AlloppNode tetroot = (AlloppNode)tettrees.get(tt).getSlidableRoot(); - tetroot.fillinUnionsInSubtree(apsp.numberOfSpSeqs()); - return tetroot.getUnion(); - } - - - public double addHybPopParam() { - assert tettrees.size() <= hybpopvalues.length; - double newval = hybridPopModel.quantile(MathUtils.nextDouble()); - if (newval < 1E-10) { - newval = 1E-10; // grjtodo-soon. - // There is a problem. quantile(3.84E-7) with sensible param values returns 4.9E-324 - // GammaDistImpl(alpha=1,beta=6.5e-5) - } - hybpopvalues[tettrees.size()-1] = newval; - return hybridPopModel.logPdf(newval); - } - - - public double removeHybPopParam() { - assert tettrees.size() < hybpopvalues.length; - double oldval = hybpopvalues[tettrees.size()]; - hybpopvalues[tettrees.size()] = 0.0; // set unused dimension to impossible value - return hybridPopModel.logPdf(oldval); - } - - - public int getNumberOfTetraTrees() { - return tettrees.size(); - } - - public boolean getDiploidRootIsRoot() { - return diploidrootisroot; - } - - - public boolean getOneHybridization() { - return onehybridization; - } - - public int getNumberOfInternalNodesInTetTree(int n) { - return tettrees.get(n).getInternalNodeCount(); - } - - - public int getNumberOfInternalNodesInDipHist() { - return adhist.getInternalNodeCount(); - } - - - public AlloppLeggedTree getTetraploidTree(int t) { - return tettrees.get(t); - } - - public AlloppDiploidHistory getDiploidHistory() { - return adhist; - } - - - public int getNofDiploids() { - return nofdiploids; - } - - - // for merge and split moves - public void setTetTree(int oldtt, AlloppLeggedTree newttree) { - tettrees.set(oldtt, newttree); - } - - // for split move - public int addTetTree(AlloppLeggedTree tettree) { - tettrees.add(tettree); - return tettrees.size() - 1; - } - - // for merge move - public void removeTetree(int tt) { - tettrees.remove(tt); - } - - - // for move that flips all seqs of tet tree and its legs - public void flipLegsOfTetraTree(int tt) { - int oldlftleg = tettrees.get(tt).getDiphistLftLeg(); - int oldrgtleg = tettrees.get(tt).getDiphistRgtLeg(); - AlloppDiploidHistory.LegLorR lftLorR = adhist.getNodeLeg(oldlftleg); - AlloppDiploidHistory.LegLorR rgtLorR = adhist.getNodeLeg(oldrgtleg); - adhist.setNodeLeg(oldlftleg, rgtLorR); - adhist.setNodeLeg(oldrgtleg, lftLorR); - tettrees.get(tt).setDiphistLftLeg(oldrgtleg); - tettrees.get(tt).setDiphistRgtLeg(oldlftleg); - } - - public void moveLegs() { - // ood - } - - - - public int maxNumberOfHybPopParameters() { - return apsp.SpeciesWithinPloidyLevel(4).length; - } - - public void setOneHybPopValue(int i, double v) { - hybpopvalues[i] = v; - } - - /******************************** next bunch for lhood calculations **************************************/ - - - Parameter getTipPopValues() { - return tippopvalues; - } - - Parameter getRootPopValues() { - return rootpopvalues; - } - - public double getOneHybPopValue(int i) { - return hybpopvalues[i]; - } - - /* - * Called from AlloppSpeciesBindings to check if a node in a gene tree - * is compatible with the network. - */ - boolean coalescenceIsCompatible(double height, FixedBitSet union) { - boolean ok = mullabtree.coalescenceIsCompatible(height, union); - return ok; - } - - - /* - * Called from AlloppSpeciesBindings to remove coalescent information - * from branches of mullabtree. Required before call to recordCoalescence - */ - void clearCoalescences() { - mullabtree.clearCoalescences(); - } - - - /* - * Called from AlloppSpeciesBindings to add a node from a gene tree - * to its branch in mullabtree. - */ - void recordCoalescence(double height, FixedBitSet union) { - mullabtree.recordCoalescence(height, union); - } - - - void sortCoalescences() { - mullabtree.sortCoalescences(); - } - - - /* - * Records the number of gene lineages at nodes of mullabtree. - */ - void recordLineageCounts() { - mullabtree.recordLineageCounts(); - } - - - /* - * Calculates the log-likelihood for a single gene tree in the network - * - * Requires that clearCoalescences(), recordCoalescence(), recordLineageCounts() - * called to fill mullabtree with information about gene tree coalescences first. - */ - double geneTreeInNetworkLogLikelihood() { - return mullabtree.geneTreeInMULTreeLogLikelihood(); - } - - - - /********************** for logging ********************/ - - public TreeTrait[] getTreeTraits() { - return new TreeTrait[]{tti}; - } - - public TreeTrait getTreeTrait(String key) { - if (key.equals(tti.getTraitName())) { - return tti; - } - if (key.equals(hh.getTraitName())) { - return hh; - } - throw new IllegalArgumentException(); - } - - - /********************************************************************************/ - /*********************** private *******************************************/ - /********************************************************************************/ - - - /* - * Make a random initial starting network. - */ - private void makeInitialNDipsNTetsNetwork(Taxon[] dipspp, Taxon[] tetspp) { - // - double rate = 1.0; // scale later - assert tetspp.length > 0; - assert dipspp.length > 1; - ArrayList tetgps = new ArrayList(); - TetraTaxonGroup gp1 = new TetraTaxonGroup(); - if (onehybridization) { - for (int t = 0; t < tetspp.length; t++) { - gp1.add(tetspp[t]); - } - tetgps.add(gp1); - } else { - // Chinese restuarant process to partition tetraploids - gp1.add(tetspp[0]); - tetgps.add(gp1); - for (int t = 1; t < tetspp.length; t++) { - double [] pdf = new double[tetgps.size() + 1]; - for (int g = 0; g < tetgps.size(); g++) { - pdf[g] = tetgps.get(g).size(); - } - pdf[tetgps.size()] = 1; - int nextg = MathUtils.randomChoicePDF(pdf); - if (nextg == tetgps.size()) { - TetraTaxonGroup newgp = new TetraTaxonGroup(); - newgp.add(tetspp[t]); - tetgps.add(newgp); - } else { - tetgps.get(nextg).add(tetspp[t]); - } - } - } - // Make trees for each group of tetraploids - for (int g = 0; g < tetgps.size(); g++) { - Taxon [] gpspp = new Taxon[tetgps.get(g).size()]; - for (int t = 0; t < tetgps.get(g).size(); t++) { - gpspp[t] = tetgps.get(g).get(t); - } - AlloppLeggedTree tettree = new AlloppLeggedTree(gpspp, rate); - tettrees.add(tettree); - } - // Make diploid history given tetraploid subtrees - adhist = new AlloppDiploidHistory(dipspp, tettrees, diploidrootisroot, rate, apsp); - } - - - private class TetraTaxonGroup { - ArrayList tettxs; - TetraTaxonGroup() { tettxs = new ArrayList(); } - public void add(Taxon tx) { tettxs.add(tx); } - public Taxon get(int i) { return tettxs.get(i); } - public int size() { return tettxs.size(); } - } - - - private void makeLoggingHybPopParam() { - for (int i = 0; i < hybpopvalues.length; i++) { - logginghybpopvalues.setParameterValueQuietly(i, hybpopvalues[i]); - } - } - - /* - * Stretches or squashes all population values. Used by MCMC operators. - */ - private int scaleAllPopValues(double scale) { - int count = 0; - for (int i = 0; i < tippopvalues.getDimension(); i++) { - tippopvalues.setParameterValue(i, scale*tippopvalues.getParameterValue(i)); - count++; - } - for (int i = 0; i < rootpopvalues.getDimension(); i++) { - rootpopvalues.setParameterValue(i, scale*rootpopvalues.getParameterValue(i)); - count++; - } - for (int i = 0; i < tettrees.size(); i++) { - hybpopvalues[i] *= scale; - count++; - } - return count; - } - - - /* - * Stretches or squashes all node heights. Used by constructors and - * MCMC operators. - */ - private int scaleAllHeights(double scale) { - int count = adhist.scaleAllHeights(scale); - for (int i = 0; i < tettrees.size(); i++) { - count += tettrees.get(i).scaleAllHeights(scale); - } - return count; - } - - - - - private int numberOfTipPopParameters() { - int nditips = apsp.SpeciesWithinPloidyLevel(2).length; - int ntettips = apsp.SpeciesWithinPloidyLevel(4).length; - return nditips + ntettips; - } - - private int numberOfRootPopParameters() { - int nditips = apsp.SpeciesWithinPloidyLevel(2).length; - int ntettips = apsp.SpeciesWithinPloidyLevel(4).length; - return 2*(nditips + ntettips - 1); - } - - - - /***************************************************************************/ - /****************** Delgations for Tree ******************************/ - /***************************************************************************/ - - - public int getTaxonCount() { - return mullabtree.simptree.getTaxonCount(); - } - - public Taxon getTaxon(int taxonIndex) { - return mullabtree.simptree.getTaxon(taxonIndex); - } - - - public String getTaxonId(int taxonIndex) { - return mullabtree.simptree.getTaxonId(taxonIndex); - } - - - public int getTaxonIndex(String id) { - return mullabtree.simptree.getTaxonIndex(id); - } - - - public int getTaxonIndex(Taxon taxon) { - return mullabtree.simptree.getTaxonIndex(taxon); - } - - - public List asList() { - return mullabtree.simptree.asList(); - } - - - public Object getTaxonAttribute(int taxonIndex, String name) { - return mullabtree.simptree.getTaxonAttribute(taxonIndex, name); - } - - - public String getId() { - return mullabtree.simptree.getId(); - } - - - public void setId(String id) { - mullabtree.simptree.setId(id); - - } - - - public Iterator iterator() { - return mullabtree.simptree.iterator(); - } - - - public Type getUnits() { - return mullabtree.simptree.getUnits(); - } - - - public void setUnits(Type units) { - mullabtree.simptree.setUnits(units); - - } - - - public void setAttribute(String name, Object value) { - mullabtree.simptree.setAttribute(name, value); - - } - - - public Object getAttribute(String name) { - return mullabtree.simptree.getAttribute(name); - } - - - public Iterator getAttributeNames() { - return mullabtree.simptree.getAttributeNames(); - } - - - public NodeRef getRoot() { - return mullabtree.simptree.getRoot(); - } - - - public int getNodeCount() { - return mullabtree.simptree.getNodeCount(); - } - - - public NodeRef getNode(int i) { - return mullabtree.simptree.getNode(i); - } - - - public NodeRef getInternalNode(int i) { - return mullabtree.simptree.getInternalNode(i); - } - - - public NodeRef getExternalNode(int i) { - return mullabtree.simptree.getExternalNode(i); - } - - - public int getExternalNodeCount() { - return mullabtree.simptree.getExternalNodeCount(); - } - - - public int getInternalNodeCount() { - return mullabtree.simptree.getInternalNodeCount(); - } - - - public Taxon getNodeTaxon(NodeRef node) { - return mullabtree.simptree.getNodeTaxon(node); - } - - public boolean hasNodeHeights() { - return true; - } - - - public double getNodeHeight(NodeRef node) { - return mullabtree.simptree.getNodeHeight(node); - } - - - public boolean hasBranchLengths() { - return true; - } - - - public double getBranchLength(NodeRef node) { - return mullabtree.simptree.getBranchLength(node); - } - - - public double getNodeRate(NodeRef node) { - return mullabtree.simptree.getNodeRate(node); - } - - - public Object getNodeAttribute(NodeRef node, String name) { - return mullabtree.simptree.getNodeAttribute(node, name); - } - - - public Iterator getNodeAttributeNames(NodeRef node) { - return mullabtree.simptree.getNodeAttributeNames(node); - } - - - public boolean isExternal(NodeRef node) { - return mullabtree.simptree.isExternal(node); - } - - - public boolean isRoot(NodeRef node) { - return mullabtree.simptree.isRoot(node); - } - - - public int getChildCount(NodeRef node) { - int cc = mullabtree.simptree.getChildCount(node); - assert cc == 2; - return cc; - } - - - public NodeRef getChild(NodeRef node, int j) { - return mullabtree.simptree.getChild(node, j); - } - - - public NodeRef getParent(NodeRef node) { - return mullabtree.simptree.getParent(node); - } - - - public Tree getCopy() { - return mullabtree.simptree.getCopy(); - } - - - public boolean logNow(long state) { - // can set logEvery=0 in XML for multree: - // (ntettrees); - - Taxon l0 = new Taxon("L0"); - Taxon l1 = new Taxon("L1"); - Taxon l2 = new Taxon("L2"); - Taxon r0 = new Taxon("R0"); - Taxon r1 = new Taxon("R1"); - Taxon r2 = new Taxon("R2"); - - Taxon[] tets123 = {spp[1], spp[2], spp[3]}; - Taxon[] tets12 = {spp[1], spp[2]}; - Taxon[] tets1 = {spp[1]}; - Taxon[] tets2 = {spp[2]}; - Taxon[] tets3 = {spp[3]}; - Taxon[] dips = new Taxon[0]; - switch (testcase) { - case 1: - tettrees.add(new AlloppLeggedTree(tets123)); - tetheight0 = tettrees.get(0).getRootHeight(); - dips = new Taxon[] {spp[0], l0, r0, spp[4]}; - break; - case 2: - tettrees.add(new AlloppLeggedTree(tets123)); - tetheight0 = tettrees.get(0).getRootHeight(); - dips = new Taxon[] {spp[0], l0, r0, spp[4]}; - break; - case 3: - tettrees.add(new AlloppLeggedTree(tets123)); - tetheight0 = tettrees.get(0).getRootHeight(); - dips = new Taxon[] {spp[0], l0, r0, spp[4]}; - break; - case 4: - tettrees.add(new AlloppLeggedTree(tets12)); - tettrees.add(new AlloppLeggedTree(tets3)); - tetheight0 = tettrees.get(0).getRootHeight(); - tetheight1 = tettrees.get(1).getRootHeight(); - dips = new Taxon[] {spp[0], l0, r0, l1, r1, spp[4]}; - break; - case 5: - tettrees.add(new AlloppLeggedTree(tets1)); - tettrees.add(new AlloppLeggedTree(tets2)); - tettrees.add(new AlloppLeggedTree(tets3)); - tetheight0 = tettrees.get(0).getRootHeight(); - tetheight1 = tettrees.get(1).getRootHeight(); - tetheight2 = tettrees.get(2).getRootHeight(); - dips = new Taxon[] {spp[0], l0, r0, l1, r1, l2, r2, spp[4]}; - break; - } - assert dips.length >= 2; - int ndhnodes = 2*dips.length - 1; - SimpleNode[] dhnodes = new SimpleNode[ndhnodes]; - for (int n = 0; n < ndhnodes; n++) { - dhnodes[n] = new SimpleNode(); - if (n < dips.length) { - dhnodes[n].setTaxon(dips[n]); - } else { - dhnodes[n].setTaxon(new Taxon("")); - } - } - int dhroot = -1; - switch (testcase) { - case 1: - dhnodes[1].setHeight(tetheight0 + 1.0); - dhnodes[2].setHeight(tetheight0 + 1.0); - addSimpleNodeChildren(dhnodes[4], dhnodes[0], dhnodes[1], 1.0); - addSimpleNodeChildren(dhnodes[5], dhnodes[2], dhnodes[3], 1.0); - addSimpleNodeChildren(dhnodes[6], dhnodes[4], dhnodes[5], 1.0); - dhroot = 6; - break; - case 2: - dhnodes[1].setHeight(tetheight0 + 1.0); - dhnodes[2].setHeight(tetheight0 + 1.0); - addSimpleNodeChildren(dhnodes[4], dhnodes[0], dhnodes[1], 1.0); - addSimpleNodeChildren(dhnodes[5], dhnodes[2], dhnodes[4], 1.0); - addSimpleNodeChildren(dhnodes[6], dhnodes[3], dhnodes[5], 1.0); - dhroot = 6; - break; - case 3: - dhnodes[1].setHeight(tetheight0 + 1.0); - dhnodes[2].setHeight(tetheight0 + 1.0); - addSimpleNodeChildren(dhnodes[4], dhnodes[1], dhnodes[2], 1.0); - addSimpleNodeChildren(dhnodes[5], dhnodes[0], dhnodes[4], 1.0); - addSimpleNodeChildren(dhnodes[6], dhnodes[3], dhnodes[5], 1.0); - dhroot = 6; - break; - case 4: - dhnodes[1].setHeight(tetheight0 + 1.0); - dhnodes[2].setHeight(tetheight0 + 1.0); - dhnodes[3].setHeight(tetheight1 + 1.0); - dhnodes[4].setHeight(tetheight1 + 1.0); - addSimpleNodeChildren(dhnodes[6], dhnodes[0], dhnodes[1], 1.0); - addSimpleNodeChildren(dhnodes[7], dhnodes[3], dhnodes[4], 1.0); - addSimpleNodeChildren(dhnodes[8], dhnodes[6], dhnodes[7], 1.0); - addSimpleNodeChildren(dhnodes[9], dhnodes[2], dhnodes[5], 1.0); - addSimpleNodeChildren(dhnodes[10], dhnodes[8], dhnodes[9], 1.0); - dhroot = 10; - break; - case 5: - dhnodes[1].setHeight(tetheight0 + 1.0); - dhnodes[2].setHeight(tetheight0 + 1.0); - dhnodes[3].setHeight(tetheight1 + 1.0); - dhnodes[4].setHeight(tetheight1 + 1.0); - dhnodes[5].setHeight(tetheight2 + 1.0); - dhnodes[6].setHeight(tetheight2 + 1.0); - addSimpleNodeChildren(dhnodes[8], dhnodes[0], dhnodes[1], 1.0); - addSimpleNodeChildren(dhnodes[9], dhnodes[5], dhnodes[6], 1.0); - addSimpleNodeChildren(dhnodes[10], dhnodes[2], dhnodes[7], 1.0); - addSimpleNodeChildren(dhnodes[11], dhnodes[3], dhnodes[8], 1.0); - addSimpleNodeChildren(dhnodes[12], dhnodes[4], dhnodes[11], 1.0); - addSimpleNodeChildren(dhnodes[13], dhnodes[9], dhnodes[12], 1.0); - addSimpleNodeChildren(dhnodes[14], dhnodes[10], dhnodes[13], 1.0); - dhroot = 14; - break; - } - AlloppDiploidHistory adhist = new AlloppDiploidHistory(dhnodes, dhroot, tettrees, true, apsp); - int ntippopparams = numberOfTipPopParameters(); - int nrootpopparams = numberOfRootPopParameters(); - int maxnhybpopparams = maxNumberOfHybPopParameters(); - Parameter testtippopvalues = new Parameter.Default(ntippopparams); - Parameter testrootpopvalues = new Parameter.Default(nrootpopparams); - double [] testhybpopvalues = new double[maxnhybpopparams]; - for (int pp=0; pp. -*/ - -package dr.evomodel.alloppnet.speciation; - - -/** - * - * Model for prior for species delimitation in multispecies coalescent model. - * - * @author Graham Jones - * Date: 01/09/2013 - */ - -import dr.evolution.tree.NodeRef; -import dr.evolution.util.Taxon; -import dr.evolution.util.Units; -import dr.evolution.tree.Tree; -import dr.evomodel.speciation.SpeciationModel; -import dr.inference.model.Parameter; -import dr.util.Author; -import dr.util.Citable; -import dr.util.Citation; - -import java.util.*; -import java.util.logging.Logger; - - -public class BirthDeathCollapseModel extends SpeciationModel implements Citable { - private Parameter birthDiffRate; // lambda - mu - private Parameter relativeDeathRate; // mu/lambda - private Parameter originHeight; - private Parameter collapseWeight; - private final double collapseHeight; - - public BirthDeathCollapseModel(String modelName, Tree tree, Units.Type units, - Parameter birthDiffRate, Parameter relativeDeathRate, - Parameter originHeight, Parameter collapseWeight, double collH) { - super(modelName, units); - this.collapseHeight = collH; - - this.birthDiffRate = birthDiffRate; - addVariable(birthDiffRate); - birthDiffRate.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, 0.0, 1)); - - this.relativeDeathRate = relativeDeathRate; - addVariable(relativeDeathRate); - relativeDeathRate.addBounds(new Parameter.DefaultBounds(1.0, 0.0, 1)); - - this.originHeight = originHeight; - originHeight.setParameterValue(0, 1.05 * tree.getNodeHeight(tree.getRoot())); - addVariable(originHeight); - originHeight.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, 0.0, 1)); - - this.collapseWeight = collapseWeight; - addVariable(collapseWeight); - collapseWeight.addBounds(new Parameter.DefaultBounds(1.0, 0.0, 1)); - - Logger.getLogger("dr.evomodel.speciation").info("\tConstructing a birth-death-collapse model, please cite:\n" - + Citable.Utils.getCitationString(this)); - } - - - public double getCollapseHeight() { - return collapseHeight; - } - - // provided to help avoid inconsistent treatment of h == collapseHeight - public static boolean belowCollapseHeight(double h, double collapseHeight) { - return (h < collapseHeight); - } - - - @Override - public double calculateTreeLogLikelihood(Tree tree) { - double logpt = 0.0; - int ninodes = tree.getInternalNodeCount(); - int ntips = tree.getExternalNodeCount(); - double alpha = birthDiffRate.getParameterValue(0); - double beta = relativeDeathRate.getParameterValue(0); - double tor = originHeight.getParameterValue(0); - double w = collapseWeight.getParameterValue(0); - - double rooth = tree.getNodeHeight(tree.getRoot()); - if (rooth > tor) { - return Double.NEGATIVE_INFINITY; - } - - logpt += originHeightLogLikelihood(tor, alpha, beta, w, ntips); - - for (int n = 0; n < ninodes; n++) { - final double height = tree.getNodeHeight(tree.getInternalNode(n)); - double usualpn = nodeHeightLikelihood(height, tor, alpha, beta); - double collapsedpn = (height < collapseHeight) ? 1.0 / collapseHeight : 0.0; - logpt += Math.log((1.0 - w) * usualpn + w * collapsedpn); - } - - return logpt; - } - - - private double originHeightLogLikelihood(double t, double a, double b, double w, int n) { - double E = Math.exp(-a * t); - double B = (1 - E) / (1-b*E); - double z = 0.0; - z += Math.log(a); - z += Math.log(1 - b); - z -= a * t; - z -= 2 * Math.log(1 - b * E); - z += (n-2) * Math.log(w + (1 - w) * B); - z += Math.log(w + n * (1 - w) * B); - return z; - } - - - private double nodeHeightLikelihood(double s, double t, double a, double b) { - double Es = Math.exp(-a * s); - double Et = Math.exp(-a * t); - double z = 0.0; - if (s < t) { - z = a; - z *= (1 - b); - z *= Es; - z /= (1 - b * Es) * (1 - b * Es); - z *= (1 - b * Et); - z /= (1 - Et); - } - return z; - } - - - @Override - public double calculateTreeLogLikelihood(Tree tree, Set exclude) { - // not implemented. - return Double.NEGATIVE_INFINITY; - } - - @Override - public Citation.Category getCategory() { - return Citation.Category.SPECIES_MODELS; - } - - @Override - public String getDescription() { - return "DISSECT species delimitation model"; - } - - @Override - public List getCitations() { - return Collections.singletonList( - new Citation( - new Author[]{ - new Author("Graham", "Jones"), - new Author("Bengt", "Oxelman") - }, - "DISSECT: an assignment-free Bayesian discovery method for species delimitation under the multispecies coalescent", - 2014, - "BIORXIV/2014/003178", - -1, - -1, - -1, - Citation.Status.IN_SUBMISSION - )); - } -} diff --git a/src/dr/evomodel/alloppnet/speciation/BirthDeathCollapseNClustersStatistic.java b/src/dr/evomodel/alloppnet/speciation/BirthDeathCollapseNClustersStatistic.java deleted file mode 100644 index e5cd04aa3f..0000000000 --- a/src/dr/evomodel/alloppnet/speciation/BirthDeathCollapseNClustersStatistic.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * BirthDeathCollapseNClustersStatistic.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -/* - This file is part of BEAST. - - BEAST is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - BEAST is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with DISSECT. If not, see . -*/ - -package dr.evomodel.alloppnet.speciation; - - -import dr.evomodel.speciation.SpeciesTreeModel; -import dr.evomodel.alloppnet.parsers.BirthDeathCollapseNClustersStatisticParser; -import dr.inference.model.Statistic; - -/** - * @author Graham Jones - * Date: 01/10/2013 - */ -public class BirthDeathCollapseNClustersStatistic extends Statistic.Abstract { - private SpeciesTreeModel spptree; - private BirthDeathCollapseModel bdcm; - - - public BirthDeathCollapseNClustersStatistic(SpeciesTreeModel spptree, BirthDeathCollapseModel bdcm) { - super(BirthDeathCollapseNClustersStatisticParser.BDC_NCLUSTERS_STATISTIC); - this.spptree = spptree; - this.bdcm = bdcm; - } - - @Override - public int getDimension() { - return 1; - } - - @Override - public double getStatisticValue(int dim) { - int ninodes = spptree.getInternalNodeCount(); - int n = 0; - for (int i = 0; i < ninodes; i++) { - double h = spptree.getNodeHeight(spptree.getInternalNode(i)); - if (!BirthDeathCollapseModel.belowCollapseHeight(h, bdcm.getCollapseHeight())) { - n++; - } - } - return n+1; - } -} diff --git a/src/dr/evomodel/alloppnet/speciation/MulMSCoalescent.java b/src/dr/evomodel/alloppnet/speciation/MulMSCoalescent.java deleted file mode 100644 index 33dbcf06f5..0000000000 --- a/src/dr/evomodel/alloppnet/speciation/MulMSCoalescent.java +++ /dev/null @@ -1,317 +0,0 @@ -/* - * MulMSCoalescent.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.alloppnet.speciation; - -import dr.evolution.coalescent.DemographicFunction; -import dr.evolution.coalescent.ScaledDemographic; -import dr.evolution.tree.NodeRef; -import dr.evolution.tree.TreeUtils; -import dr.evolution.util.Units; -import dr.inference.model.Likelihood; -import dr.inference.model.Model; -import jebl.util.FixedBitSet; - -import java.util.Arrays; - -/** - * Compute coalescent log-likelihood of a set of gene trees embedded inside one multiply labelled species tree. - * - * @author Joseph Heled, Graham Jones - * Date: 29/12/2011 - */ - - -/* - * Very similar to MultiSpeciesCoalescent. (10/01/2012) - * - */ - -public class MulMSCoalescent extends Likelihood.Abstract implements Units { - private final MulSpeciesTreeModel spTree; - private final MulSpeciesBindings mulspb; - private boolean checkCompatibility; //grj not using this yet - private final boolean[] compatibleCheckRequired; //grj not using this yet - - public MulMSCoalescent(MulSpeciesBindings mulspb, MulSpeciesTreeModel sptree) { - super(sptree); - spTree = sptree; - this.mulspb = mulspb; - - spTree.addModelRestoreListener(this); - - // recompute on any change in geneTree - - // possible optimization: keep track which tree changed. - final MulSpeciesBindings.GeneTreeInfo[] trees = mulspb.getGeneTrees(); - for(MulSpeciesBindings.GeneTreeInfo geneTree : trees) { - geneTree.tree.addModelListener(this); - } - - compatibleCheckRequired = new boolean[trees.length]; - Arrays.fill(compatibleCheckRequired, false); - checkCompatibility = false; - } - - // override this for efficiency, otherwise the overridden makeDirty, which results in additional overhead is called - public void modelRestored(Model model) { - super.makeDirty(); - } - - // Upon a direct "make dirty" enable all compatibility checks, since the last call to calculateLogLikelihood may have - // found a non compatible tree and returned -inf. This case is not explicitly saved. - public void makeDirty() { - super.makeDirty(); - checkCompatibility = true; - for(int i = 0; i < mulspb.getGeneTrees().length; i++) { - compatibleCheckRequired[i] = true; - } - } - - protected double calculateLogLikelihood() { - if( checkCompatibility ) { - boolean compatibility = true; - - for(int i = 0; i < compatibleCheckRequired.length; ++i) { - if( compatibleCheckRequired[i] ) { - - if( !spTree.isCompatible(mulspb.getGeneTrees()[i]) ) { - compatibility = false; - } - compatibleCheckRequired[i] = false; - //System.out.println("check compatibility:" + species.getGeneTrees()[i].tree.getId() + " - " + compatibility ); - } - } - if( !compatibility ) { - return Double.NEGATIVE_INFINITY; - } - checkCompatibility = false; - } - - // grjtodo-oneday. For now, always do checks. Should make them when do a seq reassign, plus as above, otherwise not - for (int i = 0; i < mulspb.getGeneTrees().length; i++) { - if (!spTree.isCompatible(mulspb.getGeneTrees()[i])) { - return Double.NEGATIVE_INFINITY; - } - } - - double logl = 0; - int[] info = {0, 0}; - for( MulSpeciesBindings.GeneTreeInfo geneTree : mulspb.getGeneTrees() ) { - final double v = treeLogLikelihood(geneTree, spTree.getRoot(), info, geneTree.popFactor()); - assert ! Double.isNaN(v); -// if( Double.isNaN(v) ) { -// double x = 0; -// } - logl += v; - } - ccc += 1; - return logl; - } - - - - int ccc = 0; - private final boolean verbose = false; - - - - private double treeLogLikelihood(MulSpeciesBindings.GeneTreeInfo geneTree, NodeRef node, int[] info, double popFactor) { - // number of lineages remaining at node - int nLineages; - // location in coalescent list (optimization) - int indexInClist = 0; - // accumulated log-likelihood inBranchh from node to it's parent - double like = 0; - - final double t0 = spTree.getNodeHeight(node); - - final MulSpeciesBindings.CoalInfo[] cList = geneTree.getCoalInfo(); - - if( verbose ) { - if( spTree.isRoot(node) ) { - System.err.println("gtree:" + geneTree.tree.getId()); - System.err.println("t0 " + t0); - for(int k = 0; k < cList.length; ++k) { - System.err.println(k + " " + cList[k].ctime + " " + cList[k].sinfo[0] + " " + cList[k].sinfo[1]); - } - } - } - - if( spTree.isExternal(node) ) { - nLineages = geneTree.nLineages(spTree.speciesIndex(node)); - indexInClist = 0; - } else { - //assert spTree.getChildCount(node) == 2; - - nLineages = 0; - for(int nc = 0; nc < 2; ++nc) { - final NodeRef child = spTree.getChild(node, nc); - like += treeLogLikelihood(geneTree, child, info, popFactor); - nLineages += info[0]; - indexInClist = Math.max(indexInClist, info[1]); - } - - // The root of every gene tree (last coalescent point) should be always above - // root of species tree - if( indexInClist >= cList.length) { - System.err.println("ERROR in evomodel.speciation.MulMSCoalescent.treeLogLikelihood()"); - } - assert indexInClist < cList.length; - - // Skip over (presumably, not tested by assert) non interesting coalescent - // events to the first event before speciation point - - while( cList[indexInClist].ctime < t0 ) { - ++indexInClist; - } - } - - final boolean isRoot = spTree.isRoot(node); - - // Upper limit - // use of (t0 + spTree.getBranchLength(node)) caused problem since there was a tiny difference - // between those (supposedly equal) values. we should track where the discrepancy comes from. - final double stopTime = isRoot ? Double.MAX_VALUE : spTree.getNodeHeight(spTree.getParent(node)); - - // demographic function is 0 based (relative to node height) - // time away from node - double lastTime = 0.0; - - // demographic function across branch - DemographicFunction demog = spTree.getNodeDemographic(node); - if( popFactor > 0 ) { - demog = new ScaledDemographic(demog, popFactor); - } - -// if(false) { -// final double duration = isRoot ? cList[cList.length - 1].ctime - t0 : stopTime; -// double demographicAtCoalPoint = demog.getDemographic(duration); -// double intervalArea = demog.getIntegral(0, duration); -// if( demographicAtCoalPoint < 1e-12 * (duration/intervalArea) ) { -// return Double.NEGATIVE_INFINITY; -// } -// } - // Species sharing this branch - FixedBitSet subspeciesSet = spTree.spSet(node); - - if( verbose ) { - System.err.println(TreeUtils.uniqueNewick(spTree, node) + " nl " + nLineages - + " " + subspeciesSet + " t0 - st " + t0 + " - " + stopTime); - } - - while( nLineages > 1 ) { -// if ( !( indexInClist < cList.length ) ) { -// System.err.println( indexInClist ) ; -// } - assert ( indexInClist < cList.length ); - - final double nextT = cList[indexInClist].ctime; - - // while rare they can be equal - if( nextT >= stopTime ) { - break; - } - - if( nonEmptyIntersection(cList[indexInClist].sinfo, subspeciesSet) ) { - final double time = nextT - t0; - if( time > 0 ) { - final double interval = demog.getIntegral(lastTime, time); - lastTime = time; - - final int nLineageOver2 = (nLineages * (nLineages - 1)) / 2; - like -= nLineageOver2 * interval; - - final double pop = demog.getDemographic(time); assert( pop > 0 ); - like -= Math.log(pop); - } - --nLineages; - } - ++indexInClist; - } - - - if( nLineages > 1 ) { - // add term for No coalescent until root - final double interval = demog.getIntegral(lastTime, stopTime - t0); - - final int nLineageOver2 = (nLineages * (nLineages - 1)) / 2; - - like -= nLineageOver2 * interval; - } - - info[0] = nLineages; - info[1] = indexInClist; - if( verbose ) { - System.err.println(TreeUtils.uniqueNewick(spTree, node) + " stopTime " + stopTime + - " nl " + nLineages + " icl " + indexInClist); - } - return like; - } - - public void modelChangedEvent(Model model, Object object, int index) { - //super.modelChangedEvent(model, object, index); - // not the above for efficiency, otherwise the overridden makeDirty, which results in additional overhead is called. - super.makeDirty(); - - if( model == spTree ) { - if( object == spTree && index != -1 ) { - // Species tree scaling - checkCompatibility = true; - Arrays.fill(compatibleCheckRequired, true); - } - } else { - - final MulSpeciesBindings.GeneTreeInfo[] trees = mulspb.getGeneTrees(); - for(int i = 0; i < mulspb.getGeneTrees().length; i++) { - if( trees[i].tree == model ) { - checkCompatibility = true; - compatibleCheckRequired[i] = true; - break; - } - } - } - } - - private boolean nonEmptyIntersection(FixedBitSet[] sinfo, FixedBitSet subspeciesSet) { - for( FixedBitSet nodeSpSet : sinfo ) { - if( nodeSpSet.intersectCardinality(subspeciesSet) == 0 ) { - return false; - } - } - return true; - } - - - public Type getUnits() { - return spTree.getUnits(); - } - - public void setUnits(Type units) { - assert false; - } - -} diff --git a/src/dr/evomodel/alloppnet/speciation/MulSpeciesBindings.java b/src/dr/evomodel/alloppnet/speciation/MulSpeciesBindings.java deleted file mode 100644 index 48ba3fda0a..0000000000 --- a/src/dr/evomodel/alloppnet/speciation/MulSpeciesBindings.java +++ /dev/null @@ -1,938 +0,0 @@ -/* - * MulSpeciesBindings.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.alloppnet.speciation; - -import dr.evolution.tree.MutableTree; -import dr.evolution.tree.NodeRef; -import dr.evolution.tree.Tree; -import dr.evolution.util.Taxon; -import dr.evomodel.tree.TreeModel; -import dr.evomodel.alloppnet.parsers.MulSpeciesBindingsParser; -import dr.inference.loggers.LogColumn; -import dr.inference.loggers.Loggable; -import dr.inference.model.*; -import dr.math.MathUtils; -import dr.util.HeapSort; -import jebl.util.FixedBitSet; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -/** - * Binds taxa in gene trees to multiply labelled species. - * - * Extension of Joseph Heled's SpeciesBindings to deal with multiply labelled trees. - * It combines the SpeciesBindings code with functions from AlloppSpeciesBindings. - * - * @author Joseph Heled, Graham Jones - * Date: 21/12/2011 - */ - - - -public class MulSpeciesBindings extends AbstractModel implements Loggable { - // grj all gene trees - private final GeneTreeInfo[] geneTreeInfos; - - // grj Species definition - private final AlloppSpeciesBindings.ApSpInfo[] apspecies; - private final Taxon[] taxa; - private final Map taxon2index = new HashMap(); - private final int spsq[][]; - private final int numberOfSpSeqs; - - - // jh - private final double[][] popTimesPair; - private boolean dirty_pp; - - private final double[][] popTimesSingle; - private boolean dirty_sg; - private final boolean verbose = false; - - // grj - private class SpeciesIndivPair { - public int spIndex; - public int ivIndex; - - public SpeciesIndivPair(int spIndex, int ivIndex) { - this.spIndex = spIndex; - this.ivIndex = ivIndex; - } - } - - - // mostly grj - public MulSpeciesBindings(AlloppSpeciesBindings.ApSpInfo[] apspecies, TreeModel[] geneTrees, double[] popFactors) { - super(MulSpeciesBindingsParser.MUL_SPECIES); - - this.apspecies = apspecies; - - // make the flattened arrays - int n = 0; - for (AlloppSpeciesBindings.ApSpInfo apspi : apspecies) { - n += apspi.individuals.length; - } - AlloppSpeciesBindings.Individual [] indivs = new AlloppSpeciesBindings.Individual[n]; - n = 0; - for (AlloppSpeciesBindings.ApSpInfo apspi : apspecies) { - for (int i = 0; i < apspi.individuals.length; i++, n++) { - indivs[n] = apspi.individuals[i]; - } - } - int t = 0; - for (AlloppSpeciesBindings.Individual indiv : indivs) { - t += indiv.taxa.length; - } - taxa = new Taxon[t]; - t = 0; - for (AlloppSpeciesBindings.Individual indiv : indivs) { - for (int j = 0; j < indiv.taxa.length; j++, t++) { - taxa[t] = indiv.taxa[j]; - } - } - // set up maps to indices - for (int i = 0; i < taxa.length; i++) { - taxon2index.put(taxa[i], i); - } - spsq = new int[apspecies.length][]; - int spsqindex = 0; - for (int sp = 0; sp < apspecies.length; sp++) { - spsq[sp] = new int[apspecies[sp].ploidylevel/2]; - for (int seq = 0; seq < spsq[sp].length; seq++, spsqindex++) { - spsq[sp][seq] = spsqindex; - } - } - numberOfSpSeqs = spsqindex; - - geneTreeInfos = new GeneTreeInfo[geneTrees.length]; - for (int i = 0; i < geneTrees.length; i++) { - final TreeModel gtm = geneTrees[i]; - addModel(gtm); - geneTreeInfos[i] = new GeneTreeInfo(gtm, popFactors[i]); - } - - // like SpeciesBindings but using number of species-sequence pairs, not number of species - popTimesSingle = new double[numberOfSpSeqs][]; - for (int ns = 0; ns < popTimesSingle.length; ++ns) { - popTimesSingle[ns] = new double[allCoalPointsCount(ns)]; - } - dirty_sg = true; - - popTimesPair = new double[(numberOfSpSeqs * (numberOfSpSeqs - 1)) / 2][]; - { - final int nps = allPairCoalPointsCount(); - for (int ns = 0; ns < popTimesPair.length; ++ns) { - popTimesPair[ns] = new double[nps]; - } - } - - dirty_pp = true; - - addStatistic(new SpeciesLimits()); - } - - - - - - - // grj - public int numberOfGeneTrees() { - return geneTreeInfos.length; - } - - - // grj - public int nSpSeqs() { - return numberOfSpSeqs; - } - - // grj - public String apspeciesName(int i) { - return apspecies[i].name; - } - - - //grj - public int spseqindex2sp(int spsqindex) { - return spseqindex2spandseq(spsqindex)[0]; - } - - //grj - public int spseqindex2seq(int spsqindex) { - return spseqindex2spandseq(spsqindex)[1]; - } - - - - // grj - public SpeciesIndivPair apspeciesId2speciesindiv(String apspId) { - int sp = -1; - int iv = -1; - for (int s = 0; s < apspecies.length; s++) { - for (int i = 0; i < apspecies[s].individuals.length; i++) { - for (int t = 0; t < apspecies[s].individuals[i].taxa.length; t++) { - Taxon taxon = apspecies[s].individuals[i].taxa[t]; - if (taxon.getId().compareTo(apspId) == 0) { - sp = s; - iv = i; - } - } - } - } - assert sp != -1; - SpeciesIndivPair x = new SpeciesIndivPair(sp, iv); - - return x; - } - - // grj - public void permuteOneSpeciesOneIndivForOneGene() { - int i = MathUtils.nextInt(geneTreeInfos.length); - geneTreeInfos[i].permuteOneSpeciesOneIndiv(); - geneTreeInfos[i].wasChanged(); - } - - - // grj - public void permuteSetOfIndivsForOneGene() { - int i = MathUtils.nextInt(geneTreeInfos.length); - geneTreeInfos[i].permuteSetOfIndivs(); - geneTreeInfos[i].wasChanged(); - } - - - // grj - public String seqassignsAsText(int g) { - return geneTreeInfos[g].seqassignsAsText(); - } - - // grj - public String genetreeAsText(int g) { - return geneTreeInfos[g].genetreeAsText(); - } - - - /** - * Per species coalecent times. - *

- * Indexed by sp index, a list of coalescent times of taxa of this sp from all gene trees. - * - * @return Per species coalecent times - */ - // jh - public double[][] getPopTimesSingle() { - if (dirty_sg) { - for (int ns = 0; ns < popTimesSingle.length; ++ns) { - getAllCoalPoints(ns, popTimesSingle[ns]); - } - dirty_sg = false; - } - return popTimesSingle; - } - - // jh - public double[][] getPopTimesPair() { - if (dirty_pp) { - final int nsp = nSpSeqs(); - for (int ns1 = 0; ns1 < nsp - 1; ++ns1) { - final int z = (ns1 * (2 * nsp - ns1 - 3)) / 2 - 1; - - for (int ns2 = ns1 + 1; ns2 < nsp; ++ns2) { - getAllPairCoalPoints(ns1, ns2, popTimesPair[z + ns2]); - } - } - } - return popTimesPair; - } - - - // jh - private void getAllPairCoalPoints(int ns1, int ns2, double[] popTimes) { - - for (int i = 0; i < geneTreeInfos.length; i++) { - for (CoalInfo ci : geneTreeInfos[i].getCoalInfo()) { - if ((ci.sinfo[0].contains(ns1) && ci.sinfo[1].contains(ns2)) || - (ci.sinfo[1].contains(ns1) && ci.sinfo[0].contains(ns2))) { - popTimes[i] = ci.ctime; - break; - } - } - } - HeapSort.sort(popTimes); - } - - - // jh - private int allCoalPointsCount(int spseqIndex) { - int tot = 0; - for (GeneTreeInfo t : geneTreeInfos) { - if (t.nLineages(spseqIndex) > 0) { - tot += t.nLineages(spseqIndex) - 1; - } - } - return tot; - } - - - // length of points must be right - // jh - void getAllCoalPoints(int spseqIndex, double[] points) { - - int k = 0; - for (GeneTreeInfo t : geneTreeInfos) { - final int totCoalEvents = t.nLineages(spseqIndex) - 1; - int savek = k; - for (CoalInfo ci : t.getCoalInfo()) { -// if( ci == null ) { -// assert ci != null; -// } - if (ci.allHas(spseqIndex)) { - points[k] = ci.ctime; - ++k; - } - } - if (!(totCoalEvents >= 0 && savek + totCoalEvents == k) || (totCoalEvents < 0 && savek == k)) { - System.err.println(totCoalEvents); - } - assert (totCoalEvents >= 0 && savek + totCoalEvents == k) || (totCoalEvents < 0 && savek == k); - } - assert k == points.length; - HeapSort.sort(points); - } - - - // jh - private int allPairCoalPointsCount() { - return geneTreeInfos.length; - } - - - // jh - public double speciationUpperBound(FixedBitSet sub1, FixedBitSet sub2) { - //Determined by the last time any pair of sp's in sub1 x sub2 have been seen - // together in any of the gene trees.""" - - double bound = Double.MAX_VALUE; - for (GeneTreeInfo g : getGeneTrees()) { - for (CoalInfo ci : g.getCoalInfo()) { - // if past time of current bound, can't change it anymore - if (ci.ctime >= bound) { - break; - } - if ((ci.sinfo[0].intersectCardinality(sub1) > 0 && ci.sinfo[1].intersectCardinality(sub2) > 0) - || - (ci.sinfo[0].intersectCardinality(sub2) > 0 && ci.sinfo[1].intersectCardinality(sub1) > 0)) { - bound = ci.ctime; - break; - } - } - } - return bound; - } - - - // jh - public void makeCompatible(double rootHeight) { - for( GeneTreeInfo t : getGeneTrees() ) { - - MutableTree tree = t.tree; - - for (int i = 0; i < tree.getExternalNodeCount(); i++) { - final NodeRef node = tree.getExternalNode(i); - final NodeRef p = tree.getParent(node); - tree.setNodeHeight(p, rootHeight + tree.getNodeHeight(p)); - } - MutableTree.Utils.correctHeightsForTips(tree); - // (todo) ugly re-init - can I do something better? - t.wasChanged(); - t.getCoalInfo(); - t.wasBacked = false; - //t.wasChanged(); - } - } - - - // jh - class CoalInfo implements Comparable { - // zero based, 0 is taxa time, i.e. in tree branch units - final double ctime; - // sp info for each subtree - final FixedBitSet[] sinfo; - - CoalInfo(double t, int nc) { - ctime = t; - sinfo = new FixedBitSet[nc]; - } - - public int compareTo(CoalInfo o) { - return o.ctime < ctime ? +1 : (o.ctime > ctime ? -1 : 0); - } - - /** - * @param s - * @return true if all children have at least one taxa from sp 's' - */ - public boolean allHas(int s) { - for (FixedBitSet b : sinfo) { - if (!b.contains(s)) { - return false; - } - } - return true; - } - } - - - // jh + grj - /** - * Collect coalescence information for sub-tree rooted at 'node'. - * - * @param tree - * @param node - * @param loc Place node data in loc, sub-tree info before that. - * @param info array to fill - * @return location of next available location - */ - private int collectCoalInfo(Tree tree, NodeRef node, - GeneTreeInfo.SequenceAssignment[] seqassigns, int loc, CoalInfo[] info) { - - info[loc] = new CoalInfo(tree.getNodeHeight(node), tree.getChildCount(node)); - - int newLoc = loc - 1; - for (int i = 0; i < 2; i++) { - NodeRef child = tree.getChild(node, i); - info[loc].sinfo[i] = new FixedBitSet(nSpSeqs()); - - if (tree.isExternal(child)) { - Taxon taxon = tree.getNodeTaxon(child); - int ti = taxon2index.get(taxon); - int spseq = spsq[seqassigns[ti].spIndex][seqassigns[ti].seqIndex]; - info[loc].sinfo[i].set(spseq); - - assert tree.getNodeHeight(child) == 0; - } else { - final int used = collectCoalInfo(tree, child, seqassigns, newLoc, info); - for (int j = 0; j < info[newLoc].sinfo.length; ++j) { - info[loc].sinfo[i].union(info[newLoc].sinfo[j]); - } - newLoc = used; - } - } - return newLoc; - } - - - // mostly grj - public class GeneTreeInfo { - public final TreeModel tree; - private SequenceAssignment seqassigns[]; - private SequenceAssignment oldseqassigns[]; - private final int[] lineagesCount; - private CoalInfo[] cList; - private CoalInfo[] savedcList; - private boolean dirty; - private boolean wasBacked; - private final double popFactor; - - - /* class GeneTreeInfo.SequenceAssignments - * - * spIndex is an index for an allopolyploid species. For example, it identifies - * a bit in a FixedBitSet (union) in a MulLabTree - * - * seqIndex identifies a sequence copy for this gene and for each individual. - * seqIndex is 0 or 1 for tetraploids and it is these that get flipped to change - * assignments of sequence copies to legs in AlloppSpeciesNetworkModel (or - * equivalently to tips in a MulLabTree). - * - * 2011-06-23 spIndex is the same for all gene trees. Maybe - * allow non-rectangular data later. - */ - private class SequenceAssignment { - public int spIndex; - public int seqIndex; - - public SequenceAssignment(int spIndex, int seqIndex) { - this.spIndex = spIndex; - this.seqIndex = seqIndex; - } - - public String toString() { - String s = "" + seqIndex; - return s; - } - } - - - - // grj - GeneTreeInfo(TreeModel tree, double popFactor) { - this.tree = tree; - this.popFactor = popFactor; - seqassigns = new SequenceAssignment[taxa.length]; - oldseqassigns = new SequenceAssignment[taxa.length]; - - // This uses taxa list for *all* gene trees, not this gene tree. - for (int s = 0; s < apspecies.length; s++) { - for (int i = 0; i < apspecies[s].individuals.length; i++) { - int nseqs = apspecies[s].individuals[i].taxa.length; - int asgns[] = new int [nseqs]; - for (int x = 0; x < nseqs; x++) { - asgns[x] = x; - } - MathUtils.permute(asgns); - for (int x = 0; x < nseqs; x++) { - int t = taxon2index.get(apspecies[s].individuals[i].taxa[x]); - seqassigns[t] = new SequenceAssignment(s, asgns[x]); - oldseqassigns[t] = new SequenceAssignment(s, asgns[x]); - } - } - } - lineagesCount = new int[nSpSeqs()]; - Arrays.fill(lineagesCount, 0); - - for (int nl = 0; nl < lineagesCount.length; ++nl) { - int sp = spseqindex2sp(nl); - for (AlloppSpeciesBindings.Individual indiv : apspecies[sp].individuals) { - boolean got = false; - for (Taxon t : indiv.taxa) { - if (tree.getTaxonIndex(t) >= 0) { - got = true; - } - } - for (Taxon t : indiv.taxa) { - assert (tree.getTaxonIndex(t) >= 0) == got; - } - assert got; - if (got) { - ++lineagesCount[nl]; - } - } - } - - // this bit jh - cList = new CoalInfo[tree.getExternalNodeCount() - 1]; - savedcList = new CoalInfo[cList.length]; - wasChanged(); - getCoalInfo(); - wasBacked = false; - } - - - // grj - public String seqassignsAsText() { - String s = "Sequence assignments" + System.getProperty("line.separator"); - for (int tx = 0; tx < seqassigns.length; tx++) { - s += taxa[tx]; - s += ":"; - s += seqassigns[tx].seqIndex; - if (tx+1 < seqassigns.length && seqassigns[tx].spIndex != seqassigns[tx+1].spIndex) { - s += System.getProperty("line.separator"); - } else { - s += " "; - } - } - return s; - } - - // grj - public String genetreeAsText() { - return tree.getNewick(); - } - - // grj - public SequenceAssignment getSeqassigns(int tx) { - return seqassigns[tx]; - } - - - // grj - public void storeSequenceAssignments() { - for (int i = 0; i < seqassigns.length; i++) { - oldseqassigns[i].seqIndex = seqassigns[i].seqIndex; - } - } - - // grj - public void restoreSequenceAssignments() { - for (int i = 0; i < seqassigns.length; i++) { - seqassigns[i].seqIndex = oldseqassigns[i].seqIndex; - } - } - - - // grj - public void permuteOneSpeciesOneIndiv() { - int sp = MathUtils.nextInt(apspecies.length); - int iv = MathUtils.nextInt(apspecies[sp].individuals.length); - permuteOneAssignment(sp, iv); - } - - - /* grjtodo-oneday - * This is a bit odd. It collects individuals as (sp, iv) indices - * that `belong' to a node in the sense that any taxon (sequence) - * of an individual belongs to the clade of the node. - * I've used a set but not made SpeciesIndivPair's comparable - * so that if both sequences of an individual occurs in clade it appears - * twice. Then permuteOneAssignment() flips everything so that those - * occurring twice get flipped twice and so not changed. - * - * Result is that individuals with one but not two sequences in - * the clade of the node get flipped. Sometimes all individuals - * are flipped, sometimes none, sometimes just one, the last is the - * same as permuteOneSpeciesOneIndiv(). - * - * 2011-07-29 it appears to work OK on minimal testing and I - * don't have a good idea for a more rational or efficient version. - * - */ - public void permuteSetOfIndivs() { - int num = tree.getInternalNodeCount(); - int i = MathUtils.nextInt(num); - NodeRef node = tree.getInternalNode(i); - Set spivs = new HashSet(); - collectIndivsOfNode(node, spivs); - for (SpeciesIndivPair spiv : spivs) { - permuteOneAssignment(spiv.spIndex, spiv.ivIndex); - } - } - - - // jh - int nLineages(int spseqIndex) { - return lineagesCount[spseqIndex]; - } - - // jh - public CoalInfo[] getCoalInfo() { - if (dirty) { - swap(); - - collectCoalInfo(tree, tree.getRoot(), seqassigns, cList.length - 1, cList); - HeapSort.sort(cList); - dirty = false; - wasBacked = true; - } - - /* - CoalInfo check[] = new CoalInfo[cList.length]; - collectCoalInfo(tree, tree.getRoot(), seqassigns, check.length - 1, check); - HeapSort.sort(check); - for (int i=0; i spivs) { - if (tree.isExternal(node)) { - SpeciesIndivPair x = apspeciesId2speciesindiv(tree.getNodeTaxon(node).getId()); - spivs.add(x); - } else { - collectIndivsOfNode(tree.getChild(node, 0), spivs); - collectIndivsOfNode(tree.getChild(node, 1), spivs); - } - } - - - // grj - private void permuteOneAssignment(int sp, int iv) { - // grjtodo-tetraonly - int tx; - if (apspecies[sp].individuals[iv].taxa.length == 2) { - tx = taxon2index.get(apspecies[sp].individuals[iv].taxa[0]); - seqassigns[tx].seqIndex = 1 - seqassigns[tx].seqIndex; - tx = taxon2index.get(apspecies[sp].individuals[iv].taxa[1]); - seqassigns[tx].seqIndex = 1 - seqassigns[tx].seqIndex; - } - } - - } // end of GeneTreeInfo - - - // jh - public GeneTreeInfo[] getGeneTrees() { - return geneTreeInfos; - } - - - // jh + grj - protected void handleModelChangedEvent(Model model, Object object, int index) { - if (verbose) System.out.println(" SP binding: model changed " + model.getId()); - - dirty_sg = true; - dirty_pp = true; - - for (GeneTreeInfo g : geneTreeInfos) { - if (g.tree == model) { - g.wasChanged(); - break; - } - } - fireModelChanged(object, index); - } - - // jh - protected final void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) { - assert false; - } - - // grj - // jh comment was 'do on a per need basis'. I hope its ok to mix with doing always. - protected void storeState() { - for (GeneTreeInfo gti : geneTreeInfos) { - gti.storeSequenceAssignments(); - } - if (MulSpeciesTreeModel.DBUGTUNE) - System.err.println("MulSpeciesBindings.storeState()"); - } - - - - - // jh + grj - protected void restoreState() { - for (GeneTreeInfo gti : geneTreeInfos) { - gti.restoreSequenceAssignments(); - } - for (GeneTreeInfo g : geneTreeInfos) { - if (g.restore()) { - dirty_sg = true; - dirty_pp = true; - } - } - if (MulSpeciesTreeModel.DBUGTUNE) - System.err.println("MulSpeciesBindings.restoreState()"); - } - - - // jh + grj - protected void acceptState() { - for (GeneTreeInfo g : geneTreeInfos) { - g.accept(); - } - } - - - // grj - public LogColumn[] getColumns() { - int ncols = geneTreeInfos.length * taxa.length; - LogColumn[] columns = new LogColumn[ncols]; - for (int g = 0, i = 0; g < geneTreeInfos.length; g++) { - for (int tx = 0; tx < taxa.length; tx++, i++) { - GeneTreeInfo.SequenceAssignment sqa = geneTreeInfos[g].getSeqassigns(tx); - String header = "Gene" + g + "taxon" + tx; - columns[i] = new LogColumn.Default(header, sqa); - } - - } - - return columns; - } - - // jh - public class SpeciesLimits extends Statistic.Abstract { - int nDim; - int c[][]; - - SpeciesLimits() { - super("SpeciationBounds"); - - nDim = 0; - - final int nsp = nSpSeqs(); - - c = new int[nsp + 1][nsp + 1]; - for(int k = 0; k < nsp + 1; ++k) { - c[k][0] = 1; - c[k][k] = 1; - } - for(int k = 0; k < nsp + 1; ++k) { - for(int j = 1; j < k; ++j) { - c[k][j] = c[k - 1][j - 1] + c[k - 1][j]; - } - } - - for(int k = 0; k <= (int) (nsp / 2); ++k) { - nDim += c[nsp][k]; - } - - } - - // jh - public int getDimension() { - return nDim; - } - - // jh - private double boundOnRoot() { - double bound = Double.MAX_VALUE; - final int nsp = nSpSeqs(); - for(GeneTreeInfo g : getGeneTrees()) { - for(CoalInfo ci : g.getCoalInfo()) { - if( ci.sinfo[0].cardinality() == nsp || ci.sinfo[1].cardinality() == nsp ) { - bound = Math.min(bound, ci.ctime); - break; - } - } - } - return bound; - } - - // jh - public double getStatisticValue(int dim) { - if( dim == 0 ) { - return boundOnRoot(); - } - - final int nsp = nSpSeqs(); - int r = 0; - int k; - for(k = 0; k <= (int) (nsp / 2); ++k) { - final int i = c[nsp][k]; - if( dim < r + i ) { - break; - } - r += i; - } - - // Classic index -> select k of nsp subset - - // number of species in set is k - int n = dim - r; - FixedBitSet in = new FixedBitSet(nsp), - out = new FixedBitSet(nsp); - int fr = nsp; - for(int i = 0; i < nsp; ++i) { - if( k == 0 ) { - out.set(i); - } else { - if( n < c[fr - 1][k - 1] ) { - in.set(i); - k -= 1; - } else { - out.set(i); - n -= c[fr - 1][k]; - } - fr -= 1; - } - } - return speciationUpperBound(in, out); - } - } - - - - // grj - private int[] spseqindex2spandseq(int spsqindex) { - int indexp = -1; - int indexq = -1; - for (int p = 0; p < spsq.length; p++) { - for (int q = 0; q < spsq[p].length; q++) { - if (spsq[p][q] == spsqindex) { - assert indexp == -1; - assert indexq == -1; - indexp = p; - indexq = q; - } - } - } - assert indexp != -1; - assert indexq != -1; - int[] pq = new int[2]; - pq[0] = indexp; - pq[1] = indexq; - return pq; - } - -} \ No newline at end of file diff --git a/src/dr/evomodel/alloppnet/speciation/MulSpeciesTreeModel.java b/src/dr/evomodel/alloppnet/speciation/MulSpeciesTreeModel.java deleted file mode 100644 index 1a32ef84c9..0000000000 --- a/src/dr/evomodel/alloppnet/speciation/MulSpeciesTreeModel.java +++ /dev/null @@ -1,1567 +0,0 @@ -/* - * MulSpeciesTreeModel.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.alloppnet.speciation; - -import dr.evolution.coalescent.DemographicFunction; -import dr.evolution.io.NewickImporter; -import dr.evolution.tree.*; -import dr.evolution.util.MutableTaxonListListener; -import dr.evolution.util.Taxon; -import dr.evomodel.coalescent.VDdemographicFunction; -import dr.evomodel.alloppnet.operators.MulTreeNodeSlide; -import dr.evomodel.tree.TreeLogger; -import dr.evomodel.alloppnet.parsers.MulSpeciesTreeModelParser; -import dr.inference.loggers.LogColumn; -import dr.inference.model.AbstractModel; -import dr.inference.model.Model; -import dr.inference.model.Parameter; -import dr.inference.model.Variable; -import dr.inference.operators.Scalable; -import dr.evomodel.alloppnet.util.AlloppMisc; -import dr.util.Author; -import dr.util.Citable; -import dr.util.Citation; -import dr.util.HeapSort; -import jebl.util.FixedBitSet; - -import java.util.*; -import java.util.logging.Logger; - -/** - * Multiply labelled species tree which includes demographic function per branch. - * - * @author Joseph Heled, Graham Jones - * Date: 20/12/2011 - */ - -/* - * grjtodo-oneday This includes a lot of code from SpeciesTreeModel. It would be better to re-use! - * Not clear how: neither contain nor extend seems ideal. This uses - * a MulSpeciesBindings which is seriously different from a SpeciesBindings. - * - * Or, at least simplify this, removing the bmp = brownian motion prior - * and the piece-wise linear model for population sizes. - * - */ - - -public class MulSpeciesTreeModel extends AbstractModel implements MutableTree, Citable, TreeTraitProvider, TreeLogger.LogUpon, Scalable { - private final SimpleTree spTree; - private final MulSpeciesBindings mulspb; - private final Map props = new HashMap(); - public final Parameter sppSplitPopulations; - private int[] singleStartPoints; - private int[] pairStartPoints; - - private final Parameter coalPointsPops; - private final Parameter coalPointsIndicator; - private boolean nodePropsReady; - - private final NodeRef[] children; - private final double[] heights; - - // any change of underlying parameters / models - private boolean anyChange; - // Tree has been edited in this cycle - private boolean treeChanged; - - private final String spIndexAttrName = "spi"; - private final boolean bmp; - private final boolean nonConstRootPopulation; - private final boolean constantPopulation; - - // grj - public final static boolean DBUGTUNE = false; - - - - private class NodeProperties { - private final int speciesIndex; - public VDdemographicFunction demogf; - FixedBitSet spSet; - - public NodeProperties(int n) { - speciesIndex = n; - demogf = null; - spSet = new FixedBitSet(mulspb.nSpSeqs()); - } - } - - public MulSpeciesTreeModel(MulSpeciesBindings species, Parameter sppSplitPopulations, - Parameter coalPointsPops, Parameter coalPointsIndicator, Tree startTree, - boolean bmp, boolean nonConstRootPopulation, boolean constantPopulation) { - super(MulSpeciesTreeModelParser.MUL_SPECIES_TREE); - - this.mulspb = species; - - this.sppSplitPopulations = sppSplitPopulations; - this.coalPointsPops = coalPointsPops; - this.coalPointsIndicator = coalPointsIndicator; - - this.bmp = bmp; - this.nonConstRootPopulation = nonConstRootPopulation; - this.constantPopulation = constantPopulation; - - addVariable(sppSplitPopulations); - - addModel(species); - - if (coalPointsPops != null) { - assert coalPointsIndicator != null; - assert !constantPopulation; - - addVariable(coalPointsPops); - addVariable(coalPointsIndicator); - - final double[][] pts = species.getPopTimesSingle(); - - int start = 0; - singleStartPoints = new int[pts.length]; - for (int i = 0; i < pts.length; i++) { - singleStartPoints[i] = start; - start += pts[i].length; - } - - if (!bmp) { - final double[][] ptp = species.getPopTimesPair(); - pairStartPoints = new int[ptp.length]; - for (int i = 0; i < ptp.length; i++) { - pairStartPoints[i] = start; - start += ptp[i].length; - } - } - } - - // build an initial noninformative tree - spTree = compatibleUninformedSpeciesTree(startTree); - - // some of the code is generic but some parts assume a binary tree. - assert TreeUtils.isBinary(spTree); - - final int nNodes = spTree.getNodeCount(); - heights = new double[nNodes]; - children = new NodeRef[2 * nNodes + 1]; - - // fixed properties - for (int k = 0; k < getExternalNodeCount(); ++k) { - final NodeRef nodeRef = getExternalNode(k); - final int n = (Integer) getNodeAttribute(nodeRef, spIndexAttrName); - final NodeProperties np = new NodeProperties(n); - props.put(nodeRef, np); - np.spSet.set(n); - } - - for (int k = 0; k < getInternalNodeCount(); ++k) { - final NodeRef nodeRef = getInternalNode(k); - props.put(nodeRef, new NodeProperties(-1)); - } - - nodePropsReady = false; - - // crappy way to pass a result back from compatibleUninformedSpeciesTree. - // check is using isCompatible(), which requires completion of construction. - boolean check = spTree.getAttribute("check") != null; - spTree.setAttribute("check", null); - - if (check) { - // change only is needed - if the user provided a compatible state she may know - // what she is doing - for (MulSpeciesBindings.GeneTreeInfo gt : species.getGeneTrees()) { - if (!isCompatible(gt)) { - - species.makeCompatible(spTree.getRootHeight()); - for (MulSpeciesBindings.GeneTreeInfo t : species.getGeneTrees()) { - assert isCompatible(t); - } - anyChange = false; - break; - } - } - } - - Logger.getLogger("dr.evomodel.speciation.allopolyploid").info("\tConstructing a multiply labelled tree, please cite:\n" - + Citable.Utils.getCitationString(this)); - - } - - - - // grj - private String nodeAsText(NodeRef node, int indentlen) { - StringBuilder s = new StringBuilder(); - Formatter formatter = new Formatter(s, Locale.US); - if (spTree.isExternal(node)) { - formatter.format("%s ", spTree.getNodeTaxon(node)); - } else { - formatter.format("%s ", "+"); - } - while (s.length() < 20-indentlen) { - formatter.format("%s", " "); - } - formatter.format("%s ", AlloppMisc.nonnegIn8Chars(spTree.getNodeHeight(node))); - // it would be nice to disply popsizes and nlineages like allopp mul tree - return s.toString(); - } - - - - // grj - private String subtreeAsText(NodeRef node, String s, Stack x, int depth, String b) { - Integer[] y = x.toArray(new Integer[x.size()]); - StringBuffer indent = new StringBuffer(); - for (int i = 0; i < depth; i++) { - indent.append(" "); - } - for (int i = 0; i < y.length; i++) { - indent.replace(2*y[i], 2*y[i]+1, "|"); - } - if (b.length() > 0) { - indent.replace(indent.length()-b.length(), indent.length(), b); - } - s += indent; - s += nodeAsText(node, indent.length()); - s += System.getProperty("line.separator"); - String subs = ""; - if (!spTree.isExternal(node)) { - x.push(depth); - subs += subtreeAsText(spTree.getChild(node, 0), "", x, depth+1, "-"); - x.pop(); - subs += subtreeAsText(spTree.getChild(node, 1), "", x, depth+1, "`-"); - } - return s + subs; - } - - - - // grj - public String asText() { - String header = "topology height" + System.getProperty("line.separator"); - - String s = ""; - Stack x = new Stack(); - return header + subtreeAsText(spTree.getRoot(), s, x, 0, ""); - } - - - public String toString() { - int ngt = mulspb.numberOfGeneTrees(); - String nl = System.getProperty("line.separator"); - String s = nl + asText() + nl; - for (int g = 0; g < ngt; g++) { - s += "Gene tree " + g + nl; - s += mulspb.genetreeAsText(g) + nl; - s += mulspb.seqassignsAsText(g) + nl; - } - s += nl; - return s; - } - - - - // grj - public LogColumn[] getColumns() { - LogColumn[] columns = new LogColumn[1]; - columns[0] = new LogColumn.Default(" MUL-tree and gene trees", this); - return columns; - } - - - - - - public boolean constPopulation() { - return constantPopulation; - } - - // Is gene tree compatible with species tree - // grj: the sequence assignments are handled in geneTreeInfo.getCoalInfo() - public boolean isCompatible(MulSpeciesBindings.GeneTreeInfo geneTreeInfo) { - // can't set demographics if a tree is not compatible, but we need spSets. - if (!nodePropsReady) { - setSPsets(getRoot()); - } - return isSubtreeCompatible(getRoot(), geneTreeInfo.getCoalInfo(), 0) >= 0; - } - - - - // Not very efficient, should do something better, based on traversing the cList once - private int isSubtreeCompatible(NodeRef node, MulSpeciesBindings.CoalInfo[] cList, int loc) { - if (!isExternal(node)) { - int l = -1; - for (int nc = 0; nc < getChildCount(node); ++nc) { - int l1 = isSubtreeCompatible(getChild(node, nc), cList, loc); - if (l1 < 0) { - return -1; - } - assert l == -1 || l1 == l; - - l = l1; - } - loc = l; - - assert cList[loc].ctime >= getNodeHeight(node); - } - - if (node == getRoot()) { - return cList.length; - } - - // spSet guaranteed to be ready by caller - final FixedBitSet nodeSps = props.get(node).spSet; - - final double limit = getNodeHeight(getParent(node)); - - while (loc < cList.length) { - final MulSpeciesBindings.CoalInfo ci = cList[loc]; - if (ci.ctime >= limit) { - break; - } - boolean allIn = true, noneIn = true; - - for (int i = 0; i < 2; ++i) { - final FixedBitSet s = ci.sinfo[i]; - - final int in1 = s.intersectCardinality(nodeSps); - if (in1 > 0) { - noneIn = false; - } - if (s.cardinality() != in1) { - allIn = false; - } - } - if (!(allIn || noneIn)) { - return -1; - } - ++loc; - } - return loc; - } - - - private static double - fp(double val, double low, double[][] tt, int[] ii) { - for (int k = 0; k < ii.length; ++k) { - int ip = ii[k]; - if (ip == tt[k].length || val <= tt[k][ip]) { - --ip; - while (ip >= 0 && val <= tt[k][ip]) { - --ip; - } - assert ((ip < 0) || (tt[k][ip] < val)) && ((ip + 1 == tt[k].length) || (val <= tt[k][ip + 1])); - if (ip >= 0) { - low = Math.max(low, tt[k][ip]); - } - } else { - ++ip; - while (ip < tt[k].length && val > tt[k][ip]) { - ++ip; - } - assert tt[k][ip - 1] < val && ((ip == tt[k].length) || (val <= tt[k][ip])); - low = Math.max(low, tt[k][ip - 1]); - } - } - return low; - } - - private interface SimpleDemographicFunction { - double population(double t); - - double upperBound(); - } - - private class PLSD implements SimpleDemographicFunction { - private final double[] pops; - private final double[] times; - - public PLSD(double[] pops, double[] times) { - assert pops.length == times.length + 1; - - this.pops = pops; - this.times = times; - } - - public double population(double t) { - if (t >= upperBound()) { - return pops[pops.length - 1]; - } - - int k = 0; - while (t > times[k]) { - t -= times[k]; - ++k; - } - double a = t / (times[k] - (k > 0 ? times[k - 1] : 0)); - return a * pops[k] + (1 - a) * pops[k + 1]; - } - - public double upperBound() { - return times[times.length - 1]; - } - } - // Pass arguments of recursive functions in a compact format. - - private class Args { - final double[][] cps = mulspb.getPopTimesSingle(); - final double[][] cpp; // = species.getPopTimesPair(); - final int[] iSingle = new int[cps.length]; - final int[] iPair; // = new int[cpp.length]; - - final double[] indicators = ((Parameter.Default) coalPointsIndicator).inspectParameterValues(); - final double[] pops = ((Parameter.Default) coalPointsPops).inspectParameterValues(); - final SimpleDemographicFunction[] dms; - - Args(Boolean bmp) { - if (!bmp) { - cpp = mulspb.getPopTimesPair(); - iPair = new int[cpp.length]; - dms = null; - } else { - cpp = null; - iPair = null; - int nsps = cps.length; - dms = new SimpleDemographicFunction[nsps]; - for (int nsp = 0; nsp < nsps; ++nsp) { - final int start = singleStartPoints[nsp]; - final int stop = nsp < nsps - 1 ? singleStartPoints[nsp + 1] : pops.length; - - double[] pop = new double[1 + stop - start]; - pop[0] = sppSplitPopulations.getParameterValue(nsp); // pops[nsp]; - - for (int k = 0; k < stop - start; ++k) { - pop[k + 1] = pops[start + k]; - } - dms[nsp] = new PLSD(pop, cps[nsp]); - } - } - } - - private double findPrev(double val, double low) { - low = fp(val, low, cps, iSingle); - low = fp(val, low, cpp, iPair); - - return low; - } - } - - class RawPopulationHelper { - final int[] preOrderIndices = new int[getNodeCount()]; - final double[] pops = ((Parameter.Default) sppSplitPopulations).inspectParameterValues(); - final int nsp = mulspb.nSpSeqs(); - final Args args = coalPointsPops != null ? new Args(bmp) : null; - - RawPopulationHelper() { - setPreorderIndices(preOrderIndices); - } - - public void getPopulations(NodeRef n, int nc, double[] p) { - p[1] = pops[nsp + 2 * preOrderIndices[n.getNumber()] + nc]; - - final NodeRef child = getChild(n, nc); - if (isExternal(child)) { - p[0] = pops[props.get(child).speciesIndex]; - } else { - int k = nsp + 2 * preOrderIndices[child.getNumber()]; - p[0] = pops[k] + pops[k + 1]; - } - } - - public double tipPopulation(NodeRef tip) { - return pops[props.get(tip).speciesIndex]; - } - - // grj: this doesn't work for multiply labelled tree. - // Use nSqSeqs() instead for most purposes - /*public int nSpecies() { - return species.nSpecies(); - }*/ - - public boolean perSpeciesPopulation() { - return args != null; - } - - public double[] getTimes(int ns) { - return ((PLSD) args.dms[ns]).times; - } - - public double[] getPops(int ns) { - return ((PLSD) args.dms[ns]).pops; - } - - public void getRootPopulations(double[] p) { - int k = nsp + 2 * preOrderIndices[getRoot().getNumber()]; - p[0] = pops[k] + pops[k + 1]; - p[1] = nonConstRootPopulation ? pops[pops.length - 1] : p[0]; - } - - public double geneTreesRootHeight() { - //getNodeDemographic(getRoot()). - double h = -1; - for (MulSpeciesBindings.GeneTreeInfo t : mulspb.getGeneTrees()) { - h = Math.max(h, t.tree.getNodeHeight(t.tree.getRoot())); - } - return h; - } - } - - RawPopulationHelper getPopulationHelper() { - return new RawPopulationHelper(); - } - - static private class Points implements Comparable { - final double time; - double population; - final boolean use; - - Points(double t, double p) { - time = t; - population = p; - use = true; - } - - Points(double t, boolean u) { - time = t; - population = 0; - use = u; - } - - public int compareTo(Points points) { - return time < points.time ? -1 : (time > points.time ? 1 : 0); - } - } - - private NodeProperties - setSPsets(NodeRef nodeID) { - final NodeProperties nprop = props.get(nodeID); - - if (!isExternal(nodeID)) { - nprop.spSet = new FixedBitSet(mulspb.nSpSeqs()); - for (int nc = 0; nc < getChildCount(nodeID); ++nc) { - NodeProperties p = setSPsets(getChild(nodeID, nc)); - nprop.spSet.union(p.spSet); - } - } - return nprop; - } - - private int ti2f(int i, int j) { - return (i == 0) ? j : 2 * i + j + 1; - } - - private VDdemographicFunction - bestLinearFit(double[] xs, double[] ys, boolean[] use) { - - assert (xs.length + 1) == ys.length; - assert ys.length == use.length + 2 || ys.length == use.length + 1; - - int N = ys.length; - if (N == 2) { - // cheaper - return new VDdemographicFunction(xs, ys, getUnits()); - } - - List iv = new ArrayList(2); - iv.add(0); - for (int k = 0; k < N - 2; ++k) { - if (use[k]) { - iv.add(k + 1); - } - } - iv.add(N - 1); - - double[] ati = new double[xs.length + 1]; - ati[0] = 0.0; - System.arraycopy(xs, 0, ati, 1, xs.length); - int n = iv.size(); - - double[] a = new double[3 * n]; - double[] v = new double[n]; - - for (int k = 0; k < n - 1; ++k) { - int i0 = iv.get(k); - int i1 = iv.get(k + 1); - - double u0 = ati[i0]; - double u1 = ati[i1] - ati[i0]; - // on last interval add data for last point - if (i1 == N - 1) { - i1 += 1; - } - - final int l = ti2f(k, k); - final int l1 = ti2f(k + 1, k); - - for (int j = i0; j < i1; ++j) { - double t = ati[j]; - double y = ys[j]; - - double z = (t - u0) / u1; - v[k] += y * (1 - z); - - a[l] += (1 - z) * (1 - z); - a[l + 1] += z * (1 - z); - - a[l1] += z * (1 - z); - a[l1 + 1] += z * z; - v[k + 1] += y * z; - } - } - - for (int k = 0; k < n - 1; ++k) { - - final double r = a[ti2f(k + 1, k)] / a[ti2f(k, k)]; - for (int j = k; j < k + 3; ++j) { - a[ti2f((k + 1), j)] -= a[ti2f(k, j)] * r; - } - v[k + 1] -= v[k] * r; - } - - double[] z = new double[n]; - for (int k = n - 1; k > 0; --k) { - z[k] = v[k] / a[ti2f(k, k)]; - v[k - 1] -= a[ti2f((k - 1), k)] * z[k]; - } - - z[0] = v[0] / a[ti2f(0, 0)]; - double[] t = new double[iv.size() - 1]; - for (int j = 0; j < t.length; ++j) { - t[j] = ati[iv.get(j + 1)]; - } - return new VDdemographicFunction(t, z, getUnits()); - } - - // Assign positions in 'pointsList' for the sub-tree rooted at the ancestor of - // nodeID. - // - // pointsList is indexed by node-id. Every element is a list of internal - // population points for the branch between nodeID and it's ancestor - // - - private NodeProperties getDemographicPoints(final NodeRef nodeID, Args args, Points[][] pointsList) { - - final NodeProperties nprop = props.get(nodeID); - final int nSpSeqs = mulspb.nSpSeqs(); - - // Species assignment from the tips never changes - if (!isExternal(nodeID)) { - nprop.spSet = new FixedBitSet(nSpSeqs); - for (int nc = 0; nc < getChildCount(nodeID); ++nc) { - final NodeProperties p = getDemographicPoints(getChild(nodeID, nc), args, pointsList); - nprop.spSet.union(p.spSet); - } - } - - if (args == null) { - return nprop; - } - - // parent height - final double cHeight = nodeID != getRoot() ? getNodeHeight(getParent(nodeID)) : Double.MAX_VALUE; - - // points along branch - // not sure what a good default size is? - List allPoints = new ArrayList(5); - - if (bmp) { - for (int isp = nprop.spSet.nextOnBit(0); isp >= 0; isp = nprop.spSet.nextOnBit(isp + 1)) { - final double[] cp = args.cps[isp]; - final int upi = singleStartPoints[isp]; - - int i = args.iSingle[isp]; - for (/**/; i < cp.length && cp[i] < cHeight; ++i) { - allPoints.add(new Points(cp[i], args.indicators[upi + i] > 0)); - } - args.iSingle[isp] = i; - } - } else { - - for (int isp = nprop.spSet.nextOnBit(0); isp >= 0; isp = nprop.spSet.nextOnBit(isp + 1)) { - final double nodeHeight = spTree.getNodeHeight(nodeID); - { - double[] cp = args.cps[isp]; - final int upi = singleStartPoints[isp]; - - int i = args.iSingle[isp]; - - while (i < cp.length && cp[i] < cHeight) { - if (args.indicators[upi + i] > 0) { - //System.out.println(" popbit s"); - args.iSingle[isp] = i; - double prev = args.findPrev(cp[i], nodeHeight); - double mid = (prev + cp[i]) / 2.0; - assert nodeHeight < mid; - allPoints.add(new Points(mid, args.pops[upi + i])); - } - ++i; - } - args.iSingle[isp] = i; - } - - final int kx = (isp * (2 * nSpSeqs - isp - 3)) / 2 - 1; - for (int y = nprop.spSet.nextOnBit(isp + 1); y >= 0; y = nprop.spSet.nextOnBit(y + 1)) { - - assert isp < y; - int k = kx + y; - - double[] cp = args.cpp[k]; - int i = args.iPair[k]; - final int upi = pairStartPoints[k]; - - while (i < cp.length && cp[i] < cHeight) { - if (args.indicators[upi + i] > 0) { - //System.out.println(" popbit p"); - args.iPair[k] = i; - final double prev = args.findPrev(cp[i], nodeHeight); - double mid = (prev + cp[i]) / 2.0; - assert nodeHeight < mid; - allPoints.add(new Points(mid, args.pops[upi + i])); - } - ++i; - } - args.iPair[k] = i; - } - } - } - - Points[] all = null; - - if (allPoints.size() > 0) { - all = allPoints.toArray(new Points[allPoints.size()]); - if (all.length > 1) { - HeapSort.sort(all); - } - - int len = all.length; - - if (bmp) { - int k = 0; - while (k + 1 < len) { - final double t = all[k].time; - if (t == all[k + 1].time) { - int j = k + 2; - boolean use = all[k].use || all[k + 1].use; - - while (j < len && t == all[j].time) { - use = use || all[j].use; - j += 1; - } - int removed = (j - k - 1); - all[k] = new Points(t, use); - for (int i = k + 1; i < len - removed; ++i) { - all[i] = all[i + removed]; - } - len -= removed; - } - ++k; - } - } else { - // duplications - - int k = 0; - while (k + 1 < len) { - double t = all[k].time; - if (t == all[k + 1].time) { - int j = k + 2; - double v = all[k].population + all[k + 1].population; - while (j < len && t == all[j].time) { - v += all[j].population; - j += 1; - } - int removed = (j - k - 1); - all[k] = new Points(t, v / (removed + 1)); - for (int i = k + 1; i < len - removed; ++i) { - all[i] = all[i + removed]; - } - //System.arraycopy(all, j, all, k + 1, all.length - j + 1); - len -= removed; - } - ++k; - } - } - - if (len != all.length) { - Points[] a = new Points[len]; - System.arraycopy(all, 0, a, 0, len); - all = a; - } - - if (bmp) { - for (Points p : all) { - double t = p.time; - assert p.population == 0; - for (int isp = nprop.spSet.nextOnBit(0); isp >= 0; isp = nprop.spSet.nextOnBit(isp + 1)) { - SimpleDemographicFunction d = args.dms[isp]; - if (t <= d.upperBound()) { - p.population += d.population(t); - } - } - } - } - } - - pointsList[nodeID.getNumber()] = all; - - return nprop; - } - - private int setDemographics(NodeRef nodeID, int pStart, int side, double[] pops, Points[][] pointsList) { - - final int nSpSeqs = mulspb.nSpSeqs(); - final NodeProperties nprop = props.get(nodeID); - int pEnd; - double p0; - - if (isExternal(nodeID)) { - final int sps = nprop.speciesIndex; - p0 = pops[sps]; - pEnd = pStart; - } else { - assert getChildCount(nodeID) == 2; - - final int iHere = setDemographics(getChild(nodeID, 0), pStart, 0, pops, pointsList); - pEnd = setDemographics(getChild(nodeID, 1), iHere + 1, 1, pops, pointsList); - if (constantPopulation) { - final int i = nSpSeqs + iHere; - p0 = pops[i]; - } else { - final int i = nSpSeqs + iHere * 2; - p0 = pops[i] + pops[i + 1]; - } - } - - if (constantPopulation) { - double[] xs = {}; - double[] ys = {p0}; - - nprop.demogf = new VDdemographicFunction(xs, ys, getUnits()); - // new ConstantPopulation(p0, getUnits()); - } else { - final double t0 = getNodeHeight(nodeID); - - Points[] p = pointsList != null ? pointsList[nodeID.getNumber()] : null; - final int plen = p == null ? 0 : p.length; - - final boolean isRoot = nodeID == getRoot(); -// double[] xs = new double[plen + (isRoot ? 1 : 1)]; -// double[] ys = new double[plen + (isRoot ? 2 : 2)]; - - final boolean useBMP = bmp && pointsList != null; - // internal nodes add one population point for the branch end. - // on the root (with bmp) there is no such point. - final int len = plen + (useBMP ? (!isRoot ? 1 : 0) : 1); - double[] xs = new double[len]; - double[] ys = new double[len + 1]; - boolean[] use = new boolean[len]; - ys[0] = p0; - for (int i = 0; i < plen; ++i) { - xs[i] = p[i].time - t0; - ys[i + 1] = p[i].population; - use[i] = p[i].use; - } - - if (!isRoot) { - final int anccIndex = (side == 0) ? pEnd : pStart - 1; - final double pe = pops[nSpSeqs + anccIndex * 2 + side]; - final double b = getBranchLength(nodeID); - - xs[xs.length - 1] = b; - ys[ys.length - 1] = pe; - } - - if (useBMP) { - nprop.demogf = bestLinearFit(xs, ys, use); - } else { - - if (isRoot) { - // extend the last point to most ancient coalescent point. Has no effect on the demographic - // per se but for use when analyzing the results. - - double h = -1; - for (MulSpeciesBindings.GeneTreeInfo t : mulspb.getGeneTrees()) { - h = Math.max(h, t.tree.getNodeHeight(t.tree.getRoot())); - } - - final double rh = h - t0; - xs[xs.length - 1] = rh; //getNodeHeight(nodeID); - //spTree.setBranchLength(nodeID, rh); - - // last value is for root branch end point - ys[ys.length - 1] = pointsList != null ? ys[ys.length - 2] : - (nonConstRootPopulation ? pops[pops.length - 1] : ys[ys.length - 2]); - } - - nprop.demogf = new VDdemographicFunction(xs, ys, getUnits()); - } - } - return pEnd; - } - - private void setNodeProperties() { - Points[][] perBranchPoints = null; - - if (coalPointsPops != null) { - final Args args = new Args(bmp); - perBranchPoints = new Points[getNodeCount()][]; - getDemographicPoints(getRoot(), args, perBranchPoints); - } else { - // sets species info - getDemographicPoints(getRoot(), null, null); - } - - setDemographics(getRoot(), 0, -1, ((Parameter.Default) sppSplitPopulations).inspectParameterValues(), perBranchPoints); - } - - private Map getProps() { - if (!nodePropsReady) { - setNodeProperties(); - nodePropsReady = true; - } - return props; - } - - public DemographicFunction getNodeDemographic(NodeRef node) { - return getProps().get(node).demogf; - } - - public FixedBitSet spSet(NodeRef node) { - return getProps().get(node).spSet; - } - - public int speciesIndex(NodeRef tip) { - assert isExternal(tip); - - // always ready even if props is dirty - return props.get(tip).speciesIndex; - } - - // grjtodo-oneday: not used because user starting tree not yet supported - private Double setInitialSplitPopulations(FlexibleTree startTree, NodeRef node, int pos[]) { - if (!startTree.isExternal(node)) { - int loc = -1; - for (int nc = 0; nc < startTree.getChildCount(node); ++nc) { - final Double p = setInitialSplitPopulations(startTree, startTree.getChild(node, nc), pos); - if (!constantPopulation && nc == 0) { - loc = pos[0]; - pos[0] += 1; - } - if (p != null) { - if (constantPopulation) { - // - } else { - sppSplitPopulations.setParameterValueQuietly(mulspb.nSpSeqs() + 2 * loc + nc, p); - } - } - } - } - - final String comment = (String) startTree.getNodeAttribute(node, NewickImporter.COMMENT); - Double p0 = null; - if (comment != null) { - StringTokenizer st = new StringTokenizer(comment); - - p0 = Double.parseDouble(st.nextToken()); - if (startTree.isExternal(node)) { - int ns = (Integer) startTree.getNodeAttribute(node, spIndexAttrName); - sppSplitPopulations.setParameterValueQuietly(ns, p0); - } else if (constantPopulation) { - // not tested code !! - sppSplitPopulations.setParameterValueQuietly(mulspb.nSpSeqs() + pos[0], p0); - pos[0] += 1; - } - - // if just one value const - if (st.hasMoreTokens()) { - p0 = Double.parseDouble(st.nextToken()); - } - } - return !constantPopulation ? p0 : null; - } - - private SimpleTree compatibleUninformedSpeciesTree(Tree startTree) { - double rootHeight = Double.MAX_VALUE; - - for (MulSpeciesBindings.GeneTreeInfo t : mulspb.getGeneTrees()) { - rootHeight = Math.min(rootHeight, t.getCoalInfo()[0].ctime); - } - - if (startTree != null) {/* - // Allow start tree to be very basic basic - may be only partially resolved and no - // branch lengths - - if (startTree.getExternalNodeCount() != spp.length) { - throw new Error("Start tree error - different number of tips"); - } - - final FlexibleTree tree = new FlexibleTree(startTree, true); - tree.resolveTree(); - final double treeHeight = tree.getRootHeight(); - if (treeHeight <= 0) { - tree.setRootHeight(1.0); - Utils.correctHeightsForTips(tree); - SimpleTree.Utils.scaleNodeHeights(tree, rootHeight / tree.getRootHeight()); - } - - SimpleTree sTree = new SimpleTree(tree); - for (int ns = 0; ns < spp.length; ns++) { - MulSpeciesBindings.SPinfo sp = spp[ns]; - final int i = sTree.getTaxonIndex(sp.name); - if (i < 0) { - throw new Error(sp.name + " is not present in the start tree"); - } - final SimpleNode node = sTree.getExternalNode(i); - node.setAttribute(spIndexAttrName, ns); - - // set for possible pops - tree.setNodeAttribute(tree.getNode(tree.getTaxonIndex(sp.name)), spIndexAttrName, ns); - } - - if (treeHeight > 0) { - sTree.setAttribute("check", new Double(rootHeight)); - } - - { - //assert ! constantPopulation; // not implemented yet - int[] pos = {0}; - setInitialSplitPopulations(tree, tree.getRoot(), pos); - } - - return sTree;*/ - } - - int nSpSeqs = mulspb.nSpSeqs(); - final double delta = rootHeight / (nSpSeqs + 1); - double cTime = delta; - - List subs = new ArrayList(nSpSeqs); - - for (int ns = 0; ns < nSpSeqs; ns++) { - //Taxon taxon = mulspb.getSpSeq(ns); - final SimpleNode node = new SimpleNode(); - int sp = mulspb.spseqindex2sp(ns); - int seq = mulspb.spseqindex2seq(ns); - String spSeqName = mulspb.apspeciesName(sp) + seq; - node.setTaxon(new Taxon(spSeqName)); - subs.add(node); - - node.setAttribute(spIndexAttrName, ns); - } - - while (subs.size() > 1) { - final SimpleNode node = new SimpleNode(); - int i = 0, j = 1; - node.addChild(subs.get(i)); - node.addChild(subs.get(j)); - node.setHeight(cTime); - cTime += delta; - subs.set(j, node); - subs.remove(i); - } - - return new SimpleTree(subs.get(0)); - } - - public void setPreorderIndices(int[] indices) { - setPreorderIndices(getRoot(), 0, indices); - } - - private int setPreorderIndices(NodeRef node, int loc, int[] indices) { - if (!isExternal(node)) { - int l = setPreorderIndices(getChild(node, 0), loc, indices); - indices[node.getNumber()] = l; - loc = setPreorderIndices(getChild(node, 1), l + 1, indices); - } - return loc; - } - - public String getName() { - return getModelName(); - } - - // grj need to use a different operator - static private MulTreeNodeSlide internalTreeOP = null; - - public int scale(double scaleFactor, int nDims, boolean testBounds) { - assert scaleFactor > 0; - if (nDims <= 0) { - // actually when in an up down with operators on the gene trees the flags - // may indicate a change - //storeState(); // just checks assert really - beginTreeEdit(); - final int count = getInternalNodeCount(); - for (int i = 0; i < count; ++i) { - final NodeRef n = getInternalNode(i); - setNodeHeight(n, getNodeHeight(n) * scaleFactor); - } - endTreeEdit(); - fireModelChanged(this, 1); - return count; - } else { - if (nDims != 1) { - throw new UnsupportedOperationException("not implemented for count != 1"); - } - if (internalTreeOP == null) { - internalTreeOP = new MulTreeNodeSlide(this, mulspb, 1); - } - - internalTreeOP.operateOneNode(scaleFactor); - fireModelChanged(this, 1); - return nDims; - } - } - - @Override - public boolean testBounds() { - return true; - } - - private final boolean verbose = false; - - protected void handleModelChangedEvent(Model model, Object object, int index) { - if (verbose) System.out.println(" SPtree: model changed " + model.getId()); - - nodePropsReady = false; - anyChange = true; - // this should happen by default, no? - fireModelChanged(); - } - - protected final void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) { - if (verbose) System.out.println(" SPtree: parameter changed " + variable.getId()); - - nodePropsReady = false; - anyChange = true; - } - - protected void storeState() { - assert !treeChanged; - assert !anyChange; - } - - protected void restoreState() { - if (verbose) System.out.println(" SPtree: restore (" + treeChanged + "," + anyChange + ")"); - - if (treeChanged) { - // - spTree.beginTreeEdit(); - - for (int k = 0; k < getInternalNodeCount(); ++k) { - final NodeRef node = getInternalNode(k); - final int index = node.getNumber(); - final double h = heights[index]; - if (getNodeHeight(node) != h) { - setNodeHeight(node, h); - } - for (int nc = 0; nc < 2; ++nc) { - final NodeRef child = getChild(node, nc); - - final NodeRef child1 = children[2 * index + nc]; - if (child != child1) { - replaceChild(node, child, child1); - } - assert getParent(child1) == node; - } - } - setRoot(children[children.length - 1]); - - if (verbose) System.out.println(" restored to: " + spTree); - - spTree.endTreeEdit(); - } - if (treeChanged || anyChange) { - setNodeProperties(); - } - treeChanged = false; - anyChange = false; - } - - protected void acceptState() { - if (verbose) System.out.println(" SPtree: accept"); - - treeChanged = false; - anyChange = false; - } - - String previousTopology = null; - - public boolean logNow(long state) { - final String curTop = TreeUtils.uniqueNewick(spTree, spTree.getRoot()); - if (state == 0 || !curTop.equals(previousTopology)) { - previousTopology = curTop; - return true; - } - return false; - } - -// TreeTrait dmf = new TreeTrait.S() { -// public String getTraitName() { -// return "dmf"; -// } -// -// public Intent getIntent() { -// return Intent.NODE; -// } -// -// public String getTrait(Tree tree, NodeRef node) { -// assert tree == SpeciesTreeModel.this; -// -// //final VDdemographicFunction df = getProps().get(node).demogf; -// -// final DemographicFunction df = getNodeDemographic(node); -// return df.toString(); -// } -// }; - - TreeTrait dmt = new TreeTrait.DA() { - public String getTraitName() { - return "dmt"; - } - - public Intent getIntent() { - return Intent.NODE; - } - - public double[] getTrait(Tree tree, NodeRef node) { - assert tree == MulSpeciesTreeModel.this; - - final VDdemographicFunction df = (VDdemographicFunction) getNodeDemographic(node); - return df.times(); - } - }; - - TreeTrait dmv = new TreeTrait.DA() { - public String getTraitName() { - return "dmv"; - } - - public Intent getIntent() { - return Intent.NODE; - } - - public double[] getTrait(Tree tree, NodeRef node) { - assert tree == MulSpeciesTreeModel.this; - - final VDdemographicFunction df = (VDdemographicFunction) getNodeDemographic(node); - return df.values(); - } - }; - - - public TreeTrait[] getTreeTraits() { - return new TreeTrait[]{dmt, dmv}; - } - - public TreeTrait getTreeTrait(String key) { - if (key.equals(dmt.getTraitName())) { - return dmt; - } else if (key.equals(dmv.getTraitName())) { - return dmv; - } - throw new IllegalArgumentException(); - } - - - // boring delegation - - public SimpleTree getSimpleTree() { - return spTree; - } - - public Tree getCopy() { - return spTree.getCopy(); - } - - public Type getUnits() { - return spTree.getUnits(); - } - - public void setUnits(Type units) { - spTree.setUnits(units); - } - - public int getNodeCount() { - return spTree.getNodeCount(); - } - - public boolean hasNodeHeights() { - return spTree.hasNodeHeights(); - } - - public double getNodeHeight(NodeRef node) { - return spTree.getNodeHeight(node); - } - - public double getNodeRate(NodeRef node) { - return spTree.getNodeRate(node); - } - - public Taxon getNodeTaxon(NodeRef node) { - return spTree.getNodeTaxon(node); - } - - public int getChildCount(NodeRef node) { - return spTree.getChildCount(node); - } - - public boolean isExternal(NodeRef node) { - return spTree.isExternal(node); - } - - public boolean isRoot(NodeRef node) { - return spTree.isRoot(node); - } - - public NodeRef getChild(NodeRef node, int i) { - return spTree.getChild(node, i); - } - - public NodeRef getParent(NodeRef node) { - return spTree.getParent(node); - } - - public boolean hasBranchLengths() { - return spTree.hasBranchLengths(); - } - - public double getBranchLength(NodeRef node) { - return spTree.getBranchLength(node); - } - - public void setBranchLength(NodeRef node, double length) { - spTree.setBranchLength(node, length); - } - - public NodeRef getExternalNode(int i) { - return spTree.getExternalNode(i); - } - - public NodeRef getInternalNode(int i) { - return spTree.getInternalNode(i); - } - - public NodeRef getNode(int i) { - return spTree.getNode(i); - } - - public int getExternalNodeCount() { - return spTree.getExternalNodeCount(); - } - - public int getInternalNodeCount() { - return spTree.getInternalNodeCount(); - } - - public NodeRef getRoot() { - return spTree.getRoot(); - } - - public void setRoot(NodeRef r) { - spTree.setRoot(r); - } - - public void addChild(NodeRef p, NodeRef c) { - spTree.addChild(p, c); - } - - public void removeChild(NodeRef p, NodeRef c) { - spTree.removeChild(p, c); - } - - public void replaceChild(NodeRef node, NodeRef child, NodeRef newChild) { - spTree.replaceChild(node, child, newChild); - } - - public boolean beginTreeEdit() { - boolean beingEdited = spTree.beginTreeEdit(); - if (!beingEdited) { - // save tree for restore - for (int n = 0; n < getInternalNodeCount(); ++n) { - final NodeRef node = getInternalNode(n); - final int k = node.getNumber(); - children[2 * k] = getChild(node, 0); - children[2 * k + 1] = getChild(node, 1); - heights[k] = getNodeHeight(node); - } - children[children.length - 1] = getRoot(); - - treeChanged = true; - nodePropsReady = false; - //anyChange = true; - } - return beingEdited; - } - - public void endTreeEdit() { - spTree.endTreeEdit(); - fireModelChanged(); - } - - public void setNodeHeight(NodeRef n, double height) { - spTree.setNodeHeight(n, height); - } - - public void setNodeRate(NodeRef n, double rate) { - spTree.setNodeRate(n, rate); - } - - public void setNodeAttribute(NodeRef node, String name, Object value) { - spTree.setNodeAttribute(node, name, value); - } - - public Object getNodeAttribute(NodeRef node, String name) { - return spTree.getNodeAttribute(node, name); - } - - public Iterator getNodeAttributeNames(NodeRef node) { - return spTree.getNodeAttributeNames(node); - } - - public int getTaxonCount() { - return spTree.getTaxonCount(); - } - - public Taxon getTaxon(int taxonIndex) { - return spTree.getTaxon(taxonIndex); - } - - public String getTaxonId(int taxonIndex) { - return spTree.getTaxonId(taxonIndex); - } - - public int getTaxonIndex(String id) { - return spTree.getTaxonIndex(id); - } - - public int getTaxonIndex(Taxon taxon) { - // can't compare taxa - return getTaxonIndex(taxon.getId()); - } - - public List asList() { - return spTree.asList(); - } - - public Iterator iterator() { - return spTree.iterator(); - } - - public Object getTaxonAttribute(int taxonIndex, String name) { - return spTree.getTaxonAttribute(taxonIndex, name); - } - - public int addTaxon(Taxon taxon) { - return spTree.addTaxon(taxon); - } - - public boolean removeTaxon(Taxon taxon) { - return spTree.removeTaxon(taxon); - } - - public void setTaxonId(int taxonIndex, String id) { - spTree.setTaxonId(taxonIndex, id); - } - - public void setTaxonAttribute(int taxonIndex, String name, Object value) { - spTree.setTaxonAttribute(taxonIndex, name, value); - } - - public String getId() { - return spTree.getId(); - } - - public void setId(String id) { - spTree.setId(id); - } - - public void setAttribute(String name, Object value) { - spTree.setAttribute(name, value); - } - - public Object getAttribute(String name) { - return spTree.getAttribute(name); - } - - public Iterator getAttributeNames() { - return spTree.getAttributeNames(); - } - - public void addMutableTreeListener(MutableTreeListener listener) { - spTree.addMutableTreeListener(listener); - } - - public void addMutableTaxonListListener(MutableTaxonListListener listener) { - spTree.addMutableTaxonListListener(listener); - } - - public static Parameter createCoalPointsPopParameter(MulSpeciesBindings spb, Double value, Boolean bmp) { - int dim = 0; - for (double[] d : spb.getPopTimesSingle()) { - dim += d.length; - } - - if (!bmp) { - for (double[] d : spb.getPopTimesPair()) { - dim += d.length; - } - } - - return new Parameter.Default(dim, value); - } - - public static Parameter createSplitPopulationsParameter(MulSpeciesBindings spb, double value, boolean root, boolean constPop) { - int dim; - if (constPop) { - // one per node - dim = 2 * spb.nSpSeqs() - 1; - } else { - // one per species leaf (ns) + 2 per internal node (2*(ns-1)) + optionally one for the root - dim = 3 * spb.nSpSeqs() - 2 + (root ? 1 : 0); - } - return new Parameter.Default(dim, value); - } - - @Override - public Citation.Category getCategory() { - return Citation.Category.SPECIES_MODELS; - } - - @Override - public String getDescription() { - return "Multiply labelled species tree"; - } - - public List getCitations() { - return Arrays.asList( - new Citation( - new Author[]{ - new Author("GR", "Jones") - }, - Citation.Status.IN_PREPARATION - )); - } - -} diff --git a/src/dr/evomodel/alloppnet/speciation/MulSpeciesTreePrior.java b/src/dr/evomodel/alloppnet/speciation/MulSpeciesTreePrior.java deleted file mode 100644 index 83b154a3c0..0000000000 --- a/src/dr/evomodel/alloppnet/speciation/MulSpeciesTreePrior.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * MulSpeciesTreePrior.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -/** - * - * @author Graham Jones - * Date: 21/12/2011 - */ - -package dr.evomodel.alloppnet.speciation; - -import dr.evomodel.speciation.SpeciationModel; -import dr.inference.model.Likelihood; - - - -public class MulSpeciesTreePrior extends Likelihood.Abstract { - MulSpeciesTreeModel mulsptree; - SpeciationModel prior; - - public MulSpeciesTreePrior(SpeciationModel prior, MulSpeciesTreeModel mulsptree) { - super(prior); - this.mulsptree = mulsptree; - this.prior = prior; - } - - - @Override - protected boolean getLikelihoodKnown() { - return false; - } - - - - @Override - protected double calculateLogLikelihood() { - double lhood = prior.calculateTreeLogLikelihood(mulsptree); - return lhood; - } -} diff --git a/src/dr/evomodel/alloppnet/tree/SlidableTree.java b/src/dr/evomodel/alloppnet/tree/SlidableTree.java deleted file mode 100644 index 36041d4465..0000000000 --- a/src/dr/evomodel/alloppnet/tree/SlidableTree.java +++ /dev/null @@ -1,182 +0,0 @@ - -/* - * SlidableTree.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.alloppnet.tree; - -import dr.evolution.tree.NodeRef; -import dr.evolution.util.Taxon; -import dr.math.MathUtils; - -/** - * Interface for a binary tree which can support a Mau-et-al MCMC move - * in which node heights `slide' and can change topology. - * - * @author Graham Jones - * Date 2012-03-30 - * - */ - -/* -The aim is to simplify code by not having to use a MutableTree with its long list of -methods. The users of SlidableTree are - -1. AlloppLeggedTree, for moves within tetraploid subtrees. - -2. AlloppDiploidHistory. A SimpleTree is made for testing purposes. - -3. PopsIOSpeciesTreeModel. Needs to be a Tree for logging. So I -make and update a SimpleTree and delegate to that. - -4. MulSpeciesTreeModel does not use it yet, but could do. Currently a MutableTree and -uses near-copy of JH's code for MCMC moves. Same issue as PopsIOSpeciesTreeModel if use -SlidableTree. - -It uses NodeRefs cause that's what SimpleTree uses. This means that clients have -to implement get/setNumber when they have no use for node numbers. - - */ - - -public interface SlidableTree { - - NodeRef getSlidableRoot(); - - int getSlidableNodeCount(); - - Taxon getSlidableNodeTaxon(NodeRef node); - - double getSlidableNodeHeight(NodeRef node); - - void setSlidableNodeHeight(NodeRef node, double height); - - boolean isExternalSlidable(NodeRef node); - - NodeRef getSlidableChild(NodeRef node, int i); - - void replaceSlidableChildren(NodeRef node, NodeRef lft, NodeRef rgt); - - void replaceSlidableRoot(NodeRef root); - - - public class Utils { - - /* - * This is an implementation of the ideas of - * - * Bayesian Phylogenetic Inference via Markov Chain Monte Carlo Methods - * Bob Mau, Michael A. Newton, Bret Larget - * Biometrics, Vol. 55, No. 1 (Mar., 1999), pp. 1-12 - * - * similar to implementation by Joseph Heled in TreeNodeSlide. - * This version works on a SlidableTree rather than a SimpleTree and is - * simpler than JH's version. It does not keep track of what was swapped. - * Instead I assign popvalues to nodes via an ordering of species (see - * fillinpopvals() in network). - */ - - - /* - * For Mau-Newton-Larget MCMC moves on tree. - * Do this, then change a node height, then call mnlReconstruct() - * - */ - static public NodeRef[] mnlCanonical(SlidableTree tree) { - final int count = tree.getSlidableNodeCount(); - NodeRef[] order = new NodeRef[count]; - mnlCanonicalSub(tree, tree.getSlidableRoot(), 0, order); - return order; - } - - - /* - * For Mau-etal MCMC moves on tree - */ - static public void mnlReconstruct(SlidableTree tree, NodeRef[] order) { - final NodeRef root = mnlReconstructSub(tree, 0, (order.length - 1) / 2, order); - tree.replaceSlidableRoot(root); - } - - - /* - * ****************** private methods ********************** - */ - - - static private int mnlCanonicalSub(SlidableTree tree, NodeRef node, - int nextloc, NodeRef[] order) { - if( tree.isExternalSlidable(node) ) { - order[nextloc] = node; assert (nextloc & 0x1) == 0; - nextloc++; - return nextloc; - } - final boolean swap = MathUtils.nextBoolean(); - nextloc = mnlCanonicalSub(tree, tree.getSlidableChild(node, swap ? 1 : 0), nextloc, order); - order[nextloc] = node; assert (nextloc & 0x1) == 1; - nextloc++; - nextloc = mnlCanonicalSub(tree, tree.getSlidableChild(node, swap ? 0 : 1), nextloc, order); - return nextloc; - } - - - - static private NodeRef mnlReconstructSub(SlidableTree tree, int from, int to, - NodeRef[] order) { - if (from == to) { - return order[2*from]; - } - int rootIndex = highestNode(tree, order, from, to); - NodeRef root = order[2 * rootIndex + 1]; - NodeRef lft = mnlReconstructSub(tree, from, rootIndex, order); - NodeRef rgt = mnlReconstructSub(tree, rootIndex+1, to, order); - tree.replaceSlidableChildren(root, lft, rgt); - return root; - } - - - - - - - static private int highestNode(SlidableTree tree, NodeRef[] order, int from, int to) { - int rootIndex = -1; - double maxh = -1.0; - - for (int i = from; i < to; ++i) { - final double h = tree.getSlidableNodeHeight(order[2 * i + 1]); - if (h > maxh) { - maxh = h; - rootIndex = i; - } - } - return rootIndex; - } - - - - } -} diff --git a/src/dr/evomodel/alloppnet/util/AlloppMisc.java b/src/dr/evomodel/alloppnet/util/AlloppMisc.java deleted file mode 100644 index 1842ef2400..0000000000 --- a/src/dr/evomodel/alloppnet/util/AlloppMisc.java +++ /dev/null @@ -1,167 +0,0 @@ -/* - * AlloppMisc.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.alloppnet.util; - -import java.util.Formatter; -import java.util.Iterator; - -/** - * - * @author Graham Jones - * Date: 01/07/2011 - */ - -import java.util.Locale; - -import dr.evolution.tree.NodeRef; -import dr.evolution.tree.SimpleTree; -import dr.evolution.util.Taxon; -import dr.math.MathUtils; - -import jebl.util.FixedBitSet; - -public class AlloppMisc { - - - public static String FixedBitSetasText(FixedBitSet x) { - if (x == null) { - return "{?}"; - } - StringBuilder rep = new StringBuilder(); - rep.append("{"); - for (int b = 0; b < x.cardinality() + FixedBitSet.complement(x).cardinality(); ++b) { - String comma = (b==0) ? "" : ","; - if (x.contains(b)) { - rep.append(comma + b); - } else { - rep.append(comma + " "); - } - } - rep.append("}"); - return rep.toString(); - } - - - - public static String nonnegIn8Chars(double x) - { - StringBuilder s = new StringBuilder(); - Formatter formatter = new Formatter(s, Locale.US); - if (x < 0) { - formatter.format("%8s", "NA"); - } else if (x == 0.0) { - formatter.format("%8s", "zero"); - } else if (x < 1e-3) { - formatter.format("%8.2e", x); - } else if (x < 9.999) { - formatter.format("%8.5f", x); - } else if (x < 99.99) { - formatter.format("%8.4f", x); - } else if (x < 999.9) { - formatter.format("%8.3f", x); - } else if (x < 9999) { - formatter.format("%8.2f", x); - } else { - formatter.format("%8.0f", x); - } - return s.toString(); - } - - - public static String nonnegIntIn2Chars(int x) - { - StringBuilder s = new StringBuilder(); - Formatter formatter = new Formatter(s, Locale.US); - if (x < 0) { - formatter.format("%2s", "NA"); - } else { - formatter.format("%2d", x); - } - return s.toString(); - } - - - public static String SimpleNodeAsText(SimpleTree stree, NodeRef node) { - String s = "" + node.getNumber() + " "; - while (s.length() < 3) { s += " "; } - int nch = stree.getChildCount(node); - if (nch> 0) { - assert(nch==2); - s += stree.getChild(node, 0).getNumber(); - while (s.length() < 6) { s += " "; } - s += stree.getChild(node, 1).getNumber(); - } - while (s.length() < 9) { s += " "; } - Taxon tx = stree.getNodeTaxon(node); - String taxonid = "*"; - if (tx != null) { - taxonid = tx.getId(); - if (taxonid == null || taxonid.length() == 0) { - taxonid = "*"; - } - - } - s += taxonid; - while (s.length() < 20) { s += " "; } - - stree.getNodeHeight(node); - s += " height="; - s += stree.getNodeHeight(node); - Iterator iter = stree.getNodeAttributeNames(node); - if (iter != null) { - while (iter.hasNext()) { - String name = (String) iter.next(); - s += " "; - s += name; - s += "="; - s += stree.getNodeAttribute(node, name); - } - } - return s; - } - - - - - - public static double uniformInRange(double oldx, double min, double max, double halfwidth) { - assert halfwidth > 0.0; - assert halfwidth < 0.5; - assert min < max; - double change = MathUtils.uniform(-1.0, 1.0) * (max - min) * halfwidth; - double newx = oldx + change; - if (newx < min) { newx = 2*min - newx; } - if (newx > max) { newx = 2*max - newx; } - assert newx > min; - assert newx < max; - return newx; - } - -} - - diff --git a/src/dr/evomodel/arg/ARGDistinctTreeCountStatistic.java b/src/dr/evomodel/arg/ARGDistinctTreeCountStatistic.java deleted file mode 100644 index 5d867984a7..0000000000 --- a/src/dr/evomodel/arg/ARGDistinctTreeCountStatistic.java +++ /dev/null @@ -1,189 +0,0 @@ -/* - * ARGDistinctTreeCountStatistic.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.arg; - -import java.util.ArrayList; -import java.util.Collections; - -import dr.inference.model.Statistic; -import dr.xml.AbstractXMLObjectParser; -import dr.xml.ElementRule; -import dr.xml.XMLObject; -import dr.xml.XMLObjectParser; -import dr.xml.XMLParseException; -import dr.xml.XMLSyntaxRule; - - -public class ARGDistinctTreeCountStatistic extends Statistic.Abstract{ - - public static final String ARG_TREE_COUNT = "argTreeCount"; - public static final String PRINT_TREES = "printTrees"; - - private ARGModel arg; - private int numberOfPartitions; - - public ARGDistinctTreeCountStatistic(ARGModel arg){ - this.arg = arg; - numberOfPartitions = arg.getNumberOfPartitions(); - } - - public int getDimension() { - - return 1; - } - - - public double getStatisticValue(int dim){ - ArrayList listOfTrees = new ArrayList(numberOfPartitions/10); - - for(int i = 0; i < numberOfPartitions; i++){ - ARGTree tree = new ARGTree(arg,i); - - String newick = tree.getUniqueNewick(); - - - - if(!listOfTrees.contains(newick)){ - listOfTrees.add(newick); - - } - } - - - - - return listOfTrees.size(); - } - - private class DistinctTreeCount implements Comparable{ - private final String tree; - private int count; - - public DistinctTreeCount(String tree, int count){ - this.tree = tree; - this.count = count; - } - - public void increaseCount(){ - count++; - } - - public int compareTo(DistinctTreeCount o) { - if(this.tree.equals(o.tree)){ - return 0; - }else if(this.count < o.count){ - return 1; - } - return -1; - } - - public boolean equals(Object o){ - try{ - DistinctTreeCount dtc = (DistinctTreeCount)o; - - if(dtc.compareTo(this) == 0){ - return true; - } - return false; - }catch(ClassCastException e){ - return false; - } - - } - - public String toString(){ - return tree + " " + count; - } - - - - - }; - - - - public String getFullOutput(){ - ArrayList listOfTrees = new ArrayList(numberOfPartitions); - ArrayList numbers = new ArrayList(numberOfPartitions); - - for(int i = 0; i < numberOfPartitions; i++){ - ARGTree tree = new ARGTree(arg,i); - - String newick = tree.getUniqueNewick(); - if(!listOfTrees.contains(newick)){ - listOfTrees.add(newick); - numbers.add(1); - }else{ - int index = listOfTrees.indexOf(newick); - numbers.set(index, numbers.get(index) + 1); - } - } - - ArrayList trees = new ArrayList(numberOfPartitions); - - for(int i = 0; i < listOfTrees.size(); i++){ - trees.add(new DistinctTreeCount(listOfTrees.get(i),numbers.get(i))); - } - - Collections.sort(trees); - - return trees.toString(); - } - - public static XMLObjectParser PARSER = new AbstractXMLObjectParser(){ - - public String getParserDescription() { - - return "Provides number of distinct loci trees"; - } - - public Class getReturnType() { - return ARGDistinctTreeCountStatistic.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return new XMLSyntaxRule[]{ - new ElementRule(ARGModel.class), - }; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - ARGModel arg = (ARGModel) xo.getChild(ARGModel.class); - - return new ARGDistinctTreeCountStatistic(arg); - } - - public String getParserName() { - return ARG_TREE_COUNT; - } - - }; - - - -} diff --git a/src/dr/evomodel/arg/ARGLogger.java b/src/dr/evomodel/arg/ARGLogger.java deleted file mode 100644 index 78f6965b87..0000000000 --- a/src/dr/evomodel/arg/ARGLogger.java +++ /dev/null @@ -1,286 +0,0 @@ -/* - * ARGLogger.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.arg; - -import dr.evoxml.util.GraphMLUtils; -import dr.inference.loggers.LogFormatter; -import dr.inference.loggers.MCLogger; -import dr.inference.loggers.MLLogger; -import dr.inference.loggers.TabDelimitedFormatter; -import dr.xml.*; -import org.jdom.Element; -import org.jdom.output.XMLOutputter; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.PrintWriter; -import java.util.logging.Logger; - -/** - * Created by IntelliJ IDEA. - * User: msuchard - * Date: Jan 13, 2007 - * Time: 2:16:08 PM - * To change this template use File | Settings | File Templates. - */ -public class ARGLogger extends MCLogger { - - public static final String LOG_ARG = "logArg"; - public static final String DOT_FORMAT = "dotFormat"; - public static final String COMPRESSED_STRING = "compressedString"; - public static final String EXTENDED_NEWICK = "extendedNewick"; - public static final String STRIPPED_NEWICK = "strippedNewick"; - public static final String FULL_STRING = "fullString"; - public static final String DISTINCT_TREES = "distinctTrees"; - public static final String FORMAT = "format"; - - // The following were in MCLogger; where did they go? - public static final String LOG = "log"; - public static final String ECHO = "echo"; - public static final String ECHO_EVERY = "echoEvery"; - public static final String TITLE = "title"; - public static final String FILE_NAME = "fileName"; - // public static final String FORMAT = "format"; - public static final String TAB = "tab"; - public static final String HTML = "html"; - public static final String PRETTY = "pretty"; - public static final String LOG_EVERY = "logEvery"; - - public static final String COLUMNS = "columns"; - public static final String COLUMN = "column"; - public static final String LABEL = "label"; - public static final String SIGNIFICANT_FIGURES = "sf"; - public static final String DECIMAL_PLACES = "dp"; - public static final String WIDTH = "width"; - - - private ARGModel argModel; - private String formatType; - - private ARGDistinctTreeCountStatistic treeStat; - - public ARGLogger(ARGModel argModel, LogFormatter formatter, int logEvery, String formatType) { - super(formatter, logEvery, false); - this.argModel = argModel; - this.formatType = formatType; - - if(formatType.equals(DISTINCT_TREES)){ - treeStat = new ARGDistinctTreeCountStatistic(argModel); - } - } - - - public static final String GRAPHML_HEADER = "\n"; - public static final String GRAPHML_FOOTER = ""; - - public void startLogging() { - if (formatType.equals(EXTENDED_NEWICK)) { - logLine("stateARG.string"); - } else if (formatType.equals(STRIPPED_NEWICK)) { - logLine("StrippedARGString"); - } else { - logLine(GRAPHML_HEADER); - } -// if (!dotFormat && !newickFormat) -// logLine(GRAPHML_HEADER); -// if (newickFormat) -// logLine("state ARG.string"); - } - - public void stopLogging() { - if (!formatType.equals(EXTENDED_NEWICK) && !formatType.equals(STRIPPED_NEWICK)) { - logLine(GRAPHML_FOOTER); - } -// if (!dotFormat && !newickFormat) -// logLine(GRAPHML_FOOTER); - } - - static XMLOutputter outputter = new XMLOutputter(org.jdom.output.Format.getPrettyFormat()); - - public void log(long state) { - if (logEvery <= 0 || ((state % logEvery) == 0)) { - Element graphElement = argModel.toXML(); - graphElement.setAttribute(ARGModel.ID_ATTRIBUTE, "STATE_" + state); - if (formatType.equals(DOT_FORMAT)) - logLine(GraphMLUtils.dotFormat(graphElement)); - else if (formatType.equals(COMPRESSED_STRING)) - logLine("ARG STATE_" + state + " = " + argModel.toGraphStringCompressed(false)); - else if (formatType.equals(FULL_STRING)) - logLine(outputter.outputString(graphElement)); - else if (formatType.equals(EXTENDED_NEWICK)) - logLine(argModel.toExtendedNewick()); - else if (formatType.equals(DISTINCT_TREES)) - logLine(treeStat.getStatisticValue(0) + "\t" + treeStat.getFullOutput()); - else - logLine(argModel.toStrippedNewick()); - } -// logLine("ARG STATE_" + state + " = " + argModel.toExtendedNewick()); - } - - - public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { - - public String getParserName() { - return LOG_ARG; - } - - /** - * @return an object based on the XML element it was passed. - */ - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - ARGModel argModel = (ARGModel) xo.getChild(ARGModel.class); - - String fileName = null; - String title = null; - String argModelLoggerFormat = null; -// boolean dotFormat = false; -// boolean newickFormat = false; -// boolean nexusFormat = false; -// -// String colouringLabel = "demes"; -// String rateLabel = "rate"; -// String likelihoodLabel = "lnP"; - - if (xo.hasAttribute(TITLE)) { - title = xo.getStringAttribute(TITLE); - } - - if (xo.hasAttribute(FILE_NAME)) { - fileName = xo.getStringAttribute(FILE_NAME); - } - - if (xo.hasAttribute(FORMAT)) { - argModelLoggerFormat = xo.getStringAttribute(FORMAT); - } - -// boolean substitutions = false; -// if (xo.hasAttribute(BRANCH_LENGTHS)) { -// substitutions = xo.getStringAttribute(BRANCH_LENGTHS).equals(SUBSTITUTIONS); -// } - -// BranchRateModel branchRateModel = (BranchRateModel) xo.getChild(BranchRateModel.class); - -// ColourSamplerModel colourSamplerModel = (ColourSamplerModel) xo.getChild(ColourSamplerModel.class); - -// Likelihood likelihood = (Likelihood) xo.getChild(Likelihood.class); - - // logEvery of zero only displays at the end - int logEvery = 1; - - if (xo.hasAttribute(LOG_EVERY)) { - logEvery = xo.getIntegerAttribute(LOG_EVERY); - } - - PrintWriter pw; - - if (fileName != null) { - - try { - File file = new File(fileName); - String name = file.getName(); - String parent = file.getParent(); - - if (!file.isAbsolute()) { - parent = System.getProperty("user.dir"); - } - -// System.out.println("Writing log file to "+parent+System.getProperty("path.separator")+name); - pw = new PrintWriter(new FileOutputStream(new File(parent, name))); - } catch (FileNotFoundException fnfe) { - throw new XMLParseException("File '" + fileName + "' can not be opened for " + getParserName() + " element."); - } - } else { - pw = new PrintWriter(System.out); - } - - LogFormatter formatter = new TabDelimitedFormatter(pw); - - Logger.getLogger("dr.evomodel").info("Creating " + LOG_ARG + " of type " + argModelLoggerFormat); - - ARGLogger logger = new ARGLogger(argModel, formatter, logEvery, argModelLoggerFormat); - -// TreeLogger logger = new TreeLogger(tree, branchRateModel, rateLabel, -// colourSamplerModel, colouringLabel, likelihood, likelihoodLabel, -// formatter, logEvery, nexusFormat, substitutions); - - if (title != null) { - logger.setTitle(title); - } - - return logger; - } - - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - String[] validFormats = {DOT_FORMAT, EXTENDED_NEWICK, - COMPRESSED_STRING, FULL_STRING, STRIPPED_NEWICK, DISTINCT_TREES}; - - private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{ - - AttributeRule.newIntegerRule(LOG_EVERY), - new StringAttributeRule(FORMAT, "The type logger's output type", - validFormats, false), - new StringAttributeRule(FILE_NAME, - "The name of the file to send log output to. " + - "If no file name is specified then log is sent to standard output", true), - new StringAttributeRule(TITLE, "The title of the log", true), -// AttributeRule.newBooleanRule(NEXUS_FORMAT, true, -// "Whether to use the NEXUS format for the tree log"), -// new StringAttributeRule(BRANCH_LENGTHS, "What units should the branch lengths be in", new String[]{TIME, SUBSTITUTIONS}, true), - new ElementRule(ARGModel.class, "The ARG which is to be logged"), -// new ElementRule(BranchRateModel.class, true), -// new ElementRule(ColourSamplerModel.class, true), -// new ElementRule(Likelihood.class, true) - }; - - public String getParserDescription() { - return "Logs an ARG to a file"; - } - - public String getExample() { - return - "\n" + - "<" + getParserName() + " " + LOG_EVERY + "=\"100\" " + FILE_NAME + "=\"log.args\">\n" + - " \n" + - "\n"; - } - - public Class getReturnType() { - return MLLogger.class; - } - }; - - -} diff --git a/src/dr/evomodel/arg/ARGModel.java b/src/dr/evomodel/arg/ARGModel.java deleted file mode 100755 index b62b0edc92..0000000000 --- a/src/dr/evomodel/arg/ARGModel.java +++ /dev/null @@ -1,4432 +0,0 @@ -/* - * ARGModel.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -/* - * ARGModel.java - * - * (c) 2002-2005 BEAST Development Core Team - * - * This package may be distributed under the - * Lesser Gnu Public Licence (LGPL) - */ - -package dr.evomodel.arg; - -import dr.evolution.tree.*; -import dr.evolution.util.MutableTaxonListListener; -import dr.evolution.util.Taxon; -import dr.evomodel.arg.likelihood.ARGLikelihood; -import dr.evomodel.tree.NewTreeModel; -import dr.evomodel.tree.TreeChangedEvent; -import dr.evomodelxml.tree.TreeModelParser; -import dr.inference.loggers.LogColumn; -import dr.inference.loggers.Loggable; -import dr.inference.loggers.NumberColumn; -import dr.inference.model.*; -import dr.inference.parallel.MPIServices; -import dr.math.MathUtils; -import dr.util.Attributable; -import dr.util.NumberFormatter; -import dr.xml.*; -import org.jdom.Document; -import org.jdom.Element; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.StringTokenizer; -import java.util.logging.Logger; - -/** - * A model component for trees. - * - * @author Marc A. Suchard - * @author Eric Bloomquist - */ -public class ARGModel extends AbstractModel implements MutableTree, Loggable { - - - public static final String TREE_MODEL = "argTreeModel"; - public static final String ROOT_HEIGHT = TreeModelParser.ROOT_HEIGHT; - public static final String LEAF_HEIGHT = "leafHeight"; - public static final String NODE_HEIGHTS = "nodeHeights"; - public static final String NODE_RATES = TreeModelParser.NODE_RATES; - public static final String NODE_TRAITS = TreeModelParser.NODE_TRAITS; - public static final String ROOT_NODE = "rootNode"; - public static final String INTERNAL_NODES = "internalNodes"; - public static final String LEAF_NODES = "leafNodes"; - public static final String TAXON = "taxon"; - public static final String GRAPH_ELEMENT = "graph"; - public static final String NODE_ELEMENT = "node"; - public static final String EDGE_ELEMENT = "edge"; - public static final String ID_ATTRIBUTE = XMLParser.ID; - public static final String EDGE_FROM = "source"; - public static final String EDGE_TO = "target"; - public static final String TAXON_NAME = "taxonName"; - public static final String EDGE_LENGTH = "len"; - public static final String EDGE_PARTITIONS = "edgePartitions"; - public static final String IS_TIP = "isTip"; - public static final String IS_ROOT = "isRoot"; - public static final String LEFT_PARENT = "leftParent"; - public static final String RIGHT_PARENT = "rightParent"; - public static final String LEFT_CHILD = "leftChild"; - public static final String RIGHT_CHILD = "rightChild"; - public static final String NODE_HEIGHT = "nodeHeight"; - public static final String IS_REASSORTMENT = "true"; - public static final String NUM_PARTITIONS = "numberOfPartitions"; - public static final String GRAPH_SIZE = "size=\"6,6\""; - public static final String DOT_EDGE_DEF = "edge[style=\"setlinewidth(2)\",arrowhead=none]"; - public static final String DOT_NODE_DEF = "node[shape=plaintext,width=auto,fontname=Helvitica,fontsize=10]"; - - public static final int LEFT = 0; - public static final int RIGHT = 1; - - public static final String PARTITION_TYPE = "partitionType"; - public static final String REASSORTMENT_PARTITION = "reassortment"; - public static final String RECOMBINATION_PARTITION = "recombination"; - public static final String PARTITION_DEFAULT_TYPE = REASSORTMENT_PARTITION; - - // *********************************************************************** - // Private members - // *********************************************************************** - - protected int storedRootNumber; - protected int nodeCount; - protected int storedNodeCount; - protected int externalNodeCount; - protected int internalNodeCount; - protected int storedInternalNodeCount; - protected boolean inEdit = false; - - protected Node root = null; - public ArrayList nodes = null; - public ArrayList storedNodes = null; - protected Parameter[] addedParameters = null; - protected Parameter[] removedParameters = null; - protected Parameter addedPartitioningParameter = null; - protected Parameter removedPartitioningParameter = null; - protected CompoundParameter partitioningParameters; - protected CompoundParameter storedInternalNodeHeights; - protected CompoundParameter storedInternalAndRootNodeHeights; - protected CompoundParameter storedNodeRates; - protected Node[] addedNodes = null; - protected Node[] removedNodes = null; - - // private int units = SUBSTITUTIONS; - private Type units; - private boolean hasRates = false; - private boolean hasTraits = false; - private int nullCounter = 0; - private int storedNullCounter; - - protected String partitionType = PARTITION_DEFAULT_TYPE; - - - public ARGModel(ArrayList nodes, Node root, int numberPartitions, - int externalNodeCount) { - super(TREE_MODEL); - this.nodes = nodes; - this.root = root; - this.maxNumberOfPartitions = numberPartitions; - this.externalNodeCount = externalNodeCount; - if (nodes != null) - this.nodeCount = nodes.size(); - this.internalNodeCount = this.nodeCount - externalNodeCount; - } - - public ARGModel(Tree tree) { - - super(TREE_MODEL); - // System.err.println("constructor for TreeModel"); - partitioningParameters = new CompoundParameter("partitioning"); - // initialize(tree); - // } - - // protected void initialize(Tree tree) { - // System.err.println("init for TreeModel"); - // System.exit(-1); - // get a rooted version of the tree to clone - FlexibleTree binaryTree = new FlexibleTree(tree); - binaryTree.resolveTree(); - - // clone the node structure (this will create the individual parameters - Node node = new Node(binaryTree, binaryTree.getRoot()); - - internalNodeCount = binaryTree.getInternalNodeCount(); - externalNodeCount = binaryTree.getExternalNodeCount(); - - nodeCount = internalNodeCount + externalNodeCount; - - // nodes = new Node[nodeCount]; - // storedNodes = new Node[nodeCount]; - nodes = new ArrayList(nodeCount); - storedNodes = new ArrayList(nodeCount); - for (int i = 0; i < nodeCount; i++) { - nodes.add(null); - storedNodes.add(null); - } - int i = 0; - int j = externalNodeCount; - - root = node; - - // System.err.println("Going to do postOrder"); - - do { - node = (Node) TreeUtils.postorderSuccessor(this, node); - - if (node.isExternal()) { - node.number = i; - - // nodes[i] = node; - // storedNodes[i] = new Node(); - // storedNodes[i].taxon = node.taxon; - // storedNodes[i].number = i; - nodes.set(i, node); - Node copy = new Node(); - copy.taxon = node.taxon; - copy.number = i; - storedNodes.set(i, copy); - - i++; - } else { - node.number = j; - - // nodes[j] = node; - // storedNodes[j] = new Node(); - // storedNodes[j].number = j; - nodes.set(j, node); - Node copy = new Node(); - copy.number = j; - storedNodes.set(j, copy); - - j++; - } - } while (node != root); - - // System.err.println("Succeed in post-order"); - - // ARGTree t = new ARGTree(this,0); - // System.err.println(Tree.Utils.uniqueNewick(t, t.getRoot())); - // System.err.println(this.toGraphString()); - // System.exit(-1); - - } - - private double nextTime(int nTaxa, double pSize, double rRate) { - double t = (double) nTaxa; - - double s = t * (t - 1 + rRate) / (2.0 * pSize); - return MathUtils.nextExponential(s); - } - - private boolean nextEventIsBifurcation(int nTaxa, double rRate) { - double a = (double) (nTaxa - 1) / (nTaxa - 1 + rRate); - if (MathUtils.nextDouble() < a) { - return true; - } - return false; - } - - private class SimulateSticks { - public final Node mySon; - public final boolean leftStick; - - public SimulateSticks(Node son, boolean left) { - mySon = son; - leftStick = left; - } - } - - public ARGModel(int ntaxa, double popSize, double rRate) { - super("Simulator"); - - ArrayList currentStickList = new ArrayList(50); - ArrayList currentNodeList = new ArrayList(50); - - nodes = new ArrayList(); - - int nodeNumber = 0; - - for (int i = 0; i < ntaxa; i++) { - Node node = new Node(); - node.heightParameter = new Parameter.Default(0.0); - nodes.add(node); - currentNodeList.add(node); - node.bifurcation = true; - node.number = nodeNumber; - nodeNumber++; - - node.taxon = new Taxon("" + nodeNumber); - SimulateSticks stickGuy = new SimulateSticks(node, true); - currentStickList.add(stickGuy); - } - - double currentHeight = 0; - - while (currentStickList.size() > 1) { - currentHeight = currentHeight + nextTime(currentStickList.size(), popSize, rRate); - - if (nextEventIsBifurcation(currentStickList.size(), rRate)) { - SimulateSticks[] sticks = new SimulateSticks[2]; - - for (int i = 0; i < 2; i++) { - int randomDraw = MathUtils.nextInt(currentStickList.size()); - sticks[i] = currentStickList.get(randomDraw); - currentStickList.remove(randomDraw); - } - - Node node = new Node(); - nodes.add(node); - node.heightParameter = new Parameter.Default(currentHeight); - node.number = nodeNumber; - nodeNumber++; - node.bifurcation = true; - SimulateSticks stickGuy = new SimulateSticks(node, true); - - if (sticks[0].mySon == sticks[1].mySon) { - Node child = sticks[0].mySon; - node.leftChild = child; - node.rightChild = child; - child.rightParent = node; - child.leftParent = node; - - currentNodeList.remove(currentNodeList.indexOf(child)); - currentNodeList.add(node); - currentStickList.add(stickGuy); - } else { - Node child1 = sticks[0].mySon; - Node child2 = sticks[1].mySon; - - node.leftChild = child1; - node.rightChild = child2; - - if (child1.bifurcation) { - child1.leftParent = node; - child1.rightParent = node; - currentNodeList.remove(currentNodeList.indexOf(child1)); - } else { - if (sticks[0].leftStick) { - child1.leftParent = node; - } else { - child1.rightParent = node; - } - if (child1.leftParent != null && child1.rightParent != null) { - currentNodeList.remove(currentNodeList.indexOf(child1)); - } - } - - if (child2.bifurcation) { - child2.leftParent = node; - child2.rightParent = node; - currentNodeList.remove(currentNodeList.indexOf(child2)); - } else { - if (sticks[1].leftStick) { - child2.leftParent = node; - } else { - child2.rightParent = node; - } - if (child2.leftParent != null && child2.rightParent != null) { - currentNodeList.remove(currentNodeList.indexOf(child2)); - } - } - currentNodeList.add(node); - currentStickList.add(stickGuy); - } - } else { - int randomDraw = MathUtils.nextInt(currentStickList.size()); - SimulateSticks stick = currentStickList.get(randomDraw); - currentStickList.remove(randomDraw); - - Node node = new Node(); - nodes.add(node); - node.heightParameter = new Parameter.Default(currentHeight); - node.number = nodeNumber; - nodeNumber++; - node.bifurcation = false; - SimulateSticks leftStickGuy = new SimulateSticks(node, true); - SimulateSticks rightStickGuy = new SimulateSticks(node, false); - - Node child = stick.mySon; - node.leftChild = child; - node.rightChild = child; - - if (child.bifurcation) { - child.leftParent = node; - child.rightParent = node; - currentNodeList.remove(currentNodeList.indexOf(child)); - } else { - if (stick.leftStick) { - child.leftParent = node; - } else { - child.rightParent = node; - } - if (child.leftParent != null & child.rightParent != null) { - currentNodeList.remove(currentNodeList.indexOf(child)); - } - } - - currentNodeList.add(node); - currentStickList.add(leftStickGuy); - currentStickList.add(rightStickGuy); - } - - } - - root = currentNodeList.get(0); - - //nodeNumber--; - - // nodes = new Node[nodeNumber]; - - - } - - - public int possibleInternalNodePermuations() { - - int max = getInternalNodeCount(); - ArrayList remainingHeights = new ArrayList(max - 1); - - for (Node node : nodes) { - if (!node.isExternal() && !node.isRoot()) - remainingHeights.add(node.getHeight()); - } - - int firstNode = 0; - while (nodes.get(firstNode).isExternal() || nodes.get(firstNode).isRoot()) - firstNode++; - - int result = possibleInternalNodePermutations(firstNode, remainingHeights); - - // Restore heights - int i = 0; - for (Node node : nodes) { - if (!node.isExternal() && !node.isRoot()) { - node.setHeight(remainingHeights.get(i++)); - } - } - - return factorial(max - 1) - result; - } - - private int factorial(int x) { - int result = 1; - for (int i = 2; i <= x; i++) - result *= i; - return result; - } - - - private int possibleInternalNodePermutations(int nodeNumber, ArrayList remainingHeights) { - - int total = 0; - - if (remainingHeights.size() == 0) { - return 0; - } - - int newNodeNumber = nodeNumber + 1; - if (remainingHeights.size() > 1) { - while (nodes.get(newNodeNumber).isExternal() || nodes.get(newNodeNumber).isRoot()) - newNodeNumber++; - } - - Node nr = nodes.get(nodeNumber); - - for (double height : remainingHeights) { - - if (height < getNodeHeight(getParent(nr, 0)) && - height < getNodeHeight(getParent(nr, 1))) { - setNodeHeight(nr, height); - - ArrayList copy0 = deepCopy(remainingHeights); - if (!copy0.contains(height)) - System.err.println("where did i go?"); - copy0.remove(height); - - total += possibleInternalNodePermutations(newNodeNumber, copy0); - - } else { - // The remaining permutations will not work - total += factorial(remainingHeights.size() - 1); - } - - } - - return total; - } - - - private ArrayList deepCopy(ArrayList in) { - ArrayList out = new ArrayList(); - for (double d : in) { - out.add(d); - } - return out; - } - - private static boolean containsLessThan(int[] a, int b) { - for (int c : a) { - if (c < b) - return true; - } - return false; - } - - public static void main(String[] args) { - ARGModel arg = new ARGModel(8, 20.0, 0.5); - System.out.println(arg.toARGSummary()); - System.out.println(arg.getReassortmentNodeCount()); - System.out.println(arg.toExtendedNewick()); -// BufferedWriter out = null; -// -// try { -// out = new BufferedWriter(new FileWriter("rejections.txt")); -// } catch (Exception e) { -// System.exit(-1); -// } -// -// int rejections = 0; -// -// MathUtils.setSeed(97695); -// -// ArrayList trees = new ArrayList(10000); -// -// while (rejections < 100) { -// ARGModel arg = new ARGModel(3, 6.0, 1.0); -// String s = ""; -// if (arg.getReassortmentNodeCount() < 2) { -// s = arg.toStrippedNewick(); -// } -// -// if (!s.equals("") && !trees.contains(s)) { -// trees.add(s); -// System.out.println("Total Current Size = " + trees.size() + " Rejections= " + rejections); -// rejections = 0; -// } else { -// rejections++; -// } -// } -// -// System.out.println("\n************************************"); -// System.out.println("Simulating trees"); -// -// Collections.sort(trees); -// int[] freq = new int[trees.size()]; -// int[] mcmcFreq = new int[trees.size()]; -// rejections = 0; -// -// while (containsLessThan(freq, 10000)) { -// ARGModel arg = new ARGModel(3, 6.0, 1.0); -// String s = null; -// if (arg.getReassortmentNodeCount() < 2) { -// s = arg.toStrippedNewick(); -// } -// -// if (s != null) { -// freq[Collections.binarySearch(trees, s)]++; -// } -// rejections++; -// if (rejections % 1000000 == 0) { -// System.out.println(rejections); -// } -// } -// -//// System.out.println("\n************************************"); -//// System.out.println("Analyzing MCMC results"); -//// -//// BufferedReader read = null; -//// try{ -//// read = new BufferedReader( new FileReader("prior.args")); -//// String s = read.readLine(); -//// s = read.readLine(); -//// -//// while(s != null){ -//// mcmcFreq[Collections.binarySearch(trees, s)]++; -//// s = read.readLine(); -//// } -//// -//// }catch(Exception e){ -//// System.exit(-1); -//// } -// -// System.out.println("\n************************************"); -// System.out.println("Printing Results"); -// -// -// try { -// out = new BufferedWriter(new FileWriter("coalescent.sim")); -// -// rejections = 0; -// for (String s : trees) { -// if (mcmcFreq[rejections] > -1) { -// out.write(s + " " + freq[rejections] + " " + mcmcFreq[rejections] + " \n"); -// } -// rejections++; -// } -// out.flush(); -// } catch (Exception IOException) { -// System.exit(-1); -// } - - } - - /** - * Packs and sends ARG state, including connectedness, heightparameters and - * partitioning parameters. - * - * @param toRank - */ - - @Override - public void sendState(int toRank) { - sendStateNoParameters(toRank); - int cnt = 0; - for (Node node : nodes) { - node.number = cnt; - cnt++; - } - final int size = nodes.size(); - MPIServices.sendInt(size, toRank); - int[] intMsg = new int[size * 7]; - double[] doubleMsg = new double[size]; - int indexNode = 0; - int indexHeight = 0; - int indexPartition = 0; - ArrayList partList = new ArrayList(); - for (Node node : nodes) { - intMsg[indexNode++] = node.number; - - if (node.leftParent != null) - intMsg[indexNode++] = node.leftParent.number; - else - intMsg[indexNode++] = -1; - if (node.rightParent != null) - intMsg[indexNode++] = node.rightParent.number; - else - intMsg[indexNode++] = -1; - if (node.leftChild != null) - intMsg[indexNode++] = node.leftChild.number; - else - intMsg[indexNode++] = -1; - if (node.rightChild != null) - intMsg[indexNode++] = node.rightChild.number; - else - intMsg[indexNode++] = -1; - - if (node.partitioning != null) { - intMsg[indexNode++] = indexPartition++; - partList.add(node.partitioning); - } else { - intMsg[indexNode++] = -1; - } - - if (node.bifurcation) - intMsg[indexNode++] = 1; - else - intMsg[indexNode++] = 0; - - doubleMsg[indexHeight++] = node.heightParameter - .getParameterValue(0); - } - MPIServices.sendIntArray(intMsg, toRank); - MPIServices.sendDoubleArray(doubleMsg, toRank); - MPIServices.sendInt(partList.size(), toRank); - for (Parameter partition : partList) { - // System.err.println("Sending a partition."); - double[] values = partition.getParameterValues(); - // System.err.println("length = "+values.length); - MPIServices.sendDoubleArray(partition.getParameterValues(), toRank); - } - // partitioningParameters.sendState(toRank); - MPIServices.sendInt(((Node) getRoot()).number, toRank); - } - - @Override - public void receiveState(int fromRank) { - receiveStateNoParameters(fromRank); - final int newNodeCount = MPIServices.receiveInt(fromRank); - // while (newNodeCount < nodes.size()) - // nodes.remove(0); - int[] intMsg = MPIServices.receiveIntArray(fromRank, newNodeCount * 7); - double[] doubleMsg = MPIServices.receiveDoubleArray(fromRank, - newNodeCount); - int partitionLength = MPIServices.receiveInt(fromRank); - // System.err.println("Attemping to receive "+partitionLength+" - // partitions."); - final int length = getNumberOfPartitions(); - // System.err.println("Expected length = "+length); - while (partitionLength > partitioningParameters.getParameterCount()) { - Parameter newPartition = new Parameter.Default(length); - partitioningParameters.addParameter(newPartition); - } - - for (int i = 0; i < partitionLength; i++) { - double[] values = MPIServices.receiveDoubleArray(fromRank, length); - // System.err.println("Received."); - Parameter param = partitioningParameters.getParameter(i); - // System.err.println("null? "+ (param == null ? "Yes" : "No")); - for (int j = 0; j < length; j++) { - // System.err.println("setting value #"+j+ " = "+values[j]); - - param.setParameterValueQuietly(j, values[j]); - } - // System.err.println("Values set"); - } - // System.err.println("Done with partition receive."); - - int root = MPIServices.receiveInt(fromRank); - // System.err.println("Start reconstructing ARG"); - - beginTreeEdit(); - while (newNodeCount > nodes.size()) { - Node newNode = new Node(); - newNode.heightParameter = new Parameter.Default(0.0); - nodes.add(newNode); - } - // System.err.println("extra height added"); - int nodeInt; - int indexNode = 0; - int indexHeight = 0; - int indexPartition = 0; - for (int i = 0; i < newNodeCount; i++) { - Node node = nodes.get(i); - node.number = intMsg[indexNode++]; - - nodeInt = intMsg[indexNode++]; - if (nodeInt != -1) - node.leftParent = nodes.get(nodeInt); - else - node.leftParent = null; - nodeInt = intMsg[indexNode++]; - if (nodeInt != -1) - node.rightParent = nodes.get(nodeInt); - else - node.rightParent = null; - nodeInt = intMsg[indexNode++]; - if (nodeInt != -1) - node.leftChild = nodes.get(nodeInt); - else - node.leftChild = null; - nodeInt = intMsg[indexNode++]; - if (nodeInt != -1) - node.rightChild = nodes.get(nodeInt); - else - node.rightChild = null; - // Parameter heightParam = - node.heightParameter.setParameterValueQuietly(0, - doubleMsg[indexHeight++]); - int whichPartitionParameter = intMsg[indexNode++]; - if (whichPartitionParameter != -1) { - // System.err.println("Setting partition para"); - - node.partitioning = partitioningParameters - .getParameter(whichPartitionParameter); - // System.err.println("Done setting param"); - } - - if (intMsg[indexNode++] == 1) - node.bifurcation = true; - else - node.bifurcation = false; - - } - // System.err.println("Recovered all nodes"); - setRoot(nodes.get(root)); - // try { - endTreeEditFast(); - // todo fire an ARG changed event??? - - // } catch (InvalidTreeException e) { - // throw new RuntimeException("Unable to unpack ARG correctly"); - // e.printStackTrace(); //To change body of catch statement use File | - // Settings | File Templates. - // } - - } - - public boolean isAncestral() { - - //zero everything first. - for (int i = 0; i < getNodeCount(); i++) { - Node x = (Node) getNode(i); - - x.fullAncestralMaterial = false; - x.hasSomeAncestralMaterial = false; - - if (x.ancestralMaterial == null) { - x.ancestralMaterial = new boolean[getNumberOfPartitions()]; - } - - for (int j = 0; j < x.ancestralMaterial.length; j++) { - x.ancestralMaterial[j] = false; - } - - } - - //post order up with the external nodes - - for (int i = 0; i < getExternalNodeCount(); i++) { - Node currentNode = (Node) getExternalNode(i); - - currentNode.fullAncestralMaterial = true; - currentNode.hasSomeAncestralMaterial = true; - - for (int j = 0; j < currentNode.ancestralMaterial.length; j++) { - currentNode.ancestralMaterial[j] = true; - } - - currentNode.leftParent.setAncestralMaterial(currentNode.ancestralMaterial); - } - - - //check that everything has some ancestral stuff. - for (int i = 0, n = getNodeCount(); i < n; i++) { - Node currentNode = (Node) getNode(i); - - if (!currentNode.hasSomeAncestralMaterial) { - return false; - } - } - - - return true; - } - - - public CompoundParameter getPartitioningParameters() { - return partitioningParameters; - } - - public void setupHeightBounds() { - for (Node node : nodes) { - node.setupHeightBounds(); - } - } - - // public static final String - - private String getNameOfNode(Node node) { - if (node.taxon == null) - return "n" + Integer.toString(node.number); - else - return node.taxon.getId(); - // return Integer.toString(node.number); - } - - public static final int MAX_LABEL_COUNT = 10; - - private Element makeEdge(Node from, Node to) { - Element edgeElement = new Element(EDGE_ELEMENT); - edgeElement.setAttribute(EDGE_FROM, getNameOfNode(from)); - edgeElement.setAttribute(EDGE_TO, getNameOfNode(to)); - edgeElement.setAttribute(EDGE_LENGTH, Double - .toString(getNodeHeight(from) - getNodeHeight(to))); - if (to.isReassortment()) { - double[] bits = to.partitioning.getParameterValues(); - int length = bits.length; - StringBuilder sb = new StringBuilder(); - boolean isLeft = (from == to.leftParent); - int countLabels = 0; - for (int i = 0; i < length; i++) { - if ((isLeft && bits[i] == 0) || (!isLeft && bits[i] == 1)) { - sb.append(i); - sb.append(" "); - countLabels++; - } - - } - if (countLabels < MAX_LABEL_COUNT) - edgeElement.setAttribute(EDGE_PARTITIONS, sb.toString().trim()); - } - return edgeElement; - } - - private Element makeNode(Node node) { - Element nodeElement = new Element(NODE_ELEMENT); - nodeElement.setAttribute(ID_ATTRIBUTE, getNameOfNode(node)); - if (node.taxon != null) { - nodeElement.setAttribute(IS_TIP, "true"); - nodeElement.setAttribute(TAXON_NAME, node.taxon.getId()); - // nodeElement.setAttribute("style","filled"); - // nodeElement.setAttribute("fillcolor","blue"); - } - if (node.isRoot()) { - nodeElement.setAttribute(IS_ROOT, "true"); - } - if (node.isReassortment()) { - nodeElement.setAttribute(IS_REASSORTMENT, "true"); - } - nodeElement - .setAttribute(NODE_HEIGHT, Double.toString(node.getHeight())); - return nodeElement; - } - - private Element makeNodeFullInfo(Node node) { - Element nodeElement = new Element(NODE_ELEMENT); - nodeElement.setAttribute(ID_ATTRIBUTE, getNameOfNode(node)); - - if (node.isRoot()) { - nodeElement.setAttribute(IS_ROOT, "true"); - } else { - nodeElement.setAttribute(LEFT_PARENT, - getNameOfNode(node.leftParent)); - nodeElement.setAttribute(RIGHT_PARENT, - getNameOfNode(node.rightParent)); - } - - if (node.taxon != null) { - nodeElement.setAttribute(IS_TIP, "true"); - nodeElement.setAttribute(TAXON_NAME, node.taxon.getId()); - } else { - nodeElement.setAttribute(LEFT_CHILD, getNameOfNode(node.leftChild)); - nodeElement.setAttribute(RIGHT_CHILD, - getNameOfNode(node.rightChild)); - } - nodeElement - .setAttribute(NODE_HEIGHT, Double.toString(node.getHeight())); - - return nodeElement; - } - - public ARGModel fromXML(Element rootElement) { - - int numPartitions = Integer.parseInt(rootElement - .getAttributeValue(NUM_PARTITIONS)); - int external = 0; - - // count # of nodeElements - List nodeList = rootElement.getChildren(NODE_ELEMENT); - ArrayList nodes = new ArrayList(); - Node rootNode = null; - // System.err.println("node # = "+nodeList.size()); - // System.exit(-1); - for (Element nodeElement : nodeList) { - Node node = new Node(); - nodes.add(node); - String isRoot = nodeElement.getAttributeValue(IS_ROOT); - if (isRoot != null && isRoot.compareTo("true") == 0) - rootNode = node; - String isReassortment = nodeElement - .getAttributeValue(IS_REASSORTMENT); - if (isReassortment != null && isReassortment.compareTo("true") == 0) - node.bifurcation = false; - else - node.bifurcation = true; - double height = Double.parseDouble(nodeElement - .getAttributeValue(NODE_HEIGHT)); - - node.heightParameter = new Parameter.Default(height); - node.setHeight(height); - - String isTip = nodeElement.getAttributeValue(IS_TIP); - if (isTip != null && isTip.compareTo("true") == 0) { - external++; - String taxonName = nodeElement.getAttributeValue(TAXON_NAME); - node.taxon = new Taxon(taxonName); // todo reuse taxonList - } - } - - List edgeList = rootElement.getChildren(EDGE_ELEMENT); - for (Element edgeElement : edgeList) { - int target = Integer.parseInt(edgeElement - .getAttributeValue(EDGE_TO)); - int source = Integer.parseInt(edgeElement - .getAttributeValue(EDGE_FROM)); - Node targetNode = nodes.get(target); - Node sourceNode = nodes.get(source); - - if (targetNode.isBifurcation()) { - targetNode.leftParent = targetNode.rightParent = sourceNode; - } else { - if (targetNode.leftParent == null) - targetNode.leftParent = sourceNode; - else { - targetNode.rightParent = sourceNode; - String partitionInfo = edgeElement - .getAttributeValue(EDGE_PARTITIONS); - Parameter partitioning = null; - // if (partitionInfo != null && sourceNode.leftChild != - // null) { - partitioning = new Parameter.Default(numPartitions, 0.0); - StringTokenizer st = new StringTokenizer(partitionInfo); - while (st.hasMoreTokens()) { - int which = Integer.parseInt(st.nextToken()); - partitioning.setParameterValueQuietly(which, 1.0); - } - // } - targetNode.partitioning = partitioning; - - } - } - - if (sourceNode.leftChild == null) - sourceNode.leftChild = targetNode; - // sourceNode. - // } - else { - sourceNode.rightChild = targetNode; - // sourceNode.partitioning = partitioning; - } - // todo parse partition info - } - - return new ARGModel(nodes, rootNode, numPartitions, external); - } - - public Element toXML() { - - // toGraphStringCompressed(true); - - int cnt = 0; - for (Node node : nodes) - node.number = cnt++; - - Element graphElement = new Element(GRAPH_ELEMENT); - graphElement.setAttribute("edgedefault", "directed"); - graphElement.setAttribute(NUM_PARTITIONS, Integer - .toString(getNumberOfPartitions())); - - for (Node node : nodes) { - - graphElement.addContent(makeNode(node)); - // Add edge to left parent if not root - if (node.leftParent != null) { - graphElement.addContent(makeEdge(node.leftParent, node)); - - } - // Add edge to right parent if reassortment - if (node.rightParent != null && node.isReassortment()) { - graphElement.addContent(makeEdge(node.rightParent, node)); - } - - } - - // System.err.println("start = "+nodes.size()); - // ARGModel test = fromXML(graphElement); - // System.err.println(test.toGraphString()); - - // System.err.println("old 0:"+getNewick(0)); - // System.err.println("old 1:"+getNewick(1)); - // System.err.println("old 2:"+getNewick(2)); - // System.err.println("new 0:"+test.getNewick(0)); - - return graphElement; - } - - public String toStrippedNewick() { - String s = root.toExtendedNewick() + ";"; -// s = s.replaceAll("[0-9a-zA-Z]", ""); - s = s.replaceAll("[^(),<>;]", ""); - return s; - - } - - public String toExtendedNewick() { - // StringBuffer sb = new StringBuffer(); - return root.toExtendedNewick() + ";"; - } - - /** - * Push a tree changed event into the event stack. - */ - public void pushTreeChangedEvent() { - pushTreeChangedEvent(new ARGTreeChangedEvent()); - } - - public void pushTreeSizeChangedEvent() { - throw new RuntimeException("No longer supported; use updated operators"); - } - - public void pushTreeSizeIncreasedEvent() { - pushTreeChangedEvent(new ARGTreeChangedEvent(+1)); - } - - public void pushTreeSizeDecreasedEvent() { - pushTreeChangedEvent(new ARGTreeChangedEvent(-1)); - } - - /** - * Push a tree changed event into the event stack. - */ - public void pushTreeChangedEvent(NodeRef nodeRef) { - pushTreeChangedEvent(new ARGTreeChangedEvent((Node) nodeRef)); - } - - /** - * Push a tree changed event into the event stack. - */ - public void pushTreeChangedEvent(Node node, Parameter parameter, int index) { - pushTreeChangedEvent(new ARGTreeChangedEvent(node, parameter, index)); - } - - /** - * Push a tree changed event into the event stack. - */ - public void pushTreeChangedEvent(TreeChangedEvent event) { - if (inEdit) { - treeChangedEvents.add(event); - } else { - listenerHelper.fireModelChanged(this, event); - } - } - - protected void handleModelChangedEvent(Model model, Object object, int index) { - // no submodels so nothing to do - } - - /** - * Called when a parameter changes. - */ - public void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) { - - Node node = getNodeOfParameter((Parameter) variable); - pushTreeChangedEvent(node, (Parameter) variable, index); - } - - private ArrayList likelihoodCalculators; - - private int maxNumberOfPartitions; - - public int getNumberOfPartitions() { - return maxNumberOfPartitions; - } - - public int addLikelihoodCalculator(ARGLikelihood calc) { - // int len = 0; - if (likelihoodCalculators == null) { - likelihoodCalculators = new ArrayList(); - } - likelihoodCalculators.add(calc); - int len = likelihoodCalculators.size() - 1; - maxNumberOfPartitions = likelihoodCalculators.size(); - System.err.println("Add calculator for partition #" + len); - setPartitionRecursively(getRoot(), len); - return len; - } - - public int getMaxPartitionNumber() { - return maxNumberOfPartitions; - } - - protected final List treeChangedEvents = new ArrayList(); - - public class ARGTreeChangedEvent implements TreeChangedEvent { - - final Node node; - - final Parameter parameter; - - final int index; - - int size = 0; - final boolean nodeOrderChanged; - - public ARGTreeChangedEvent() { - this(null, null, -1,false); - } - -// public TreeChangedEvent(ARGModel arg) { -// this(null, null, -1); -// size = true; -// } - - public ARGTreeChangedEvent(Node node) { - this(node, null, -1,false); - } - - public ARGTreeChangedEvent(Node node, Parameter parameter, int index) { - this(node, parameter, index,false); - } - - public ARGTreeChangedEvent(Node node, Parameter parameter, int index, boolean nodeOrderChanged) { - this.node = node; - this.parameter = parameter; - this.index = index; - this.nodeOrderChanged = nodeOrderChanged; - } - public ARGTreeChangedEvent(int sizeChanged) { - this(null, null, -1,false); - size = sizeChanged; - } - - public int getIndex() { - return index; - } - - public Node getNode() { - return node; - } - - public Parameter getParameter() { - return parameter; - } - - public int getSize() { - return size; - } - - public boolean isSizeChanged() { - return !(size == 0); - } - - public boolean isTreeChanged() { - return parameter == null; - } - - public boolean isNodeChanged() { - return node != null; - } - - public boolean isNodeParameterChanged() { - return parameter != null; - } - - public boolean isHeightChanged() { - return parameter == node.heightParameter; - } - - public boolean isOnlyHeightChanged() { - return false; - } - - public boolean isRateChanged() { - return parameter == node.rateParameter; - } - - public boolean isTraitChanged() { - return parameter == node.traitParameter; - } - - public boolean isNodeOrderChanged(){ return nodeOrderChanged;} - } - - // ***** - // Interface Loggable - // ***** - - public LogColumn[] getColumns() { - int numColumns = 3; - // numColumns += this.getMaxPartitionNumber(); - // LogColumn[] logColumns = new LogColumn[numColumns + - // getMaxPartitionNumber()]; - LogColumn[] logColumns = new LogColumn[3]; - //logColumns[0] = new IsReassortmentColumn("isReassortment"); - logColumns[0] = new CountReassortmentColumn("numberReassortments"); - logColumns[1] = new ExtremeNodeHeightColumn("maxNodeHeight") { - double getStartValue() { - return 0; - } - - double compare(double currentValue, double newValue) { - if (newValue > currentValue) - return newValue; - return currentValue; - } - }; - logColumns[2] = new ExtremeNodeHeightColumn("minNodeHeight") { - double getStartValue() { - return 0; - } - - double compare(double currentValue, double newValue) { - if (newValue == 0) { - return currentValue; - } else if (currentValue == 0) { - return newValue; - } - if (newValue < currentValue) - return newValue; - return currentValue; - } - }; - /*logColumns[4] = new NumberColumn("Left Node"){ - public double getDoubleValue() { - Node a = (Node) getRoot(); - return a.leftChild.getHeight(); - } - }; - logColumns[5] = new NumberColumn("Right Node"){ - public double getDoubleValue() { - Node a = (Node) getRoot(); - return a.rightChild.getHeight(); - } - }; - logColumns[6] = new NumberColumn("Reassort Height"){ - public double getDoubleValue() { - double b = 0; - for(Node a : nodes){ - if(a.isReassortment()){ - b = a.getHeight(); - break; - } - } - return b; - } - };*/ - - // logColumns[2] = new IsRootTooHighColumn("isRootTooHigh"); - // for (int i = 0; i < getMaxPartitionNumber(); i++) - // logColumns[4 + i] = new ArgTreeHeightColumn("argTreeHeight", this, - // i); - return logColumns; - } - - private abstract class ExtremeNodeHeightColumn extends NumberColumn { - - public ExtremeNodeHeightColumn(String label) { - super(label); - } - - abstract double compare(double currentValue, double newValue); - - /* - * { if (newValue > currentValue) return newValue; return currentValue; } - */ - - abstract double getStartValue(); - - public double getDoubleValue() { - double criticalValue = getStartValue(); - for (Node node : nodes) { - double nodeHeight = node.heightParameter.getParameterValue(0); - if (nodeHeight > 0 && !isRoot(node)) { - criticalValue = compare(criticalValue, nodeHeight); - } - } - return criticalValue; - } - } - - private class ArgTreeHeightColumn extends NumberColumn { - - private final int partition; - - private final ARGModel argModel; - - public ArgTreeHeightColumn(String label, ARGModel argModel, - int partition) { - super(label + partition); - this.argModel = argModel; - this.partition = partition; - } - - public double getDoubleValue() { - ARGTree argTree = new ARGTree(argModel, partition); - return argTree.getNodeHeight(argTree.getRoot()); - // return (new ARGTree( - } - } - - private class IsReassortmentColumn extends NumberColumn { - - public IsReassortmentColumn(String label) { - super(label); // To change body of overridden methods use File | - // Settings | File Templates. - } - - public double getDoubleValue() { - return getReassortmentNodeCount() == 0 ? 0 : 1; - } - } - - private class IsRootTooHighColumn extends NumberColumn { - - public IsRootTooHighColumn(String label) { - super(label); // To change body of overridden methods use File | - // Settings | File Templates. - } - - public double getDoubleValue() { - return isBifurcationDoublyLinked(getRoot()) ? 1 : 0; - } - } - - private class CountReassortmentColumn extends NumberColumn { - - public CountReassortmentColumn(String label) { - super(label); // To change body of overridden methods use File | - // Settings | File Templates. - } - - public double getDoubleValue() { - return getReassortmentNodeCount(); - } - } - - public void setPartitionType(String partitionType) { - this.partitionType = partitionType; - } - - public String getPartitionType() { - return partitionType; - } - - public boolean isRecombinationPartitionType() { - if (partitionType.equals(RECOMBINATION_PARTITION)) { - return true; - } - return false; - } - - // ***************************************************************** - // Interface Tree - // ***************************************************************** - - /** - * Return the units that this tree is expressed in. - */ - public final Type getUnits() { - return units; - } - - public void setUnits(Type units) { - this.units = units; - - } - - /** - * Sets the units that this tree is expressed in. - */ - - /** - * @return a count of the number of nodes (internal + external) in this - * tree. - */ - public final int getNodeCount() { - return nodes.size(); - } - - public final boolean hasNodeHeights() { - return true; - } - - public NodeRef getMirrorNode(NodeRef node) { - -// for(Node argNode: nodes) { -// if (((Node)node).mirrorNode == argNode) -// System.err.println("Found (in getMirrorNode)"); -// } - - return ((Node) node).mirrorNode; - } - - public final double getNodeHeight(NodeRef node) { - - // System.err.println(Tree.Utils.uniqueNewick(this, node)); - // ((Node)node)) - - return ((Node) node).getHeight(); - } - - public final double getMinParentNodeHeight(NodeRef nr) { - Node node = (Node) nr; - return Math.min(node.leftParent.getHeight(), node.rightParent - .getHeight()); - } - - public final double getNodeHeightUpper(NodeRef node) { - return ((Node) node).heightParameter.getBounds().getUpperLimit(0); - } - - public final double getNodeHeightLower(NodeRef node) { - return ((Node) node).heightParameter.getBounds().getLowerLimit(0); - } - - /** - * @param nodeRef - * @return the rate parameter associated with this node. - */ - public final double getNodeRate(NodeRef nodeRef, int partition) { - if (!hasRates) { - return 1.0; - } - - - return 0.0; - } - - public Object getNodeAttribute(NodeRef node, String name) { - throw new UnsupportedOperationException( - "ARGModel does not use NodeAttributes"); - } - - public Iterator getNodeAttributeNames(NodeRef node) { - throw new UnsupportedOperationException( - "ARGModel does not use NodeAttributes"); - } - - public double getNodeTrait(NodeRef node) { - if (!hasTraits) - throw new IllegalArgumentException( - "Trait parameters have not been created"); - return ((Node) node).getTrait(); - } - - public final Taxon getNodeTaxon(NodeRef node) { - return ((Node) node).taxon; - } - - public final boolean isExternal(NodeRef node) { - return ((Node) node).isExternal(); - } - - public final boolean isInternal(NodeRef node) { - return !this.isExternal(node); - } - - public final boolean isRoot(NodeRef node) { - return (node == root); - } - - public final boolean isBifurcation(NodeRef node) { - return ((Node) node).isBifurcation(); - } - - public final boolean isBifurcationDoublyLinked(NodeRef node) { - return ((Node) node).isBifurcationDoublyLinked(); - } - - public final boolean isReassortment(NodeRef node) { - return ((Node) node).isReassortment(); - } - - public final int countReassortmentNodes(NodeRef nr) { - Node node = (Node) nr; - int count = node.countReassortmentChild(this); - // int count = 0; - return (count / 2); - } - - public final int getChildCount(NodeRef node) { - return ((Node) node).getChildCount(); - } - - - public final NodeRef getOtherChild(NodeRef parent, NodeRef wrongChild) { - Node p = (Node) parent; - Node c = (Node) wrongChild; - - if (p.leftChild == c) { - return p.rightChild; - } - return p.leftChild; - } - - public final NodeRef getBrother(NodeRef node) { - Node n = (Node) node; - - if (n.isReassortment()) { - return node; - } - Node p = n.leftParent; - - if (p.leftChild == n) { - return p.rightChild; - } - - return p.leftChild; - } - - /** - * If i = 0, the left child is returned, else if i = 1, the right child is - * returned. - * - * @return The child of the entered node. - */ - public final NodeRef getChild(NodeRef node, int i) { - return ((Node) node).getChild(i); - } - - public final NodeRef getChild(NodeRef node, int i, int partition) { - return ((Node) node).getChild(i, partition); - } - - // public final NodeRef getParent(NodeRef node) { return - // ((Node)node).parent; } - public final NodeRef getParent(NodeRef node) { - Node left = ((Node) node).leftParent; - Node right = ((Node) node).rightParent; - if (left == right) - return left; - else - throw new IllegalArgumentException( - "No single parent for reassorted node"); - } - - /** - * @param node The child noderef - * @param i i = 0 (left parent) i = 1 (right parent) - * @return The corresponding parent noderef - */ - public final NodeRef getParent(NodeRef node, int i) { - if (i == 0) - return ((Node) node).leftParent; - if (i == 1) - return ((Node) node).rightParent; - throw new IllegalArgumentException( - "ARGModel.Node can only have two parents"); - } - - public final boolean hasBranchLengths() { - return true; - } - - public final double getBranchLength(NodeRef node) { - NodeRef parent = getParent(node); - if (parent == null) { - return 0.0; - } - - return getNodeHeight(parent) - getNodeHeight(node); - } - - public final NodeRef getExternalNode(int i) { - return nodes.get(i); - } - - public final NodeRef getInternalNode(int i) { - return nodes.get(i + externalNodeCount); - } - - public final NodeRef getNode(int i) { - return nodes.get(i); - } - - /** - * Returns the number of external nodes. - */ - public final int getExternalNodeCount() { - return externalNodeCount; - } - - /** - * Returns the ith internal node. - */ - public final int getInternalNodeCount() { - return internalNodeCount; - } - - - public final int getReassortmentNodeCount() { - int cnt = 0; - for (Node node : nodes) { - if (!node.bifurcation) - cnt++; - } - return cnt; - } - - // public final int getReassortmentNodeCount() { return nullCounter; } - - public void addNullCounter() { - nullCounter++; - } - - public void removeNullCounter() { - nullCounter--; - } - - /** - * Returns the root node of this tree. - */ - public final NodeRef getRoot() { - return root; - } - - public final NodeRef getRoot(int partition) { - // TODO - return null; - } - - // ***************************************************************** - // Interface MutableTree - // ***************************************************************** - - /** - * Set a new node as root node. - */ - public final void setRoot(NodeRef newRoot) { - - if (!inEdit) - throw new RuntimeException( - "Must be in edit transaction to call this method!"); - - root = (Node) newRoot; - - // We shouldn't need this because the addChild will already have fired - // appropriate events. - // pushTreeChangedEvent(); - } - - public void swapHeightParameters(NodeRef n1, NodeRef n2) { - Node node1 = (Node) n1; - Node node2 = (Node) n2; - double height1 = node1.getHeight(); - double height2 = node2.getHeight(); - Parameter trans = node1.heightParameter; - node1.heightParameter = node2.heightParameter; - node2.heightParameter = trans; - node1.setHeight(height1); - node2.setHeight(height2); - - } - - /** - * Links parent with child. If - * parent is a bifurcation node, - * the method calls singleAddChild(parent,child), - * otherwise, the method calls doubleAddChild(parent,child). - * - * @throws RuntimeException if not in edit mode. - * @see singleAddChild(NodeRef parent, NodeRef child) - * @see doubleAddChild(NodeRef parent, NodeRef child) - */ - public void addChild(NodeRef parent, NodeRef child) { - checkEditMode(); - - Node p = (Node) parent; - Node c = (Node) child; - - if (p.bifurcation) { - p.singleAddChild(c); - } else { - p.doubleAddChild(c); - } - } - - public void addChildWithSingleParent(NodeRef parent, NodeRef child) { - checkEditMode(); - - Node p = (Node) parent; - Node c = (Node) child; - - if (p.bifurcation) { - p.singleAddChildWithOneParent(c); - } else { - p.doubleAddChildWithOneParent(c); - } - - } - - - /** - * Makes a link between parent and child. - * By default, if parent has a null reference for both - * it's children, child will become the left child of - * parent, otherwise child will become - * the right child of parent.

If the right parent - * of child is null, parent - * will become the parent, the same thing will happen for the left parent - * of child. - * - * @param parent the NodeRef that will become the parent of child - * @param child the NodeRef that will become the child of parent - * @throws RuntimeException if the you are not in edit transaction mode - * @throws IllegalArgumentException if parent already has two children. - */ - public void singleAddChild(NodeRef parent, NodeRef child) { - - if (!inEdit) { - throw new RuntimeException( - "must be in edit transaction to call this method!"); - } - - Node p = (Node) parent; - Node c = (Node) child; - p.singleAddChild(c); - } - - public void singleAddChildWithOneParent(NodeRef p, NodeRef c) { - - if (!inEdit) - throw new RuntimeException( - "Must be in edit transaction to call this method!"); - - Node parent = (Node) p; - Node child = (Node) c; - parent.singleAddChildWithOneParent(child); - } - - public void doubleAddChild(NodeRef p, NodeRef c) { - - if (!inEdit) - throw new RuntimeException( - "Must be in edit transaction to call this method!"); - - Node parent = (Node) p; - Node child = (Node) c; - parent.doubleAddChild(child); - } - - public void doubleAddChildWithOneParent(NodeRef p, NodeRef c) { - - if (!inEdit) - throw new RuntimeException( - "Must be in edit transaction to call this method!"); - - Node parent = (Node) p; - Node child = (Node) c; - parent.doubleAddChildWithOneParent(child); - } - - public void addChildAsRecombinant(NodeRef p1, NodeRef p2, NodeRef c, - Parameter partitioning) { - // public void addChildAsRecombinant(NodeRef p1, NodeRef p2, NodeRef c, - // BitSet bs1, BitSet bs2) { - if (!inEdit) - throw new RuntimeException( - "Must be in edit transaction to call this method!"); - Node parent1 = (Node) p1; - Node parent2 = (Node) p2; - Node child = (Node) c; - // if (parent1.hasChild(child) || parent2.hasChild(child)) throw new - // IllegalArgumentException("Child already exists in parent"); - // if (parent2.hasChild(child)) throw new - // IllegalArgumentException("Child already exists in") - parent1.addChildRecombinant(child, partitioning); - parent2.addChildRecombinant(child, partitioning); - // if( parent2.getChildCount() == 1 ) - // parent2.addChildNoParentConnection(node); - } - - /** - * Removes the link between parent and - * child. If parent is a bifurcation node, - * the method calls singleRemoveChild(parent, child), - * otherwise, the method calls doubleRemoveChild(parent,child). - * - * @throws RuntimeException if not in edit mode. - * @see singleRemoveChild(NodeRef parent, NodeRef child) - * @see doubleRemoveChild(NodeRef parent, NodeRef child) - */ - public void removeChild(NodeRef parent, NodeRef child) { - checkEditMode(); - - Node p = (Node) parent; - Node c = (Node) child; - - p.doubleRemoveChild(c); - } - - public void replaceChild(NodeRef node, NodeRef child, NodeRef newChild) { - - } - - /** - * Removes the link between the parent and the child. This method should be - * called when the child's parents are both the same. After the method is - * called the parent will have two null references for children, and the - * child will have two null references for parents. - * - * @param parent The parent NodeRef - * @param child The child NodeRef - * // * @see doubleAddChild() - * // * @see singleAddChild() - * // * @see removeChild() - * // * @see singleRemoveChild() - */ - public void doubleRemoveChild(NodeRef parent, NodeRef child) { - checkEditMode(); - - Node p = (Node) parent; - Node c = (Node) child; - - p.doubleRemoveChild(c); - } - - public void singleRemoveChild(NodeRef p, NodeRef c) { - checkEditMode(); - - Node parent = (Node) p; - Node child = (Node) c; - - parent.singleRemoveChild(child); - } - - protected Node oldRoot; - - - public boolean beginTreeEdit() { - if (inEdit) - throw new RuntimeException("Alreading in edit transaction mode!"); - - oldRoot = root; - - inEdit = true; - - return false; - } - - public void endTreeEdit() { - if (!inEdit) - throw new RuntimeException("Not in edit transaction mode!"); - - inEdit = false; - - if (root != oldRoot) { - swapParameterObjects(oldRoot, root); - } - - // ystem.err.println("There are "+treeChangedEvents.size()+" events - // waiting"); - // System.exit(-1); - for(TreeChangedEvent treeChangedEvent : treeChangedEvents) { - listenerHelper.fireModelChanged(this, treeChangedEvent); - } - treeChangedEvents.clear(); - } - - public void checkTreeIsValid() throws MutableTree.InvalidTreeException { - for (Node node : nodes) { - if (!node.heightParameter.isWithinBounds()) { - throw new InvalidTreeException("height parameter out of bounds"); - } - } - } - - private void endTreeEditFast() { - inEdit = false; - } - - public void setNodeHeight(NodeRef n, double height) { - ((Node) n).setHeight(height); - } - - public void setNodeRate(NodeRef n, double rate) { - if (!hasRates) - throw new IllegalArgumentException( - "Rate parameters have not been created"); - ((Node) n).setRate(rate); - - } - - public void setNodeTrait(NodeRef n, double value) { - if (!hasTraits) - throw new IllegalArgumentException( - "Trait parameters have not been created"); - ((Node) n).setTrait(value); - } - - public void setNodeNumber(NodeRef node, int n) { - node.setNumber(n); - } - - public void setBranchLength(NodeRef node, double length) { - throw new UnsupportedOperationException( - "ARGModel cannot have branch lengths set"); - } - - public void setNodeAttribute(NodeRef node, String name, Object value) { - throw new UnsupportedOperationException( - "ARGModel does not use NodeAttributes"); - } - - // ***************************************************************** - // Interface ModelComponent - // ***************************************************************** - - /** - * Store current state - */ - protected void storeState() { - /* - * System.err.println("Storing state"); this.checkBranchSanity(); - * System.err.println("sane before operation"); - */ - copyNodeStructure(storedNodes); - // storedRootNumber = storedNodes.indexOf(root.getNumber(); - storedRootNumber = nodes.indexOf(root); - storedNodeCount = nodeCount; - storedInternalNodeCount = internalNodeCount; - addedParameters = null; - addedPartitioningParameter = null; - addedNodes = null; - removedParameters = null; - removedPartitioningParameter = null; - removedNodes = null; - storedNullCounter = nullCounter; - // System.err.println("Stored: "+Tree.Utils.uniqueNewick(this, - // getRoot())); - // System.err.println("Stored : "+this.toString()); - } - - /** - * Restore the stored state - */ - protected void restoreState() { - - ArrayList tmp = storedNodes; - storedNodes = nodes; - nodes = tmp; - root = nodes.get(storedRootNumber); - - nodeCount = storedNodeCount; - internalNodeCount = storedInternalNodeCount; - - //This part occurs true when we add a new arg event - //onto the root. - - if (addedParameters != null) { - if (addedParameters.length == 5) { - removeVariable(addedParameters[0]); - removeVariable(addedParameters[1]); - removeVariable(addedParameters[2]); - removeVariable(addedParameters[3]); - - storedInternalNodeHeights.removeParameter(addedParameters[0]); - storedInternalNodeHeights.removeParameter(addedParameters[4]); - - storedInternalAndRootNodeHeights.removeParameter(addedParameters[0]); - storedInternalAndRootNodeHeights.removeParameter(addedParameters[1]); - - storedNodeRates.removeParameter(addedParameters[2]); - } else { - storedInternalNodeHeights.removeParameter(addedParameters[0]); - storedInternalNodeHeights.removeParameter(addedParameters[1]); - - removeVariable(addedParameters[0]); - removeVariable(addedParameters[1]); - - storedInternalAndRootNodeHeights - .removeParameter(addedParameters[0]); - storedInternalAndRootNodeHeights - .removeParameter(addedParameters[1]); - - removeVariable(addedParameters[2]); - removeVariable(addedParameters[3]); - storedNodeRates.removeParameter(addedParameters[2]); -// storedNodeRates.removeVariable(addedParameters[3]); - } - } - if (addedPartitioningParameter != null) { - partitioningParameters.removeParameter(addedPartitioningParameter); - removeVariable(addedPartitioningParameter); - } - if (removedParameters != null) { - storedInternalNodeHeights.addParameter(removedParameters[0]); - storedInternalNodeHeights.addParameter(removedParameters[1]); - addVariable(removedParameters[0]); - addVariable(removedParameters[1]); - - storedInternalAndRootNodeHeights.addParameter(removedParameters[0]); - storedInternalAndRootNodeHeights.addParameter(removedParameters[1]); - - addVariable(removedParameters[2]); - addVariable(removedParameters[3]); - storedNodeRates.addParameter(removedParameters[2]); -// storedNodeRates.addVariable(removedParameters[3]); - - } - - if (removedPartitioningParameter != null) { - partitioningParameters.addParameter(removedPartitioningParameter); - addVariable(removedPartitioningParameter); - } - - - nullCounter = storedNullCounter; - } - - /** - * accept the stored state - */ - protected void acceptState() { - // System.err.println("Accepted ARG\n"+this.toGraphString()); - } // nothing to do - - /** - * Adopt the state of the model component from source. - */ - protected void adoptState(Model source) { - } - - /* - * public void addNewHeightParameters(Parameter newbie1, Parameter newbie2, - * CompoundParameter internalNodeParameters, - * CompoundParameter internalAndRootNodeParameters) { - * addVariable(newbie1); addVariable(newbie2); addedParameters = new - * Parameter[2]; addedParameters[0] = newbie1; addedParameters[1] = newbie2; - * - * storedInternalNodeHeights = internalNodeParameters; - * storedInternalNodeHeights.addVariable(newbie1); - * storedInternalNodeHeights.addVariable(newbie2); - * - *//* - * storedInternalAndRootNodeHeights = internalAndRootNodeParameters; - * storedInternalAndRootNodeHeights.addVariable(newbie1); - * storedInternalAndRootNodeHeights.addVariable(newbie2); - *//* - * } - */ - - public void expandARG(Node newbie1, Node newbie2, - CompoundParameter internalNodeParameters, - CompoundParameter internalAndRootNodeParameters, - CompoundParameter nodeRates) { - - addVariable(newbie1.heightParameter); - addVariable(newbie2.heightParameter); - addVariable(newbie2.partitioning); - - addVariable(newbie1.rateParameter); - addVariable(newbie2.rateParameter); - - addedParameters = new Parameter[4]; - addedParameters[0] = newbie1.heightParameter; - addedParameters[1] = newbie2.heightParameter; - addedParameters[2] = newbie1.rateParameter; - addedParameters[3] = newbie2.rateParameter; - addedPartitioningParameter = newbie2.partitioning; - - storedInternalNodeHeights = internalNodeParameters; - storedInternalNodeHeights.addParameter(newbie1.heightParameter); - storedInternalNodeHeights.addParameter(newbie2.heightParameter); - - storedInternalAndRootNodeHeights = internalAndRootNodeParameters; - storedInternalAndRootNodeHeights.addParameter(newbie1.heightParameter); - storedInternalAndRootNodeHeights.addParameter(newbie2.heightParameter); - - storedNodeRates = nodeRates; - storedNodeRates.addParameter(newbie1.rateParameter); -// storedNodeRates.addVariable(newbie2.rateParameter); - - - partitioningParameters.addParameter(newbie2.partitioning); - nodes.add(newbie1); - nodes.add(newbie2); - internalNodeCount += 2; - -// pushTreeSizeIncreasedEvent(); - - } - - public void expandARGWithRecombinant(Node newbie1, Node newbie2, - CompoundParameter internalNodeParameters, - CompoundParameter internalAndRootNodeParameters, - CompoundParameter nodeRates) { - // System.err.println("attempting to expand"); - - addVariable(newbie1.heightParameter); - addVariable(newbie2.heightParameter); - addVariable(newbie2.partitioning); - - // System.err.println("expand 0"); - - addVariable(newbie1.rateParameter); - addVariable(newbie2.rateParameter); - - // System.err.println("expand 1"); - - addedParameters = new Parameter[4]; - addedParameters[0] = newbie1.heightParameter; - addedParameters[1] = newbie2.heightParameter; - addedParameters[2] = newbie1.rateParameter; - addedParameters[3] = newbie2.rateParameter; - addedPartitioningParameter = newbie2.partitioning; - - // System.err.println("expand 2"); - - storedInternalNodeHeights = internalNodeParameters; - storedInternalNodeHeights.addParameter(newbie1.heightParameter); - storedInternalNodeHeights.addParameter(newbie2.heightParameter); - - storedInternalAndRootNodeHeights = internalAndRootNodeParameters; - storedInternalAndRootNodeHeights.addParameter(newbie1.heightParameter); - storedInternalAndRootNodeHeights.addParameter(newbie2.heightParameter); - - storedNodeRates = nodeRates; - storedNodeRates.addParameter(newbie1.rateParameter); - storedNodeRates.addParameter(newbie2.rateParameter); - - // System.err.println("expand 3"); - - partitioningParameters.addParameter(newbie2.partitioning); - nodes.add(newbie1); - nodes.add(newbie2); - internalNodeCount += 2; - // sanityNodeCheck(internalNodeParameters); -// pushTreeSizeIncreasedEvent(); - - // System.err.println("done expand"); - - } - - public void sanityNodeCheck(CompoundParameter inodes) { - int len = inodes.getParameterCount(); - for (int i = 0; i < len; i++) { - Parameter p = inodes.getParameter(i); - for (int j = 0; j < internalNodeCount; j++) { - Node node = (Node) getInternalNode(j); - if (node.heightParameter == p) { - if (isRoot(node)) { - System.err - .println("Root height found in internal nodes"); - System.exit(-1); - } - } - - } - } - } - - public void contractARGWithRecombinantNewRoot(Node oldie, - Node oldRoot, Node newRoot, - CompoundParameter internalNodeParameters, - CompoundParameter internalAndRootNodeParameters, - CompoundParameter nodeRates) { - removeVariable(oldie.heightParameter); - removeVariable(oldRoot.heightParameter); - removeVariable(oldie.partitioning); - - removeVariable(oldie.rateParameter); - removeVariable(oldie.rateParameter); - - removedParameters = new Parameter[4]; - removedParameters[0] = oldie.heightParameter; - removedParameters[1] = oldRoot.heightParameter; - removedParameters[2] = oldie.rateParameter; - removedParameters[3] = oldRoot.rateParameter; - - partitioningParameters.removeParameter(oldie.partitioning); - removedPartitioningParameter = oldie.partitioning; - storedInternalNodeHeights = internalNodeParameters; - - storedInternalNodeHeights.removeParameter(oldie.heightParameter); - - storedInternalAndRootNodeHeights = internalAndRootNodeParameters; - storedInternalAndRootNodeHeights - .removeParameter(oldie.heightParameter); - storedInternalAndRootNodeHeights - .removeParameter(oldRoot.heightParameter); - - storedNodeRates = nodeRates; - storedNodeRates.removeParameter(oldie.rateParameter); - storedNodeRates.removeParameter(oldRoot.rateParameter); - - nodes.remove(oldie); - nodes.remove(oldRoot); - internalNodeCount -= 2; - - this.setRoot(newRoot); -// pushTreeSizeDecreasedEvent(); - - - } - - - public void contractARG(Node oldie1, Node oldie2, - CompoundParameter internalNodeParameters, - CompoundParameter internalAndRootNodeParameters, - CompoundParameter nodeRates) { - - removeVariable(oldie1.heightParameter); - removeVariable(oldie2.heightParameter); - removeVariable(oldie2.partitioning); - - - removeVariable(oldie1.rateParameter); - removeVariable(oldie2.rateParameter); - - - removedParameters = new Parameter[4]; - removedParameters[0] = oldie1.heightParameter; - removedParameters[1] = oldie2.heightParameter; - removedParameters[2] = oldie1.rateParameter; - removedParameters[3] = oldie2.rateParameter; - - - partitioningParameters.removeParameter(oldie2.partitioning); - removedPartitioningParameter = oldie2.partitioning; - storedInternalNodeHeights = internalNodeParameters; - storedInternalNodeHeights.removeParameter(oldie1.heightParameter); - storedInternalNodeHeights.removeParameter(oldie2.heightParameter); - - - storedInternalAndRootNodeHeights = internalAndRootNodeParameters; - storedInternalAndRootNodeHeights.removeParameter(oldie1.heightParameter); - storedInternalAndRootNodeHeights.removeParameter(oldie2.heightParameter); - - - storedNodeRates = nodeRates; - storedNodeRates.removeParameter(oldie1.rateParameter); -// storedNodeRates.removeVariable(oldie2.rateParameter); - - nodes.remove(oldie1); - nodes.remove(oldie2); - - internalNodeCount -= 2; -// pushTreeSizeDecreasedEvent(); - } - - - /** - * Cleans up the arg model after a deletion event. - * - * @param oldie1 - * @param oldie2 - * @param internalNodeParameters - * @param internalAndRootNodeParameters - * @param nodeRates - */ - public void contractARGWithRecombinant(Node oldie1, Node oldie2, - CompoundParameter internalNodeParameters, - CompoundParameter internalAndRootNodeParameters, - CompoundParameter nodeRates) { - - removeVariable(oldie1.heightParameter); - removeVariable(oldie2.heightParameter); - removeVariable(oldie2.partitioning); - - - removeVariable(oldie1.rateParameter); - removeVariable(oldie2.rateParameter); - - - removedParameters = new Parameter[4]; - removedParameters[0] = oldie1.heightParameter; - removedParameters[1] = oldie2.heightParameter; - removedParameters[2] = oldie1.rateParameter; - removedParameters[3] = oldie2.rateParameter; - - - partitioningParameters.removeParameter(oldie2.partitioning); - removedPartitioningParameter = oldie2.partitioning; - storedInternalNodeHeights = internalNodeParameters; - storedInternalNodeHeights.removeParameter(oldie1.heightParameter); - storedInternalNodeHeights.removeParameter(oldie2.heightParameter); - - - storedInternalAndRootNodeHeights = internalAndRootNodeParameters; - storedInternalAndRootNodeHeights - .removeParameter(oldie1.heightParameter); - storedInternalAndRootNodeHeights - .removeParameter(oldie2.heightParameter); - - - storedNodeRates = nodeRates; - storedNodeRates.removeParameter(oldie1.rateParameter); - storedNodeRates.removeParameter(oldie2.rateParameter); - - nodes.remove(oldie1); - nodes.remove(oldie2); - - internalNodeCount -= 2; -// pushTreeSizeDecreasedEvent(); - } - - public boolean argStoreCheck() { - if (storedInternalNodeHeights.getDimension() == this.internalNodeCount) - return true; - return false; - } - - /** - * Copies the node connections from this ARGModel's nodes array to the - * destination array. Basically it connects up the nodes in destination in - * the same way as this ARGModel is set up. This method is package private. - */ - void copyNodeStructure(ArrayList destination) { - - // if ( nodes.length != destination.length ) { - // throw new IllegalArgumentException("Node arrays are of different - // lengths"); - // } - while (destination.size() < nodes.size()) - destination.add(new Node()); - while (destination.size() > nodes.size()) - destination.remove(0); - int n = nodes.size(); - // System.err.println("node.size = "+n); - for (int i = 0; i < n; i++) { - // for( Node node0 : nodes ) { - Node node0 = nodes.get(i); - Node node1 = destination.get(i); - - // the parameter values are automatically stored and restored - // just need to keep the links - node1.heightParameter = node0.heightParameter; - node1.rateParameter = node0.rateParameter; - node1.traitParameter = node0.traitParameter; - node1.partitioning = node0.partitioning; - - node1.taxon = node0.taxon; - node1.bifurcation = node0.bifurcation; - node1.number = node0.number; - node1.myHashCode = node0.myHashCode; - // node1.partitionSet = (BitSet)node0.partitionSet.clone(); - // if (node0.leftPartition != null) { - // node1.leftPartition = (BitSet) node0.leftPartition.clone(); - // } else { - // node1.leftPartition = null; - // } - // if (node0.rightPartition != null) { - // node1.rightPartition = (BitSet) node0.rightPartition.clone(); - // } else { - // node1.rightPartition = null; - // } - // - - if (node0.leftParent != null) { - node1.leftParent = // storedNodes.get(node0.leftParent.getNumber()); - storedNodes.get(nodes.indexOf(node0.leftParent)); - } else { - node1.leftParent = null; - } - - if (node0.rightParent != null) { - node1.rightParent = // storedNodes.get(node0.rightParent.getNumber()); - storedNodes.get(nodes.indexOf(node0.rightParent)); - } else { - node1.rightParent = null; - } - - if (node0.leftChild != null) { - node1.leftChild = // storedNodes.get(node0.leftChild.getNumber()); - storedNodes.get(nodes.indexOf(node0.leftChild)); - } else { - node1.leftChild = null; - } - - if (node0.rightChild != null) { - node1.rightChild = // storedNodes.get(node0.rightChild.getNumber()); - storedNodes.get(nodes.indexOf(node0.rightChild)); - } else { - node1.rightChild = null; - } - } - } - - public void setPartitionRecursively(NodeRef nr, int partition) { - Node node = (Node) nr; - node.setPartitionRecursively(partition); - } - - /** - * @return the number of statistics of this component. - */ - public int getStatisticCount() { - return 1; - } - - /** - * @return the ith statistic of the component - */ - public Statistic getStatistic(int i) { - if (i == 0) - return root.heightParameter; - throw new IllegalArgumentException(); - } - - public String getModelComponentName() { - return TREE_MODEL; - } - - // ************************************************************** - // TaxonList IMPLEMENTATION - // ************************************************************** - - /** - * @return a count of the number of taxa in the list. - */ - public int getTaxonCount() { - return getExternalNodeCount(); - } - - /** - * @return the ith taxon in the list. - */ - public Taxon getTaxon(int taxonIndex) { - return ((Node) getExternalNode(taxonIndex)).taxon; - } - - /** - * @return the ID of the taxon of the ith external node. If it doesn't have - * a taxon, returns the ID of the node itself. - */ - public String getTaxonId(int taxonIndex) { - Taxon taxon = getTaxon(taxonIndex); - if (taxon != null) { - return taxon.getId(); - } else { - return null; - } - } - - /** - * returns the index of the taxon with the given id. - */ - public int getTaxonIndex(String id) { - for (int i = 0, n = getTaxonCount(); i < n; i++) { - if (getTaxonId(i).equals(id)) - return i; - } - return -1; - } - - /** - * returns the index of the given taxon. - */ - public int getTaxonIndex(Taxon taxon) { - for (int i = 0, n = getTaxonCount(); i < n; i++) { - if (getTaxon(i) == taxon) - return i; - } - return -1; - } - - public List asList() { - List taxa = new ArrayList(); - for (int i = 0, n = getTaxonCount(); i < n; i++) { - taxa.add(getTaxon(i)); - } - return taxa; - } - - public Iterator iterator() { - return new Iterator() { - private int index = -1; - - public boolean hasNext() { - return index < getTaxonCount() - 1; - } - - public Taxon next() { - index++; - return getTaxon(index); - } - - public void remove() { /* do nothing */ } - }; - } - - /** - * @param taxonIndex the index of the taxon whose attribute is being fetched. - * @param name the name of the attribute of interest. - * @return an object representing the named attributed for the taxon of the - * given external node. If the node doesn't have a taxon then the - * nodes own attribute is returned. - */ - public final Object getTaxonAttribute(int taxonIndex, String name) { - Taxon taxon = getTaxon(taxonIndex); - if (taxon != null) { - return taxon.getAttribute(name); - } - return null; - } - - // ************************************************************** - // MutableTaxonList IMPLEMENTATION - // ************************************************************** - - public int addTaxon(Taxon taxon) { - throw new IllegalArgumentException("Cannot add taxon to a ARGModel"); - } - - public boolean removeTaxon(Taxon taxon) { - throw new IllegalArgumentException("Cannot add taxon to a ARGModel"); - } - - public void setTaxonId(int taxonIndex, String id) { - throw new IllegalArgumentException("Cannot set taxon id in a ARGModel"); - } - - public void setTaxonAttribute(int taxonIndex, String name, Object value) { - throw new IllegalArgumentException( - "Cannot set taxon attribute in a ARGModel"); - } - - public void addMutableTreeListener(MutableTreeListener listener) { - } // Do nothing at the moment - - public void addMutableTaxonListListener(MutableTaxonListListener listener) { - } // Do nothing at the moment - - // ************************************************************** - // Identifiable IMPLEMENTATION - // ************************************************************** - - protected String id = null; - - /** - * @return the id. - */ - public String getId() { - return id; - } - - /** - * Sets the id. - */ - public void setId(String id) { - this.id = id; - } - - // ************************************************************** - // Attributable IMPLEMENTATION - // ************************************************************** - - private Attributable.AttributeHelper treeAttributes = null; - - /** - * Sets an named attribute for this object. - * - * @param name the name of the attribute. - * @param value the new value of the attribute. - */ - public void setAttribute(String name, Object value) { - if (treeAttributes == null) - treeAttributes = new Attributable.AttributeHelper(); - treeAttributes.setAttribute(name, value); - } - - /** - * @param name the name of the attribute of interest. - * @return an object representing the named attributed for this object. - */ - public Object getAttribute(String name) { - if (treeAttributes == null) - return null; - else - return treeAttributes.getAttribute(name); - } - - /** - * @return an iterator of the attributes that this object has. - */ - public Iterator getAttributeNames() { - if (treeAttributes == null) - return null; - else - return treeAttributes.getAttributeNames(); - } - - /** - * @return a string containing a newick representation of the tree - */ - public final String getNewick(int partition) { - return TreeUtils.newick(new ARGTree(this, partition)); - // return Tree.Utils.newick(this); - } - - /** - * Checks whether ARGMode is in edit mode. - * - * @throws RuntimeException if the ARGModel is not in edit mode. - */ - private void checkEditMode() throws RuntimeException { - if (!inEdit) - throw new RuntimeException("Not in edit transaction mode!"); - } - - public void checkBranchSanity() { - boolean plotted = false; - for (Node node : nodes) { - if (!node.isRoot()) { - double length1 = 0; - double length2 = 0; - if (node.leftParent != null) - length1 = getNodeHeight(node.leftParent) - - getNodeHeight(node); - if (node.rightParent != null) - length2 = getNodeHeight(node.rightParent) - - getNodeHeight(node); - if (String.valueOf(length1).equals("NaN") - || String.valueOf(length2).equals("NaN")) { - if (!plotted) { - System.err.println(toGraphString()); - plotted = true; - } - System.err.println("Caught the NaN: node=" + node.number - + " (" + node.getHeight() + ") lp=" - + node.leftParent.number + " (" - + node.leftParent.getHeight() + ") rp=" - + node.rightParent.number + " (" - + node.rightParent.getHeight() + ")"); - System.exit(-1); - } - } - } - - } - - /** - * @return a string containing an extended newick representation of the tree - */ - public String toString() { - // StringBuffer sb = new StringBuffer(); - // for (int i = 0; i < maxNumberOfPartitions; i++) { - // sb.append(i + ": "); - // sb.append(getNewick(i)); - // } - // return new String(sb); - return toExtendedNewick(); - } - - public static final String nullEdge = " -"; - - public void appendGraphStringOld(StringBuffer sb) { - int cnt = 0; - - for (Node node : nodes) - node.number = cnt++; - - cnt = 0; - for (Node node : nodes) { - sb.append(cnt == 0 ? "[" : ",["); - cnt++; - sb.append(node.number + ":"); - - if (node.leftParent == null) - sb.append(nullEdge); - else - sb.append(" " + node.leftParent.number); - - if (node.rightParent == null) - sb.append(nullEdge); - else - sb.append(" " + node.rightParent.number); - - if (node.leftChild == null) - sb.append(nullEdge); - else - sb.append(" " + node.leftChild.number); - - if (node.rightChild == null) - sb.append(nullEdge); - else - sb.append(" " + node.rightChild.number); - // sb.append(" " + node.bifurcation); - if (node.taxon != null) - sb.append(" " + node.taxon.toString()); - // if (node.leftPartition != null) - // sb.append(" l"); - // if (node.rightPartition != null) - // sb.append(" r"); - sb.append("]"); - // - // ); - } - // sb.append("Root = " + ((Node) getRoot()).number + "\n"); - // sb.append("\n"); - } - - public boolean validRoot() { - // todo -- there must be a way to some graph properties to do this - // check. - boolean valid = true; - for (int i = 0; valid && i < maxNumberOfPartitions; i++) { - ARGTree argTree = new ARGTree(this, i); - if (argTree.wasRootTrimmed()) - valid = false; - } - return valid; - } - - public String toGraphString() { - int cnt = 1; - for (Node node : nodes) { - node.number = cnt; - cnt++; - } - StringBuffer sb = new StringBuffer(); - sb.append("Total length: " + nodes.size() + "\n"); - for (Node node : nodes) { - sb.append(node.number + ":"); - - if (node.leftParent == null) - sb.append(" 0"); - else - sb.append(" " + node.leftParent.number); - - if (node.rightParent == null) - sb.append(" 0"); - else - sb.append(" " + node.rightParent.number); - - if (node.leftChild == null) - sb.append(" 0"); - else - sb.append(" " + node.leftChild.number); - - if (node.rightChild == null) - sb.append(" 0"); - else - sb.append(" " + node.rightChild.number); - // sb.append(" " + node.bifurcation); - if (node.taxon != null) - sb.append(" " + node.taxon.toString()); - if (node.partitioning != null) - sb.append(" p"); - /* - * if (node.leftPartition != null) sb.append(" l"); if - * (node.rightPartition != null) sb.append(" r"); - */ - sb.append("\t" + getNodeHeight(node)); - sb.append("\n"); - } - sb.append("Root = " + ((Node) getRoot()).number + "\n"); - return new String(sb); - } - - public ARGModel fromGraphStringCompressed(String source) { - StringTokenizer st1 = new StringTokenizer(source, ":"); - int numberNodes = Integer.parseInt(st1.nextToken()); - int numberPartitions = Integer.parseInt(st1.nextToken()); - int rootNumber = Integer.parseInt(st1.nextToken()); - int external = 0; - - ArrayList nodes = new ArrayList(); - for (int i = 0; i < numberNodes; i++) { - Node node = new Node(); - node.number = i; - nodes.add(node); - } - - for (int i = 0; i < numberNodes; i++) { - String nodeString = st1.nextToken(); - StringTokenizer st2 = new StringTokenizer(nodeString); - Node node = nodes.get(i); - int lP = Integer.parseInt(st2.nextToken()); - int rP = Integer.parseInt(st2.nextToken()); - int lC = Integer.parseInt(st2.nextToken()); - int rC = Integer.parseInt(st2.nextToken()); - if (lP != -1) - node.leftParent = nodes.get(lP); - if (rP != -1) - node.rightParent = nodes.get(rP); - if (lC != -1) - node.leftChild = nodes.get(lC); - if (rC != -1) - node.rightChild = nodes.get(rC); - double height = Double.parseDouble(st2.nextToken()); - node.heightParameter = new Parameter.Default(height); - String name = st2.nextToken(); - if (name.compareTo("NA") != 0) { - node.taxon = new Taxon(name); // todo saveList - external++; - } - String p = st2.nextToken(); - if (p.compareTo("NA") == 0) - node.bifurcation = true; - else { - node.bifurcation = false; - node.partitioning = new Parameter.Default(numberPartitions, 0.0); - node.partitioning.setParameterValueQuietly(Integer.parseInt(p), - 1.0); - while (st2.hasMoreTokens()) - node.partitioning.setParameterValueQuietly(Integer - .parseInt(st2.nextToken()), 1.0); - } - } - - return new ARGModel(nodes, nodes.get(rootNumber), numberPartitions, - external); - - // return null; - } - - - /** - * Gives a summary of the ARG model. Should only - * be used for debugging purposes because it's really slow. - * - * @return a summary of the ARG model. - */ - public String toARGSummary() { - NumberFormatter format = new NumberFormatter(4); - - String space = " "; - - String a = "----------------------\n" + - "ARG Summary \n---------------------- \n"; - - a += "Number of nodes: " + nodes.size() + "\n"; - a += "Number of partitions: " + maxNumberOfPartitions + "\n"; - a += "Number of Reassorments: " + this.getReassortmentNodeCount() + "\n"; - a += "Root number: " + getRoot().getNumber() + "\n"; - a += "Node Summary" - + "\n----------------------------------------\n" + - "ID LP RP LC RC Height" + space + "TX \n" + - "----------------------------------------\n"; - - for (Node node : nodes) { - a += node.getNumber() + space; - - if (node.leftParent == null) a += "-1" + space; - else a += " " + node.leftParent.number + space; - if (node.rightParent == null) a += "-1" + space; - else a += " " + node.rightParent.number + space; - if (node.leftChild == null) a += "-1" + space; - else a += " " + node.leftChild.number + space; - if (node.rightChild == null) a += "-1" + space; - else a += " " + node.rightChild.number + space; - - a += format.formatDecimal(getNodeHeight(node), 4) + space; - - if (node.partitioning != null) { - for (int i = 0, n = getNumberOfPartitions(); i < n; i++) { - a += node.partitioning.getParameterValue(i) + space; - } - } - - if (node.taxon == null) { - a += "internal" + space; - } else { - a += node.taxon + space; - } - a += "\n"; - } - a += "\nInduced Trees" + - "\n----------------------------------------\n"; -// for(int i = 0; i < maxNumberOfPartitions; i++){ -// ARGTree tree = new ARGTree(this,i); -// a += "Partition " + i + "\n " + tree.toString() + "\n"; -// } - - return a; - } - - public String toGraphStringCompressed(boolean recurse) { - int cnt = 0; - for (Node node : nodes) { - node.number = cnt; - cnt++; - } - StringBuffer sb = new StringBuffer(); - // sb.append("Total length: " + nodes.size() + "\n"); - sb.append(nodes.size()); - sb.append(":"); - sb.append(maxNumberOfPartitions); - sb.append(":"); - sb.append(getRoot().getNumber()); - for (Node node : nodes) { - sb.append(":"); - - if (node.leftParent == null) - sb.append(" -1"); - else - sb.append(" " + node.leftParent.number); - - if (node.rightParent == null) - sb.append(" -1"); - else - sb.append(" " + node.rightParent.number); - - if (node.leftChild == null) - sb.append(" -1"); - else - sb.append(" " + node.leftChild.number); - - if (node.rightChild == null) - sb.append(" -1"); - else - sb.append(" " + node.rightChild.number); - sb.append(" " + getNodeHeight(node)); - // sb.append(" " + node.bifurcation); - if (node.taxon != null) - sb.append(" " + node.taxon.toString()); - else - sb.append(" NA"); - if (node.partitioning != null) { - // sb.append(" p"); - double[] bits = node.partitioning.getParameterValues(); - for (int i = 0; i < bits.length; i++) { - if (bits[i] == 1) { - sb.append(" " + i); - } - } - - } else { - sb.append(" NA"); - } - - /* - * if (node.leftPartition != null) sb.append(" l"); if - * (node.rightPartition != null) sb.append(" r"); - */ - // sb.append("\t" + getNodeHeight(node)); - // sb.append("\n"); - } - // sb.append("Root = " + ((Node) getRoot()).number + "\n"); - - String rtn = new String(sb); - - /* - * if ( recurse ) { ARGModel test = fromGraphStringCompressed(rtn); - * System.err.println("OLD 0: "+getNewick(0)); System.err.println("NEW - * 0: "+test.getNewick(0)); System.err.println("OLD: - * "+toGraphStringCompressed(false)); System.err.println("NEW: - * "+test.toGraphStringCompressed(false)); } - */ - - return new String(sb); - } - - public Tree getCopy() { - throw new UnsupportedOperationException( - "please don't call this function"); - } - - // ************************************************************** - // XMLElement IMPLEMENTATION - // ************************************************************** - - public Element createElement(Document document) { - throw new RuntimeException("Not implemented yet"); - } - - - // *********************************************************************** - // Private methods - // *********************************************************************** - - /** - * @return the node that this parameter is a member of - */ - protected Node getNodeOfParameter(Parameter parameter) { - - if (parameter == null) - throw new IllegalArgumentException("Parameter is null!"); - - // for (int i =0; i < nodes.length; i++) { - for (Node node : nodes) { - if (node.heightParameter == parameter) { - return node; - } - if (hasRates && node.rateParameter == parameter) { - return node; - } - if (hasTraits && node.traitParameter == parameter) { - return node; - } - } - throw new RuntimeException("Parameter not found in any nodes:" - + parameter.getId()); - } - - /** - * Get the root height parameter. Is private because it can only be called - * by the XMLParser - */ - public Parameter getRootHeightParameter() { - - return root.heightParameter; - } - - /** - * @return the relevant node height parameter. Is private because it can - * only be called by the XMLParser - */ - public Parameter createNodeHeightsParameter(boolean rootNode, - boolean internalNodes, boolean leafNodes) { - - if (!rootNode && !internalNodes && !leafNodes) { - throw new IllegalArgumentException( - "At least one of rootNode, internalNodes or leafNodes must be true"); - } - - CompoundParameter parameter = new CompoundParameter("nodeHeights"); - // System.err.println("Constructed nodeHeights"); - for (int i = externalNodeCount; i < nodeCount; i++) { - Node node = nodes.get(i); - if ((rootNode && node == root) || (internalNodes && node != root)) { - parameter.addParameter(node.heightParameter); - } - } - - if (leafNodes) { - for (int i = 0; i < externalNodeCount; i++) { - parameter.addParameter(nodes.get(i).heightParameter); - } - } - - return parameter; - } - - public Parameter getLeafHeightParameter(NodeRef nr) { - Node node = (Node) nr; - if (!isExternal(node)) { - throw new RuntimeException( - "only root and leaves can be used with setNodeHeightParameter"); - } - - return nodes.get(nodes.indexOf(node)).heightParameter; - } - - /** - * @return the relevant node rate parameter. Is private because it can only - * be called by the XMLParser - */ - public Parameter createNodeRatesParameter(boolean rootNode, - boolean internalNodes, boolean leafNodes, int numberPartitions) { - - if (!rootNode && !internalNodes && !leafNodes) { - throw new IllegalArgumentException( - "At least one of rootNode, internalNodes or leafNodes must be true"); - } - - CompoundParameter parameter = new CompoundParameter(TreeModelParser.NODE_RATES); - - hasRates = true; - - for (int i = externalNodeCount; i < nodeCount; i++) { - Node node = nodes.get(i); - node.createRateParameter(numberPartitions); - if ((rootNode && node == root) || (internalNodes && node != root)) { - parameter.addParameter(node.rateParameter); - } - } - - for (int i = 0; i < externalNodeCount; i++) { - Node node = nodes.get(i); - node.createRateParameter(numberPartitions); - if (leafNodes) { - parameter.addParameter(node.rateParameter); - } - } - - return parameter; - } - - /** - * Create a node traits parameter. Is private because it can only be called - * by the XMLParser - */ - public Parameter createNodeTraitsParameter(boolean rootNode, - boolean internalNodes, boolean leafNodes) { - - if (!rootNode && !internalNodes && !leafNodes) { - throw new IllegalArgumentException( - "At least one of rootNode, internalNodes or leafNodes must be true"); - } - - CompoundParameter parameter = new CompoundParameter(TreeModelParser.NODE_TRAITS); - - hasTraits = true; - - for (int i = externalNodeCount; i < nodeCount; i++) { - Node node = nodes.get(i); - node.createTraitParameter(); - if ((rootNode && node == root) || (internalNodes && node != root)) { - parameter.addParameter(node.traitParameter); - } - } - - for (int i = 0; i < externalNodeCount; i++) { - Node node = nodes.get(i); - node.createTraitParameter(); - if (leafNodes) { - parameter.addParameter(node.traitParameter); - } - } - - return parameter; - } - - /** - * This method swaps the parameter objects of the two nodes but maintains - * the values in each node. This method is used to ensure that root node of - * the tree always has the same parameter object. - */ - private void swapParameterObjects(Node n1, Node n2) { - - double height1 = n1.getHeight(); - double height2 = n2.getHeight(); - - double rate1 = 1.0, rate2 = 1.0; - double trait1 = 0.0, trait2 = 0.0; - - if (hasRates) { - System.exit(-1); - - rate1 = n1.getRate(0); - rate2 = n2.getRate(0); - } - - if (hasTraits) { - trait1 = n1.getTrait(); - trait2 = n2.getTrait(); - } - - Parameter temp = n1.heightParameter; - n1.heightParameter = n2.heightParameter; - n2.heightParameter = temp; - - if (hasRates) { - temp = n1.rateParameter; - n1.rateParameter = n2.rateParameter; - n2.rateParameter = temp; - } - - if (hasTraits) { - temp = n1.traitParameter; - n1.traitParameter = n2.traitParameter; - n2.traitParameter = temp; - } - - n1.heightParameter.setParameterValueQuietly(0, height1); - n2.heightParameter.setParameterValueQuietly(0, height2); - - if (hasRates) { - n1.rateParameter.setParameterValueQuietly(0, rate1); - n2.rateParameter.setParameterValueQuietly(0, rate2); - } - - if (hasTraits) { - n1.traitParameter.setParameterValueQuietly(0, trait1); - n2.traitParameter.setParameterValueQuietly(0, trait2); - } - - } - - // ************************************************************** - // Private inner classes - // ************************************************************** - public class Node implements NodeRef { - - public boolean[] ancestralMaterial; - public boolean fullAncestralMaterial; - public boolean hasSomeAncestralMaterial; - - public boolean hasReassortmentAncestor() { - Node a = this; - - while (a != null) { - if (!a.bifurcation) { - return true; - } else { - a = a.leftParent; - } - } - - - return false; - } - - public void setAncestralMaterial(boolean[] childAncestralMaterial) { - if (fullAncestralMaterial) { - return; - } - - fullAncestralMaterial = true; - - for (int i = 0; i < ancestralMaterial.length; i++) { - ancestralMaterial[i] = ancestralMaterial[i] || childAncestralMaterial[i]; - - fullAncestralMaterial = fullAncestralMaterial && ancestralMaterial[i]; - hasSomeAncestralMaterial = hasSomeAncestralMaterial || ancestralMaterial[i]; - } - - if (bifurcation) { - if (this.leftParent != null) - this.leftParent.setAncestralMaterial(ancestralMaterial); - } else { - boolean[] leftAncestralMaterial = new boolean[ancestralMaterial.length]; - boolean[] rightAncestralMaterial = new boolean[ancestralMaterial.length]; - - System.arraycopy(ancestralMaterial, 0, leftAncestralMaterial, 0, leftAncestralMaterial.length); - System.arraycopy(ancestralMaterial, 0, rightAncestralMaterial, 0, rightAncestralMaterial.length); - - for (int i = 0; i < ancestralMaterial.length; i++) { - if (partitioning.getParameterValue(i) == 0.0) { - rightAncestralMaterial[i] = false; - } else { - leftAncestralMaterial[i] = false; - } - } - - this.leftParent.setAncestralMaterial(leftAncestralMaterial); - this.rightParent.setAncestralMaterial(rightAncestralMaterial); - } - } - - - public int myHashCode = 0; - - public int hashCode() { - if (myHashCode == 0) { - myHashCode = super.hashCode(); - } - return myHashCode; - } - - public boolean equals(Object o) { - return hashCode() == o.hashCode(); - } - - - public NodeRef mirrorNode; - - public Node leftParent, rightParent; - - public Node leftChild, rightChild; - - public int number; - - public Parameter heightParameter; - - //First half of the rate parameter represent the rates - //Second half represents 0-1 indicators - - public Parameter rateParameter = null; - - public Parameter traitParameter = null; - - public Taxon taxon = null; - - // public BitSet leftPartition = null; - // public BitSet rightPartition = null; - // public Node dupSister = null; - // public Node linkSister = null; - // public Node dupParent = null; - - // public Node leftParent; - // public Node rightParent; - - // public int leftPartition; - // public int rightPartition; - - public Parameter partitioning; - - public boolean bifurcation = true; - - public int countReassortmentChild(Tree tree) { - // int cnt = 0; - if (isExternal()) - return 0; - // if( leftChild == null ) { - // System.err.println("left is null"); - // System.err.println("is reassort = "+isReassortment()); - // System.err.println("right child = "+Tree.Utils.uniqueNewick(tree, - // rightChild)); - // } - // if( rightChild == null ) { - // System.err.println("right is null"); - // System.err.println("is reassort = "+isReassortment()); - // System.err.println("left child = "+Tree.Utils.uniqueNewick(tree, - // leftChild)); - // } - if (isReassortment()) { - return 1 + leftChild.countReassortmentChild(tree); - } else if (isBifurcationDoublyLinked()) { - return leftChild.countReassortmentChild(tree); - } else { - return leftChild.countReassortmentChild(tree) - + rightChild.countReassortmentChild(tree); - } - } - - public Node() { - leftParent = rightParent = null; - leftChild = rightChild = null; - heightParameter = null; - number = 0; - taxon = null; - // leftPartition = null; - // rightPartition = null; - partitioning = null; - } - - /** - * Constructor to build an ARG into a bifurcating tree - * - * @param node - */ - public Node(Node node) { - leftParent = rightParent = null; - leftChild = rightChild = null; - heightParameter = node.heightParameter; - taxon = node.taxon; - number = node.number; - // if( node.isReassortment() ) { - // Node parent = leftParent; - // parent.removeChild(this); - // return new Node(leftChild); - // } else { - if (node.leftChild != null) { - if (node.leftChild.isReassortment()) - singleAddChild(new Node(node.leftChild.leftChild)); - else - singleAddChild(new Node(node.leftChild)); - } - if (node.rightChild != null) { - if (node.rightChild.isReassortment()) - singleAddChild(new Node(node.rightChild.leftChild)); - else - singleAddChild(new Node(node.rightChild)); - } - // } - } - - /** - * constructor used to clone a node and all children with no - * reassortments - */ - public Node(Tree tree, NodeRef node) { - leftParent = rightParent = null; - leftChild = rightChild = null; - // leftPartition = new BitSet(); - // leftPartition.set(0); - // leftPartition = null; - // rightPartition = new BitSet(); - // rightPartition.set(0); - // rightPartition = null; - partitioning = null; - heightParameter = new Parameter.Default(tree.getNodeHeight(node)); - addVariable(heightParameter); - - number = node.getNumber(); - taxon = tree.getNodeTaxon(node); - - for (int i = 0; i < tree.getChildCount(node); i++) { - singleAddChild(new Node(tree, tree.getChild(node, i))); - } - // System.err.println("Built initial tree"); - // System.exit(-1); - } - - // public Node(Node node, int partition) - // { - // leftParent = rightParent = null; - // leftChild = rightChild = null; - // leftPartition = node.leftPartition; - // rightPartition = node.rightPartition; - // //leftPartition = rightPartition = null; - // heightParameter = node.heightParameter; - // number = node.number; - // taxon = node.taxon; - // bifurcation = node.bifurcation; - // // System.err.println("Examinging "+number); - // Node left; - // if( node.leftChild != null ) { - // Node left = node.getChild(0,partition); - // } - // Node right; - // if( node.rightChild != null ) { - // Node right = node.getChild(1,partition); - // } - // - // if( left != null ) { - // // System.err.println("Adding "+number+"->"+left.number); - // singleAddChild(new Node(left,partition)); - // } - // } - // - // if( right != null ) { - // // System.err.println("Adding "+number+"->"+right.number); - // singleAddChild(new Node(right,partition)); - // } - // } - // } - - public Node(Node inode, int partition) { //, ArrayList nodes) { - leftParent = rightParent = null; - leftChild = rightChild = null; - Node node = inode; - while (node.isBifurcationDoublyLinked()) { - node = node.leftChild.leftChild; - // System.err.println("Does this do anything?"); - } - heightParameter = node.heightParameter; - number = node.number; - taxon = node.taxon; - bifurcation = true; - - mirrorNode = node; - - if (node.isExternal()) -// nodes.add(this); - return; - else { - Node left, right; - left = node.getChild(0, partition); - right = node.getChild(1, partition); - if (left != null || right != null) { - if (left != null) { - singleAddChild(new Node(left, partition)); - } - if (right != null) { - singleAddChild(new Node(right, partition)); - } -// nodes.add(this); - } - } - } - - public void setPartitionRecursively(int partition) { - boolean onLeft = MathUtils.nextBoolean(); - if (leftChild != null) { - // if( leftPartition != null ) - // leftPartition.set(partition); - if (partitioning != null && onLeft) - partitioning.setParameterValue(partition, 1); - leftChild.setPartitionRecursively(partition); - } - if (rightChild != null) { - // if( leftPartition != null ) - // rightPartition.set(partition); - if (partitioning != null && !onLeft) - partitioning.setParameterValue(partition, 1); - rightChild.setPartitionRecursively(partition); - } - - } - - public void stripOutDeadEnds() { - if (leftChild != null) - leftChild.stripOutDeadEnds(); - if (rightChild != null && rightChild != leftChild) - rightChild.stripOutDeadEnds(); - if (taxon == null && leftChild == null && rightChild == null) - leftParent.doubleRemoveChild(this); - } - - public Node stripOutSingleChildNodes(Node cRoot) { - // Node rtn = cRoot; - int childCount = getChildCount(); - if (childCount == 0) { - return cRoot; - } - if (childCount == 2) { - if (hasEqualChildren()) { - return leftChild.stripOutSingleChildNodes(leftChild); - } - leftChild.stripOutSingleChildNodes(cRoot); - rightChild.stripOutSingleChildNodes(cRoot); - return cRoot; - } - if (isRoot()) { - if (leftChild != null) { - leftChild.leftParent = leftChild.rightParent = null; - return leftChild.stripOutSingleChildNodes(leftChild); - } else { - rightChild.leftParent = rightChild.rightParent = null; - return rightChild.stripOutSingleChildNodes(rightChild); - } - } - // System.err.println("Unlinking "+number); - Node parent = leftParent; - Node child = leftChild; - if (child == null) - child = rightChild; - parent.doubleRemoveChild(this); - doubleRemoveChild(child); - parent.singleAddChild(child); - return child.stripOutSingleChildNodes(cRoot); - } - - public final void setupHeightBounds() { - heightParameter.addBounds(new NodeHeightBounds(heightParameter)); - } - - - public final void createRateParameter(int numberPartitions) { - if (rateParameter == null) { - - double[] startingRateValues = new double[numberPartitions]; - - for (int i = 0; i < startingRateValues.length; i++) { - startingRateValues[i] = 1.0; - } - - rateParameter = new Parameter.Default(startingRateValues); - - if (isRoot()) { - rateParameter.setId("root.rate"); - } else if (isExternal()) { - rateParameter.setId(getTaxonId(getNumber()) + ".rate"); - } else { - rateParameter.setId("node" + getNumber() + ".rate"); - } - rateParameter.addBounds(new Parameter.DefaultBounds( - Double.POSITIVE_INFINITY, 0, startingRateValues.length)); - addVariable(rateParameter); - } - } - - public final void createTraitParameter() { - if (traitParameter == null) { - traitParameter = new Parameter.Default(1.0); - if (isRoot()) { - traitParameter.setId("root.trait"); - } else if (isExternal()) { - traitParameter.setId(getTaxonId(getNumber()) + ".trait"); - } else { - traitParameter.setId("node" + getNumber() + ".trait"); - } - rateParameter.addBounds(new Parameter.DefaultBounds( - Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, 1)); - - addVariable(traitParameter); - } - } - - public final double getHeight() { - return heightParameter.getParameterValue(0); - } - - public final double getRate(int partition) { - - - return rateParameter.getParameterValue(partition); - } - - public final double getTrait() { - return traitParameter.getParameterValue(0); - } - - public final void setHeight(double height) { - heightParameter.setParameterValue(0, height); - } - - public final void setRate(double rate) { - // System.out.println("Rate set for parameter " + - // rateParameter.getParameterName()); - rateParameter.setParameterValue(0, rate); - } - - public final void setTrait(double trait) { - // System.out.println("Trait set for parameter " + - // traitParameter.getParameterName()); - traitParameter.setParameterValue(0, trait); - } - - public int getNumber() { - return number; - } - - public void setNumber(int n) { - number = n; - } - - /** - * Returns the number of children this node has. - */ - public final int getChildCount() { - int n = 0; - if (leftChild != null) - n++; - if (rightChild != null && bifurcation) - n++; - return n; - } - - public final int getParentCount() { - int n = 0; - if (leftParent != null) - n++; - if (rightParent != null) - n++; - return n; - } - - public Node getChild(int n) { - if (n == 0) - return leftChild; - if (n == 1) - return rightChild; - throw new IllegalArgumentException( - "ARGModel.Nodes can only have up to 2 children"); - } - - - private boolean isBifurcationDoublyLinked() { - return bifurcation && (leftChild == rightChild) - && leftChild != null; - } - - private boolean recombinantIsLinked(Node parent, int partition) { - boolean left = leftParent == parent; - boolean right = rightParent == parent; - final double partitionSide = partitioning - .getParameterValue(partition); - if (left && partitionSide == 0) - return true; - if (right && partitionSide == 1) - return true; - return false; - - } - - public int getDescendentTipCount() { - if (isExternal()) - return 1; - return leftChild.getDescendentTipCount() - + rightChild.getDescendentTipCount(); - } - - public boolean checkForNullRights() { - if (isExternal()) - return false; - if (rightChild == null) - return true; - else - return rightChild.checkForNullRights() - || leftChild.checkForNullRights(); - } - - private Node findNextTreeNode(Node parent, int partition) { // searches - // down the - // ARG for - // the next - // bifurcation - // or tip - if (isExternal()) - return this; - Node next = this; - while (next.isReassortment()) { - if (recombinantIsLinked(parent, partition)) - return leftChild.findNextTreeNode(parent, partition); - else - return null; - } - // if( leftChild.findNextTreeMode()) - next = leftChild.findNextTreeNode(parent, partition); - if (next == null) - next = rightChild.findNextTreeNode(parent, partition); - if (next == null) // TODO Error check for removal - throw new IllegalArgumentException("Can't find next tree node."); - return next; - } - - private Node getChild(int n, int partition) { // Assuming an acyclic - // bifurcating tree - Node child = null; - if (n == 0) // Handle left side - child = leftChild; - if (n == 1) // Handle right side - child = rightChild; - if (child.isExternal()) - return child; - if (child.isBifurcationDoublyLinked()) { - // System.err.println("Passing double from - // "+number+"->"+child.leftChild.number); - return child.leftChild.getChild(0, partition); - } - if (child.isReassortment()) { - if (child.recombinantIsLinked(this, partition)) - return child.getChild(0, partition); - else - return null; - } - if (child.leftChild.isReassortment() - && child.rightChild.isReassortment()) { - if (child.leftChild.recombinantIsLinked(child, partition)) - return child; - if (child.rightChild.recombinantIsLinked(child, partition)) - return child; - return null; - } - return child; - } - - public Node getParent(int n) { - if (n == 0) - return leftParent; - if (n == 1) - return rightParent; - throw new IllegalArgumentException( - "ARGModel.Nodes can only have 2 parents"); - } - - public boolean hasChild(Node node) { - return (leftChild == node || rightChild == node); - } - - /** - * add new child node - * - * @param node new child node - */ - public void singleAddChild(Node node) { - if (leftChild == null) { - leftChild = node; - } else if (rightChild == null) { - rightChild = node; - } else { - throw new IllegalArgumentException( - "ARGModel.Nodes can only have 2 children"); - } - // if( node.leftParent == null ) - if (node.leftParent == null) - node.leftParent = this; - if (node.rightParent == null) - node.rightParent = this; - } - - public void singleAddChildWithOneParent(Node node) { - if (leftChild == null) { - leftChild = node; - } else if (rightChild == null) { - rightChild = node; - } else { - throw new IllegalArgumentException("ARGModel.Node " + number - + " can only have 2 children"); - } - // if( node.leftParent == null ) - if (node.leftParent == null) { - node.leftParent = this; - } else if (node.rightParent == null) { - node.rightParent = this; - } else { - throw new IllegalArgumentException( - "ARGModel.Nodes can only have 2 parents"); - } - } - - public void doubleAddChild(Node node) { - if (leftChild == null) { - leftChild = node; - } - if (rightChild == null) { - rightChild = node; - }// else { - // throw new IllegalArgumentException("ARGModel.Nodes can only have - // 2 children"); - // } - // if( node.leftParent == null ) - if (node.leftParent == null) - node.leftParent = this; - if (node.rightParent == null) - node.rightParent = this; - } - - public void doubleAddChildWithOneParent(Node node) { - if (leftChild == null) { - leftChild = node; - } - if (rightChild == null) { - rightChild = node; - }// else { - // throw new IllegalArgumentException("ARGModel.Nodes can only have - // 2 children"); - // } - if (node.leftParent == null) { - node.leftParent = this; - } else if (node.rightParent == null) { - node.rightParent = this; - } else { - throw new IllegalArgumentException( - "ARGModel.Nodes can only have 2 parents"); - } - } - - public void addChildNoParentConnection(Node node) { - if (leftChild == null) - leftChild = node; - else if (rightChild == null) - rightChild = node; - else - throw new IllegalArgumentException( - "Nodes can only have 2 children."); - } - - // public void addChild() - - // public void addChildRecombinant(Node node, BitSet partition) { - - public void addChildRecombinant(Node node, Parameter partition) { - // if( leftChild == null && rightChild == null ) { - // leftChild = rightChild = node; - // } else - // if( leftChild == null && rightChild == null ) { - // System.err.println("yep"); - // //System.exit(-1); - // leftChild = rightChild = node; - // } - if (leftChild == null) - leftChild = node; - // leftPartition = partition; - if (rightChild == null) - rightChild = node; - // rightPartition = partition; - // } else { - // throw new IllegalArgumentException("Nodes can only have 2 - // children."); - // } - // node.parent = null; - if (node.leftParent == null) { - node.leftParent = this; - // node.leftPartition = partition; - node.partitioning = partition; - } else if (node.rightParent == null) { - node.rightParent = this; - // node.rightPartition = partition; - node.partitioning = partition; - } else { - throw new IllegalArgumentException( - "Recombinant nodes can only have 2 parents."); - } - } - - /** - * remove child - * - * @param node child to be removed - */ - public Node doubleRemoveChild(Node node) { - boolean found = false; - if (leftChild == node) { - leftChild = null; - // leftPartition = null; - found = true; - } - if (rightChild == node) { - rightChild = null; - // rightPartition = null; - found = true; - } - if (!found) - throw new IllegalArgumentException("Unknown child node"); - if (node.leftParent == this) - node.leftParent = null; - // node.leftPartition = null; - if (node.rightParent == this) - node.rightParent = null; - // node.rightPartition = null; - return node; - } - - public Node singleRemoveChild(Node node) { - // boolean found = false; - if (leftChild == node) { - leftChild = null; - // leftPartition = null; - // found = true; - } else if (rightChild == node) { - rightChild = null; - // rightPartition = null; - // found = true; - } - // if( !found ) - else - throw new IllegalArgumentException("Unknown child node"); - if (node.bifurcation) { - node.leftParent = node.rightParent = null; - return null; - } - if (node.leftParent == this) - node.leftParent = null; - // node.leftPartition = null; - else if (node.rightParent == this) - node.rightParent = null; - // node.rightPartition = null; - return node; - } - - /** - * remove child - * - * @param n number of child to be removed - */ - public Node removeChild(int n) { - Node node; - if (n == 0) { - node = leftChild; - leftChild = null; - } else if (n == 1) { - node = rightChild; - rightChild = null; - } else { - throw new IllegalArgumentException( - "TreeModel.Nodes can only have 2 children"); - } - if (node.leftParent == this) - node.leftParent = null; - if (node.rightParent == this) - node.rightParent = null; - return node; - } - - public boolean hasChildren() { - return (leftChild != null || rightChild != null); - } - - public boolean isExternal() { - return !hasChildren(); - } - - public boolean isRoot() { - return (leftParent == null && rightParent == null); - } - - public boolean hasEqualChildren() { - return (leftChild == rightChild); - } - - public boolean isBifurcation() { - return bifurcation; - } - - // public boolean isReassortment() { return hasChildren() && (leftChild - // == rightChild); } - public boolean isReassortment() { - return !bifurcation; - } - - private String toExtendedNewick() { - - if (isExternal()) - return taxon.getId(); - - if (isBifurcation()) { - String left = leftChild.toExtendedNewick(); - String right = rightChild.toExtendedNewick(); - if (left.compareTo(right) < 0) - return "(" + left + "," + right + ")"; - else - return "(" + right + "," + left + ")"; - } - // must be a reassortment node - return "<" + leftChild.toExtendedNewick() + ">"; - } - - public String toString() { - if (taxon == null) { - return "" + number; - } - return "" + number + " (" + taxon.getId() + ")"; - } - } - - /** - * This class provides bounds for parameters that represent a node height in - * this tree model. - */ - private class NodeHeightBounds implements Bounds { - - public NodeHeightBounds(Parameter parameter) { - nodeHeightParameter = parameter; - } - - public Double getUpperLimit(int i) { - // I think only upper bounds are of concern with linked subtrees - // because everything below has only one parameter - // TODO -- check this! - Node node = getNodeOfParameter(nodeHeightParameter); - // Returns the first node in nodes[] with this height parameter - - if (node.isRoot()) { - return Double.POSITIVE_INFINITY; - // return 10.0; - } else { - if (node.leftParent == null) { - System.err.println("leftParent of " + node.number - + " is null"); - } - if (node.rightParent == null) { - System.err.println("rightParent of " + node.number - + " is null"); - } - return Math.min(node.leftParent.getHeight(), node.rightParent - .getHeight()); - } - } - - public Double getLowerLimit(int i) { - - Node node = getNodeOfParameter(nodeHeightParameter); - // System.err.println("Is node recombinant? - // "+node.isReassortment()); - if (node.isExternal()) { - return 0.0; - } else { - if (node.leftChild == null) - System.err.println("Node " + node.number - + " has null leftChild"); - if (node.rightChild == null) - System.err.println("Node " + node.number - + " has null rightChild"); - // System.err.println(node.number+" "+(node.leftChild==null)+" - // "+(node.rightChild==null)); - return Math.max(node.leftChild.getHeight(), node.rightChild - .getHeight()); - } - } - - public int getBoundsDimension() { - return 1; - } - - private Parameter nodeHeightParameter = null; - } - - public double getNodeRate(NodeRef node) { - if (true) - throw new RuntimeException("This should not be called"); - - return 0; - } - - /////////////////////////////////////////////////////////////////////// - //PARSER - /////////////////////////////////////////////////////////////////////// - - public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { - - public String getParserName() { - return TREE_MODEL; - } - - public String[] getParserNames() { - return new String[]{ - getParserName(), "argModel" - }; - } - - /** - * @return a tree object based on the XML element it was passed. - */ - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - Tree tree = (Tree) xo.getChild(Tree.class); - ARGModel treeModel = new ARGModel(tree); - - Logger.getLogger("dr.evomodel").info("Creating the tree model, '" + xo.getId() + "'"); - - if (xo.hasAttribute(PARTITION_TYPE)) { - treeModel.partitionType = xo.getStringAttribute(PARTITION_TYPE); - - if (!treeModel.partitionType.equals(REASSORTMENT_PARTITION) && - !treeModel.partitionType.equals(RECOMBINATION_PARTITION)) { - throw new XMLParseException("Must use either correct partition type"); - } - } - - int numberPartitions = 1; - - if (xo.hasAttribute(NUM_PARTITIONS)) { - numberPartitions = xo.getIntegerAttribute(NUM_PARTITIONS); - } - - - Logger.getLogger("dr.evomodel").info( - xo.getId() + " has partition type: " + treeModel.partitionType); - - for (int i = 0; i < xo.getChildCount(); i++) { - if (xo.getChild(i) instanceof XMLObject) { - - XMLObject cxo = (XMLObject) xo.getChild(i); - - if (cxo.getName().equals(ROOT_HEIGHT)) { - - ParameterParser.replaceParameter(cxo, treeModel - .getRootHeightParameter()); - - } else if (cxo.getName().equals(LEAF_HEIGHT)) { - - String taxonName; - if (cxo.hasAttribute(TAXON)) { - taxonName = cxo.getStringAttribute(TAXON); - } else { - throw new XMLParseException( - "taxa element missing from leafHeight element in treeModel element"); - } - - int index = treeModel.getTaxonIndex(taxonName); - if (index == -1) { - throw new XMLParseException( - "taxon " - + taxonName - + " not found for leafHeight element in treeModel element"); - } - NodeRef node = treeModel.getExternalNode(index); - ParameterParser.replaceParameter(cxo, treeModel - .getLeafHeightParameter(node)); - - } else if (cxo.getName().equals(NODE_HEIGHTS)) { - - boolean rootNode = false; - boolean internalNodes = false; - boolean leafNodes = false; - - if (cxo.hasAttribute(ROOT_NODE)) { - rootNode = cxo.getBooleanAttribute(ROOT_NODE); - } - - if (cxo.hasAttribute(INTERNAL_NODES)) { - internalNodes = cxo - .getBooleanAttribute(INTERNAL_NODES); - } - - if (cxo.hasAttribute(LEAF_NODES)) { - leafNodes = cxo.getBooleanAttribute(LEAF_NODES); - } - - if (!rootNode && !internalNodes && !leafNodes) { - throw new XMLParseException( - "one or more of root, internal or leaf nodes must be " + - "selected for the nodeHeights element"); - } - - ParameterParser.replaceParameter(cxo, treeModel - .createNodeHeightsParameter(rootNode, - internalNodes, leafNodes)); - - } else if (cxo.getName().equals(NODE_RATES)) { - - boolean rootNode = false; - boolean internalNodes = false; - boolean leafNodes = false; - - if (cxo.hasAttribute(ROOT_NODE)) { - rootNode = cxo.getBooleanAttribute(ROOT_NODE); - } - - if (cxo.hasAttribute(INTERNAL_NODES)) { - internalNodes = cxo - .getBooleanAttribute(INTERNAL_NODES); - } - - if (cxo.hasAttribute(LEAF_NODES)) { - leafNodes = cxo.getBooleanAttribute(LEAF_NODES); - } - - // if (rootNode) { - // throw new XMLParseException("root node does not have - // a rate parameter"); - // } - - if (!rootNode && !internalNodes && !leafNodes) { - throw new XMLParseException( - "one or more of root, internal or leaf nodes must be selected for the nodeRates element"); - } - - ParameterParser.replaceParameter(cxo, treeModel - .createNodeRatesParameter(rootNode, - internalNodes, leafNodes, numberPartitions)); - - } else if (cxo.getName().equals(NODE_TRAITS)) { - - boolean rootNode = false; - boolean internalNodes = false; - boolean leafNodes = false; - - if (cxo.hasAttribute(ROOT_NODE)) { - rootNode = cxo.getBooleanAttribute(ROOT_NODE); - } - - if (cxo.hasAttribute(INTERNAL_NODES)) { - internalNodes = cxo - .getBooleanAttribute(INTERNAL_NODES); - } - - if (cxo.hasAttribute(LEAF_NODES)) { - leafNodes = cxo.getBooleanAttribute(LEAF_NODES); - } - - if (!rootNode && !internalNodes && !leafNodes) { - throw new XMLParseException( - "one or more of root, internal or leaf nodes must be selected for the nodeTraits element"); - } - - ParameterParser.replaceParameter(cxo, treeModel - .createNodeTraitsParameter(rootNode, - internalNodes, leafNodes)); - - } else { - throw new XMLParseException("illegal child element in " - + getParserName() + ": " + cxo.getName()); - } - - } else if (xo.getChild(i) instanceof Tree) { - // do nothing - already handled - } else { - throw new XMLParseException("illegal child element in " - + getParserName() + ": " + xo.getChildName(i) + " " - + xo.getChild(i)); - } - } - - - treeModel.setupHeightBounds(); - - Logger.getLogger("dr.evomodel").info( - " initial tree topology = " - + TreeUtils.uniqueNewick(treeModel, treeModel - .getRoot())); - return treeModel; - } - - // ************************************************************************ - // AbstractXMLObjectParser implementation - // ************************************************************************ - - public String getParserDescription() { - return "This element represents a model of the tree. The tree model includes and attributes of the nodes " - + "including the age (or height) and the rate of evolution at each node in the tree."; - } - - public String getExample() { - return "\n" - + "\n" - + "\n" - + "\n" - + "\n" - + "\n" - + "\n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" + ""; - - } - - public Class getReturnType() { - return ARGModel.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private final String[] partitionFormats = {REASSORTMENT_PARTITION, RECOMBINATION_PARTITION}; - - private final XMLSyntaxRule[] rules = { - new StringAttributeRule(PARTITION_TYPE, "Describes the partition structure of the model", - partitionFormats, true), - new ElementRule(Tree.class), - new ElementRule( - ROOT_HEIGHT, - Parameter.class, - "A parameter definition with id only (cannot be a reference!)", - false), - new ElementRule( - NODE_HEIGHTS, - new XMLSyntaxRule[]{ - AttributeRule - .newBooleanRule(ROOT_NODE, true, - "If true the root height is included in the parameter"), - AttributeRule - .newBooleanRule( - INTERNAL_NODES, - true, - "If true the internal node heights (minus the root) are included in the parameter"), - new ElementRule(Parameter.class, - "A parameter definition with id only (cannot be a reference!)")}, - 1, Integer.MAX_VALUE)}; - - public Parameter oldGetParameter(XMLObject xo) throws XMLParseException { - // public Parameter getParameter(XMLObject xo) throws XMLParseException { - - - int paramCount = 0; - Parameter param = null; - for (int i = 0; i < xo.getChildCount(); i++) { - if (xo.getChild(i) instanceof Parameter) { - param = (Parameter) xo.getChild(i); - paramCount += 1; - } - } - - if (paramCount == 0) { - throw new XMLParseException( - "no parameter element in treeModel " + xo.getName() - + " element"); - } else if (paramCount > 1) { - throw new XMLParseException( - "More than one parameter element in treeModel " - + xo.getName() + " element"); - } - - return param; - } - - // todo check to make sure that Andrew's static routine works with this old code - public void oldReplaceParameter(XMLObject xo, Parameter newParam) -// public void replaceParameter(XMLObject xo, Parameter newParam) - - throws XMLParseException { - - for (int i = 0; i < xo.getChildCount(); i++) { - - if (xo.getChild(i) instanceof Parameter) { - - XMLObject rxo = null; - Object obj = xo.getRawChild(i); - - if (obj instanceof Reference) { - rxo = ((Reference) obj).getReferenceObject(); - } else if (obj instanceof XMLObject) { - rxo = (XMLObject) obj; - } else { - throw new XMLParseException( - "object reference not available"); - } - - if (rxo.getChildCount() > 0) { - throw new XMLParseException( - "No child elements allowed in parameter element."); - } - - if (rxo.hasAttribute(XMLParser.IDREF)) { - throw new XMLParseException("References to " - + xo.getName() - + " parameters are not allowed in treeModel."); - } - - if (rxo.hasAttribute(ParameterParser.VALUE)) { - throw new XMLParseException("Parameters in " - + xo.getName() - + " have values set automatically."); - } - - if (rxo.hasAttribute(ParameterParser.UPPER)) { - throw new XMLParseException("Parameters in " - + xo.getName() - + " have bounds set automatically."); - } - - if (rxo.hasAttribute(ParameterParser.LOWER)) { - throw new XMLParseException("Parameters in " - + xo.getName() - + " have bounds set automatically."); - } - - if (rxo.hasAttribute(XMLParser.ID)) { - - newParam.setId(rxo.getStringAttribute(XMLParser.ID)); - } - - rxo.setNativeObject(newParam); - - return; - } - } - } - }; - - -} diff --git a/src/dr/evomodel/arg/ARGPartitionLikelihood.java b/src/dr/evomodel/arg/ARGPartitionLikelihood.java deleted file mode 100644 index d820d972d4..0000000000 --- a/src/dr/evomodel/arg/ARGPartitionLikelihood.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * ARGPartitionLikelihood.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.arg; - -import dr.inference.model.AbstractModelLikelihood; -import dr.inference.model.Model; - -public abstract class ARGPartitionLikelihood extends AbstractModelLikelihood { - - - private final ARGModel arg; - - public abstract double[] generatePartition(); - public abstract double getLogLikelihood(double[] partition); - - public double getLogLikelihood() { - - double logPrior = 0; - - for(int i = 0, n = getReassortmentNodeCount(); i < n; i++){ - logPrior += getLogLikelihood(getPartition(i)); - } - - return logPrior; - } - - public double[] getPartition(int i){ - if(arg.getReassortmentNodeCount() == 0){ - return null; - } - - return arg.getPartitioningParameters().getParameter(i).getParameterValues(); - } - - public ARGPartitionLikelihood(String id, ARGModel arg){ - super(id); - - - this.arg = arg; - } - - public int getNumberOfPartitionsMinusOne(){ - return arg.getNumberOfPartitions() - 1; - } - - public int getReassortmentNodeCount(){ - return arg.getReassortmentNodeCount(); - } - - public Model getModel() { - return this; - } - - public void makeDirty() { - - } -} diff --git a/src/dr/evomodel/arg/ARGRatePrior.java b/src/dr/evomodel/arg/ARGRatePrior.java deleted file mode 100644 index ab88c73c74..0000000000 --- a/src/dr/evomodel/arg/ARGRatePrior.java +++ /dev/null @@ -1,184 +0,0 @@ -/* - * ARGRatePrior.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.arg; - -import dr.evomodel.arg.ARGModel.Node; -import dr.inference.model.AbstractModelLikelihood; -import dr.inference.model.Model; -import dr.inference.model.Parameter; -import dr.inference.model.Variable; -import dr.inference.model.Variable.ChangeType; -import dr.math.MathUtils; -import dr.math.distributions.GammaDistribution; -import dr.xml.*; - -public class ARGRatePrior extends AbstractModelLikelihood { - - public static final String ARG_RATE_PRIOR = "argRatePrior"; - public static final String SIGMA = "sigma"; - - private final ARGModel arg; - private final Parameter logNormalSigma; - - - public ARGRatePrior(String name, ARGModel arg, Parameter sigma) { - super(name); - - this.arg = arg; - this.logNormalSigma = sigma; - - addModel(arg); - addVariable(sigma); - - } - - public double[] generateValues() { - - double[] values = new double[arg.getNumberOfPartitions()]; - - double sigma = logNormalSigma.getParameterValue(0); - - double oneOverSigma = 1.0 / sigma; - - for (int i = 0; i < values.length; i++) { - values[i] = MathUtils.nextGamma(oneOverSigma, oneOverSigma); - } - - - return values; - } - - public double getLogLikelihood() { - return calculateLogLikelihood(); - } - - public double getAddHastingsRatio(double[] values) { - return -calculateLogLikelihood(values); - } - - - private double calculateLogLikelihood(double[] values) { - double logLike = 0; - - double sigma = logNormalSigma.getParameterValue(0); - double oneOverSigma = 1.0 / sigma; - - for (double d : values) { - logLike += GammaDistribution.logPdf(d, oneOverSigma, sigma); - } - - return logLike; - } - - private double calculateLogLikelihood() { - double logLike = 0; - - - for (int i = 0, n = arg.getNodeCount(); i < n; i++) { - Node x = (Node) arg.getNode(i); - - if (!x.isRoot() && x.isBifurcation()) { - - double[] values = x.rateParameter.getParameterValues(); - - logLike += calculateLogLikelihood(values); - } - } - - - return logLike; - } - - - public Model getModel() { - return this; - } - - public void makeDirty() { - - } - - public String getId() { - return super.getId(); - } - - public void setId(String id) { - super.setId(id); - } - - protected void acceptState() { - } - - protected void handleModelChangedEvent(Model model, Object object, int index) { - } - - protected void handleVariableChangedEvent(Variable variable, int index, - ChangeType type) { - } - - protected void restoreState() { - - } - - protected void storeState() { - } - - public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { - - public String getParserDescription() { - return null; - } - - public Class getReturnType() { - return ARGRatePrior.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return null; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - String id = xo.getAttribute(XMLParser.ID, ""); - - - Parameter sigma = (Parameter) xo.getChild(Parameter.class); - - - ARGModel arg = (ARGModel) xo.getChild(ARGModel.class); - - return new ARGRatePrior(id, arg, sigma); - } - - public String getParserName() { - return ARG_RATE_PRIOR; - } - - }; - - -} diff --git a/src/dr/evomodel/arg/ARGReassortmentNodeCountStatistic.java b/src/dr/evomodel/arg/ARGReassortmentNodeCountStatistic.java deleted file mode 100644 index 20a5c2a904..0000000000 --- a/src/dr/evomodel/arg/ARGReassortmentNodeCountStatistic.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * ARGReassortmentNodeCountStatistic.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.arg; - -import dr.inference.model.Statistic; -import dr.xml.*; - - -/** - * @author Marc Suchard - */ -public class ARGReassortmentNodeCountStatistic extends Statistic.Abstract { - - public static final String REASSORTMENT_STATISTIC = "argReassortmentNodeCount"; - - - public ARGReassortmentNodeCountStatistic(String name, ARGModel arg) { - super(name); - this.arg = arg; - } - - public int getDimension() { - return 1; - } - - public double getStatisticValue(int dim) { - return arg.getReassortmentNodeCount(); - } - - public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { - - public String getParserName() { - return REASSORTMENT_STATISTIC; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - String name = xo.getAttribute(NAME, xo.getId()); - ARGModel arg = (ARGModel) xo.getChild(ARGModel.class); - - return new ARGReassortmentNodeCountStatistic(name,arg); - } - - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - - public String getParserDescription() { - return "A statistic that returns the number of reassortment nodes in an ARG"; - } - - public Class getReturnType() { - return Statistic.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{ - new StringAttributeRule(NAME, "A name for this statistic for the purpose of logging", true), - new ElementRule(ARGModel.class), - }; - - }; - - - private ARGModel arg; - -} diff --git a/src/dr/evomodel/arg/ARGReassortmentTimingStatistic.java b/src/dr/evomodel/arg/ARGReassortmentTimingStatistic.java deleted file mode 100644 index f5546efe8d..0000000000 --- a/src/dr/evomodel/arg/ARGReassortmentTimingStatistic.java +++ /dev/null @@ -1,234 +0,0 @@ -/* - * ARGReassortmentTimingStatistic.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.arg; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.logging.Logger; - -import dr.evomodel.arg.ARGModel.Node; -import dr.evomodel.arg.operators.ARGPartitioningOperator.PartitionChangedEvent; - -import dr.inference.model.Parameter; -import dr.inference.model.Statistic; -import dr.math.MathUtils; -import dr.xml.AbstractXMLObjectParser; -import dr.xml.AttributeRule; -import dr.xml.ElementRule; -import dr.xml.XMLObject; -import dr.xml.XMLObjectParser; -import dr.xml.XMLParseException; -import dr.xml.XMLSyntaxRule; - -public class ARGReassortmentTimingStatistic extends Statistic.Abstract{ - - private int dimension; - private ARGModel arg; - - public static final String ARG_TIMING_STATISTIC = "argTimingStatistic"; - public static final String NUMBER_OF_REASSORTMENTS = "reassortments"; //TODO This is probably somewhere else in BEAST. - - public ARGReassortmentTimingStatistic(String name, ARGModel arg){ - super(name); - - - this.dimension = arg.getExternalNodeCount() + 1; - this.arg = arg; - } - - public int getDimension() { - return dimension; - } - - public String getDimensionName(int dim){ - if(dim == 0){ - return "Root"; - }else if(dim == 1){ - return "RootChild"; - }else if(dim == 2){ - return "ENParent"; - }else if(dim == 3){ - return "DNParent"; - }else if(dim == 4){ - return "DCParent"; - }else if(dim == 5){ - return "CCParent"; - }else if(dim == 6){ - return "FNParent"; - }else if(dim == 7){ - return "ReassortHeight"; - }else if(dim == 8){ - return "CNParent"; - }else if(dim == 9){ - return "CCParentParent"; - } - - return ""; - } - - public double getStatisticValue(int dim) { - String max = "((((((<(FC,FN)>,CN),CC),<(FC,FN)>),DC),((EC,EN),DN)),AN);"; - - - if(!arg.toExtendedNewick().equals(max)){ - return Double.NaN; - } - - if(dim == 0){ - return arg.getRootHeightParameter().getParameterValue(0); - }else if(dim == 1){ - Node a = (Node)arg.getRoot(); - - Node aLeft = a.leftChild; - Node aRight = a.rightChild; - - return Math.max(aLeft.heightParameter.getParameterValue(0), aRight.heightParameter.getParameterValue(0)); - }else if(dim == 2){ - int value = 0; - Node a = (Node)arg.getExternalNode(0); - - while(!a.taxon.toString().equals("EN")){ - value++; - a = (Node)arg.getExternalNode(value); - } - return a.leftParent.heightParameter.getParameterValue(0); - }else if(dim == 3){ - int value = 0; - Node a = (Node)arg.getExternalNode(0); - - while(!a.taxon.toString().equals("DN")){ - value++; - a = (Node)arg.getExternalNode(value); - } - return a.leftParent.heightParameter.getParameterValue(0); - }else if(dim == 4){ - int value = 0; - Node a = (Node)arg.getExternalNode(0); - - while(!a.taxon.toString().equals("DC")){ - value++; - a = (Node)arg.getExternalNode(value); - } - return a.leftParent.heightParameter.getParameterValue(0); - }else if(dim == 5){ - int value = 0; - Node a = (Node)arg.getExternalNode(0); - - while(!a.taxon.toString().equals("CC")){ - value++; - a = (Node)arg.getExternalNode(value); - } - return a.leftParent.heightParameter.getParameterValue(0); - }else if(dim == 6){ - int value = 0; - Node a = (Node)arg.getExternalNode(0); - - while(!a.taxon.toString().equals("FN")){ - value++; - a = (Node)arg.getExternalNode(value); - } - return a.leftParent.heightParameter.getParameterValue(0); - }else if(dim == 7){ - int value = 0; - Node a = (Node)arg.getExternalNode(0); - - while(!a.taxon.toString().equals("FN")){ - value++; - a = (Node)arg.getExternalNode(value); - } - return a.leftParent.leftParent.heightParameter.getParameterValue(0); - }else if(dim == 8){ - int value = 0; - Node a = (Node)arg.getExternalNode(0); - - while(!a.taxon.toString().equals("CN")){ - value++; - a = (Node)arg.getExternalNode(value); - } - return a.leftParent.heightParameter.getParameterValue(0); - } - - int value = 0; - Node a = (Node)arg.getExternalNode(0); - - while(!a.taxon.toString().equals("CC")){ - value++; - a = (Node)arg.getExternalNode(value); - } - return a.leftParent.leftParent.heightParameter.getParameterValue(0); - - - - - } - - - - - - public static XMLObjectParser PARSER = new AbstractXMLObjectParser(){ - - public String getParserDescription() { - - return ""; - } - - public Class getReturnType() { - - return ARGReassortmentTimingStatistic.class; - } - - - public XMLSyntaxRule[] getSyntaxRules() { - return new XMLSyntaxRule[]{ - new ElementRule(ARGModel.class,false), - AttributeRule.newStringRule(NAME,true), - }; - } - - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - String name = xo.getId(); -// int dim = xo.getIntegerAttribute(DIMENSION); - ARGModel arg = (ARGModel)xo.getChild(ARGModel.class); - - Logger.getLogger("dr.evomodel").info("Creating timing statistic"); - - return new ARGReassortmentTimingStatistic(name,arg); - } - - public String getParserName() { - return ARG_TIMING_STATISTIC; - } - - }; - - - -} - diff --git a/src/dr/evomodel/arg/ARGRelaxedClock.java b/src/dr/evomodel/arg/ARGRelaxedClock.java deleted file mode 100644 index 164ea8d806..0000000000 --- a/src/dr/evomodel/arg/ARGRelaxedClock.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * ARGRelaxedClock.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.arg; - -import dr.evolution.tree.NodeRef; -import dr.evolution.tree.Tree; -import dr.evomodel.arg.ARGModel.Node; -import dr.evomodel.branchratemodel.AbstractBranchRateModel; -import dr.inference.model.Model; -import dr.inference.model.Parameter; -import dr.inference.model.Variable; -import dr.inference.model.Variable.ChangeType; -import dr.xml.*; - -public class ARGRelaxedClock extends AbstractBranchRateModel { - - public static final String ARG_LOCAL_CLOCK = "argLocalClock"; - public static final String PARTITION = "partition"; - - private Parameter globalRateParameter; - - private ARGModel arg; - private int partition; - - - public ARGRelaxedClock(String name) { - super(name); - } - - public ARGRelaxedClock(String name, ARGModel arg, int partition, Parameter rate) { - super(name); - - this.arg = arg; - this.partition = partition; - - globalRateParameter = rate; - - addModel(arg); - addVariable(rate); - } - - protected void acceptState() { - - } - - protected void handleModelChangedEvent(Model model, Object object, int index) { - //do nothing - } - - - protected void handleVariableChangedEvent(Variable variable, int index, ChangeType type) { - //do nothing - } - - - protected void restoreState() { - - } - - - protected void storeState() { - - } - - public double getBranchRate(Tree tree, NodeRef nodeRef) { - - Node treeNode = (Node) nodeRef; - Node argNode = (Node) treeNode.mirrorNode; - - - return globalRateParameter.getParameterValue(0) * argNode.getRate(partition); - } - - public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { - - public String getParserDescription() { - return null; - } - - public Class getReturnType() { - - return ARGRelaxedClock.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - - return null; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - ARGModel arg = (ARGModel) xo.getChild(ARGModel.class); - - int partition = xo.getAttribute(PARTITION, 0); - - Parameter rate = (Parameter) xo.getChild(Parameter.class); - - return new ARGRelaxedClock("", arg, partition, rate); - } - - public String getParserName() { - return ARG_LOCAL_CLOCK; - } - - }; - -} diff --git a/src/dr/evomodel/arg/ARGTotalLengthStatistic.java b/src/dr/evomodel/arg/ARGTotalLengthStatistic.java deleted file mode 100644 index 8475193e68..0000000000 --- a/src/dr/evomodel/arg/ARGTotalLengthStatistic.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * ARGTotalLengthStatistic.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.arg; - -import dr.evomodel.arg.ARGModel.Node; -import dr.inference.model.Statistic; -import dr.xml.*; - -public class ARGTotalLengthStatistic extends Statistic.Abstract{ - - public static final String ARG_TOTAL_LENGTH = "argTotalLengthStatistic"; - private ARGModel arg; - - public ARGTotalLengthStatistic(String id, ARGModel arg){ - super(id); - - this.arg = arg; - } - - public int getDimension() { - return 1; - } - - public double getStatisticValue(int dim) { - - double length = 0; - - for(int i = 0; i < arg.getNodeCount(); i++){ - Node x = (Node) arg.getNode(i); - - if(!x.isRoot()){ - length += x.getParent(ARGModel.LEFT).getHeight() - x.getHeight(); - if(x.isReassortment()){ - length += x.getParent(ARGModel.RIGHT).getHeight() - x.getHeight(); - } - } - } - - return length; - } - - public static XMLObjectParser PARSER = new AbstractXMLObjectParser(){ - - @Override - public String getParserDescription() { - // TODO Auto-generated method stub - return null; - } - - @Override - public Class getReturnType() { - - return ARGTotalLengthStatistic.class; - } - - @Override - public XMLSyntaxRule[] getSyntaxRules() { - // TODO Auto-generated method stub - return null; - } - - @Override - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - String id = xo.getId(); - - ARGModel a = (ARGModel) xo.getChild(ARGModel.class); - - return new ARGTotalLengthStatistic(id,a); - } - - public String getParserName() { - // TODO Auto-generated method stub - return ARG_TOTAL_LENGTH; - } - - }; - -} diff --git a/src/dr/evomodel/arg/ARGTrace.java b/src/dr/evomodel/arg/ARGTrace.java deleted file mode 100644 index 53d478fdea..0000000000 --- a/src/dr/evomodel/arg/ARGTrace.java +++ /dev/null @@ -1,218 +0,0 @@ -/* - * ARGTrace.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.arg; - -import dr.evolution.io.Importer; -import dr.evolution.util.TaxonList; -import dr.util.Identifiable; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.Reader; -import java.util.ArrayList; -import java.util.StringTokenizer; - -/** - * Created by IntelliJ IDEA. - * User: msuchard - * Date: Jul 19, 2007 - * Time: 5:30:44 PM - * To change this template use File | Settings | File Templates. - */ - -public class ARGTrace implements Identifiable { - - public ARGTrace() { - } - - public int getTreeCount(int burnin) { - int startIndex = (burnin - minState) / stepSize; - if (startIndex < 0) { - startIndex = 0; - } - return args.size() - startIndex; - } - - public ARGModel getARG(int index, int burnin) { - int startIndex = (burnin - minState) / stepSize; - if (startIndex < 0) { - startIndex = 0; - } - return (ARGModel) args.get(index + startIndex); - } - - public void add(ARGModel arg) { - args.add(arg); - } - - public void setMinimumState(int minState) { - this.minState = minState; - } - - public int getMinimumState() { - return minState; - } - - public void setStepSize(int stepSize) { - this.stepSize = stepSize; - } - - public int getStepSize() { - return stepSize; - } - - public int getMaximumState() { - return (args.size() - 1) * stepSize + minState; - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - private ArrayList args = new ArrayList(); - - private int minState; - private int stepSize; - private String id; - - /** - * Loads the trace for with trees from a reader - * - * @return the TreeTrace - */ - public static ARGTrace loadARGTrace(Reader r) throws IOException, Importer.ImportException { - - BufferedReader reader = new BufferedReader(r); - - ARGTrace trace = new ARGTrace(); - - dr.evolution.util.TaxonList taxonList = null; - - int minState = -1; - int stepSize = 0; - - String line; - ARGModel nullARG = new ARGModel(null, null, 0, 0); - ArrayList nameList = new ArrayList(); - - taxonList = (TaxonList) nullARG; - - while ((line = reader.readLine()) != null) { - -// String line = reader.readLine(); - - line.trim(); - - if (line.toUpperCase().startsWith("ARG")) { - StringTokenizer st = new StringTokenizer(line, "="); - nameList.add(st.nextToken()); - ARGModel arg = nullARG.fromGraphStringCompressed(st.nextToken().trim()); - trace.add(arg); - - } - - } - - if (nameList.size() < 2) { - throw new Importer.ImportException("Less than two ARGs in the trace file"); - } - - minState = getStateNumber(nameList.get(0)); - stepSize = getStateNumber(nameList.get(1)) - minState; - -// if (line.toUpperCase().startsWith("#NEXUS")) { -// NexusImporter importer = new NexusImporter(reader); -// Tree [] trees = importer.importTrees(null); -// -// if (trees.length < 2) { -// throw new Importer.ImportException("Less than two trees in the trace file"); -// } -// -// String id1 = trees[0].getId(); -// String id2 = trees[1].getId(); -// -// minState = getStateNumber(id1); -// stepSize = getStateNumber(id2) - minState; -// -// for (int i = 0; i < trees.length; i++) { -// args.add(args[i]); -// } -// } else { -// NewickImporter importer = new NewickImporter(reader); -// -// while (true) { -// -// int state = 0; -// Tree tree; -// -// try { -// state = importer.readInteger(); -// tree = importer.importTree(taxonList); -// -// if (taxonList == null) { -// // The first tree becomes the taxon list. This means -// // that all subsequent trees will look up their taxa -// // in that taxon list rather than creating their own -// // duplicitous ones. -// taxonList = tree; -// } -// } catch (Importer.ImportException ie) { -// System.out.println("Error reading tree for state " + state); -// throw ie; -// } catch (EOFException e) { -// break; -// } -// -// if (minState == -1) { -// minState = state; -// } else if (stepSize == 0) { -// stepSize = state - minState; -// } -// -// trace.add(tree); -// } -// } - - trace.setMinimumState(minState); - trace.setStepSize(stepSize); - - return trace; - } - - private final static int getStateNumber(String id) throws Importer.ImportException { - try { - return Integer.parseInt(id.substring(id.indexOf('_') + 1).trim()); - } catch (NumberFormatException nfe) { - throw new Importer.ImportException("Bad state number in tree label '" + id + "', the state must be preceded by an underscore(_)."); - } - } -} diff --git a/src/dr/evomodel/arg/ARGTraceAnalysis.java b/src/dr/evomodel/arg/ARGTraceAnalysis.java deleted file mode 100644 index 120fd1e5b3..0000000000 --- a/src/dr/evomodel/arg/ARGTraceAnalysis.java +++ /dev/null @@ -1,349 +0,0 @@ -/* - * ARGTraceAnalysis.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.arg; - -import dr.evolution.io.Importer; -import dr.evolution.tree.FlexibleTree; -import dr.evolution.tree.NodeRef; -import dr.evolution.tree.Tree; -import dr.evolution.tree.TreeUtils; -import dr.evoxml.util.GraphMLUtils; -import dr.util.FrequencySet; -import dr.util.NumberFormatter; - -import java.io.IOException; -import java.io.Reader; -import java.util.Set; - -/** - * @author Marc Suchard - */ -public class ARGTraceAnalysis { - - public ARGTraceAnalysis(ARGTrace[] trace, int burnIn, boolean verbose) { - - this.trace = trace; - - int minMaxState = Integer.MAX_VALUE; - for (ARGTrace aTrace : trace) { - if (aTrace.getMaximumState() < minMaxState) { - minMaxState = aTrace.getMaximumState(); - } - } - - if (burnIn < 0 || burnIn >= minMaxState) { - this.burnin = minMaxState / (10 * trace[0].getStepSize()); - if (verbose) - System.out.println("WARNING: Burn-in larger than total number of states - using 10% of smallest trace"); - } else { - this.burnin = burnIn; - } - - analyze(verbose); - } - - - /** - * Actually analyzes the trace given the burnin - */ - public void analyze(boolean verbose) { - - if (verbose) { - if (trace.length > 1) System.out.println("Combining " + trace.length + " traces."); - } - - ARGModel arg = getARG(0); - argSet = new FrequencySet(); - argSet.add(arg); - - - for (ARGTrace aTrace : trace) { - int treeCount = aTrace.getTreeCount(burnin * aTrace.getStepSize()); - double stepSize = treeCount / 60.0; - int counter = 1; - - if (verbose) { - System.out.println("Analyzing " + treeCount + " ARGs..."); - System.out.println("0 25 50 75 100"); - System.out.println("|--------------|--------------|--------------|--------------|"); - System.out.print("*"); - } - for (int i = 1; i < treeCount; i++) { - arg = aTrace.getARG(i, burnin * aTrace.getStepSize()); -// cladeSet.add(tree); - argSet.add(arg); - if (i >= (int) Math.round(counter * stepSize) && counter <= 60) { - if (verbose) { - System.out.print("*"); - System.out.flush(); - } - counter += 1; - } - } - if (verbose) { - System.out.println("*"); - } - } - } - - /** - * Actually analyzes a particular tree using the trace given the burnin - */ - public final Tree analyzeARG(String target) { - - int n = getTreeCount(); - - FlexibleTree meanTree = null; - - for (int i = 0; i < n; i++) { - Tree tree = getARG(i); - - if (TreeUtils.uniqueNewick(tree, tree.getRoot()).equals(target)) { - meanTree = new FlexibleTree(tree); - break; - } - } - if (meanTree == null) throw new RuntimeException("No target tree in trace"); - - int m = meanTree.getInternalNodeCount(); - for (int j = 0; j < m; j++) { - double[] heights = new double[n]; - NodeRef node1 = meanTree.getInternalNode(j); - Set leafSet = TreeUtils.getDescendantLeaves(meanTree, node1); - - for (int i = 0; i < n; i++) { - Tree tree = getARG(i); - - NodeRef node2 = TreeUtils.getCommonAncestorNode(tree, leafSet); - heights[i] = tree.getNodeHeight(node2); - } - meanTree.setNodeHeight(node1, dr.stats.DiscreteStatistics.mean(heights)); - meanTree.setNodeAttribute(node1, "upper", new Double(dr.stats.DiscreteStatistics.quantile(0.975, heights))); - meanTree.setNodeAttribute(node1, "lower", new Double(dr.stats.DiscreteStatistics.quantile(0.025, heights))); - - } - - return meanTree; - } - - public final int getTreeCount() { - - int treeCount = 0; - for (ARGTrace aTrace : trace) { - treeCount += aTrace.getTreeCount(burnin * aTrace.getStepSize()); - } - return treeCount; - } - - public final ARGModel getARG(int index) { - - int oldTreeCount = 0; - int newTreeCount = 0; - for (ARGTrace aTrace : trace) { - newTreeCount += aTrace.getTreeCount(burnin * aTrace.getStepSize()); - - if (index < newTreeCount) { - return aTrace.getARG(index - oldTreeCount, burnin * aTrace.getStepSize()); - } - oldTreeCount = newTreeCount; - } - throw new RuntimeException("Couldn't find ARG " + index); - } - - - public void report() throws IOException { - - int fieldWidth = 14; - NumberFormatter formatter = new NumberFormatter(6); - formatter.setPadding(true); - formatter.setFieldWidth(fieldWidth); - - int n = argSet.size(); - int totalTrees = argSet.getSumFrequency(); - - System.out.println(); - System.out.println("burnIn=" + burnin); - System.out.println("total ARGs used =" + totalTrees); - System.out.println(); - - - System.out.println("95% credible set (" + n + " unique ARGs, " + totalTrees + " total):"); - System.out.println("Count\tPercent\tARG"); - int credSet = (95 * totalTrees) / 100; - int sumFreq = 0; - - NumberFormatter nf = new NumberFormatter(8); - - for (int i = 0; i < n; i++) { - int freq = argSet.getFrequency(i); - double prop = ((double) freq) / totalTrees; - System.out.print(freq); - System.out.print("\t" + nf.formatDecimal(prop * 100.0, 2) + "%"); - - sumFreq += freq; - double sumProp = ((double) sumFreq) / totalTrees; - System.out.print("\t" + nf.formatDecimal(sumProp * 100.0, 2) + "%"); - - String newickTree = //(String)argSet.get(i); - argSet.get(i).toString(); - -// if (freq > 100) { - // calculate conditional average node heights -// Tree meanTree = analyzeTree(newickTree); -// System.out.println("\t" + Tree.Utils.newick(meanTree)); - /*for (int k = 0; k < meanTree.getInternalNodeCount(); k++) { - NodeRef node = meanTree.getInternalNode(k); - System.out.println("node " + k + "\t" + - meanTree.getNodeHeight(node) + "\t" + - meanTree.getNodeAttribute(node, "lower") + "\t" + - meanTree.getNodeAttribute(node, "upper")); - }*/ - -// } else { - System.out.println("\t" + newickTree); -// } - - - if (sumFreq >= credSet) { - System.out.println(); - System.out.println("95% credible set has " + (i + 1) + " ARGs."); - break; - } - } - - System.out.println(); - - System.out.println("DOT Format for most probable ARG:"); - System.out.println(GraphMLUtils.dotFormat( - argSet.get(0).toXML()) - ); -// System.out.println(argSet.); - /* System.out.println("Majority rule clades (" + cladeSet.size() + " unique clades):"); - n = cladeSet.size(); - for (int i = 0; i < n; i++) { - int freq = cladeSet.getFrequency(i); - double prop = ((double)freq) / totalTrees; - if (prop > 0.5) { - System.out.print(freq); - System.out.print("\t" + nf.formatDecimal(prop * 100.0, 2) + "%"); - System.out.println("\t" + cladeSet.getClade(i)); - } - }*/ - - System.out.flush(); - } - - public void shortReport(String name, Tree tree, boolean drawHeader) throws IOException { - - /* String targetTree = ""; - if (tree != null) targetTree = Tree.Utils.uniqueNewick(tree, tree.getRoot()); - - int n = argSet.size(); - int totalTrees = argSet.getSumFrequency(); - double highestProp = ((double)argSet.getFrequency(0)) / totalTrees; - String mapTree = (String)argSet.get(0); - - if (drawHeader) { - System.out.println("file\ttrees\tuniqueTrees\tp(MAP)\tMAP tree\t95credSize\ttrue_I\tp(true)\tcum(true)"); - } - - System.out.print(name+"\t"); - System.out.print(totalTrees+"\t"); - System.out.print(n+"\t"); - System.out.print(highestProp +"\t"); - System.out.print(mapTree +"\t"); - - int credSet = (95 * totalTrees) / 100; - int sumFreq = 0; - - int credSetSize = -1; - int targetTreeIndex = -1; - double targetTreeProb = 0.0; - double targetTreeCum = 1.0; - for (int i = 0; i < n; i++) { - int freq = argSet.getFrequency(i); - double prop = ((double)freq) / totalTrees; - - sumFreq += freq; - double sumProp = ((double)sumFreq) / totalTrees; - - String newickTree = (String)argSet.get(i); - - if (newickTree.equals(targetTree)) { - targetTreeIndex = i + 1; - targetTreeProb = prop; - targetTreeCum = sumProp; - } - - if (sumFreq >= credSet) { - if (credSetSize == -1) credSetSize = i + 1; - } - } - - System.out.print(credSetSize +"\t"); - System.out.print(targetTreeIndex +"\t"); - System.out.print(targetTreeProb +"\t"); - System.out.println(targetTreeCum); */ - } - - public int getBurnin() { - return burnin; - } - - /** - * @return an analyses of the trees in a log file. - */ - //private static TreeTraceAnalysis analyzeLogFile(String fileName, int burnin) throws IOException { - // return analyzeLogFile(new Reader[] {new FileReader(fileName)}, burnin, true); - //} - - /** - * @return an analyses of the trees in a log file. - */ - public static ARGTraceAnalysis analyzeLogFile(Reader[] reader, int burnin, boolean verbose) throws IOException { - - ARGTrace[] trace = new ARGTrace[reader.length]; - for (int i = 0; i < reader.length; i++) { - try { - trace[i] = ARGTrace.loadARGTrace(reader[i]); - } catch (Importer.ImportException ie) { - throw new RuntimeException(ie.toString()); - } - reader[i].close(); - - } - - return new ARGTraceAnalysis(trace, burnin, verbose); - } - - private int burnin = -1; - private ARGTrace[] trace; - - // private CladeSet cladeSet; - private FrequencySet argSet; -} \ No newline at end of file diff --git a/src/dr/evomodel/arg/ARGTraceAnalysisParser.java b/src/dr/evomodel/arg/ARGTraceAnalysisParser.java deleted file mode 100644 index 6bbb127800..0000000000 --- a/src/dr/evomodel/arg/ARGTraceAnalysisParser.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * ARGTraceAnalysisParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.arg; - -import dr.evomodel.tree.TreeTraceAnalysis; -import dr.xml.*; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.Reader; - -/** - * @author Marc A. Suchard - */ - -public class ARGTraceAnalysisParser extends AbstractXMLObjectParser { - - public final static String ARG_TRACE_ANALYSIS = "argTraceAnalysis"; - public final static String BURN_IN = "burnIn"; - public static final String FILE_NAME = "fileName"; - - public String getParserName() { - return ARG_TRACE_ANALYSIS; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - try { - Reader reader; - - String fileName = xo.getStringAttribute(FILE_NAME); - try { - File file = new File(fileName); - String name = file.getName(); - String parent = file.getParent(); - - if (!file.isAbsolute()) { - parent = System.getProperty("user.dir"); - } - -// System.out.println("Writing log file to "+parent+System.getProperty("path.separator")+name); - reader = new FileReader(new File(parent, name)); - } catch (FileNotFoundException fnfe) { - throw new XMLParseException("File '" + fileName + "' can not be opened for " + getParserName() + " element."); - } - - int burnin = -1; - if (xo.hasAttribute(BURN_IN)) { - // leaving the burnin attribute off will result in 10% being used - burnin = xo.getIntegerAttribute(BURN_IN); - } - - ARGTraceAnalysis analysis = ARGTraceAnalysis.analyzeLogFile(new Reader[]{reader}, burnin, true); - - analysis.report(); - - System.out.println(); - System.out.flush(); - - return analysis; - } catch (java.io.IOException ioe) { - throw new XMLParseException(ioe.getMessage()); - } - } - - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - - public String getParserDescription() { - return "Analyses and reports on a trace consisting of trees."; - } - - public Class getReturnType() { - return TreeTraceAnalysis.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{ - new StringAttributeRule(FILE_NAME, "name of a tree log file", "trees.log"), - AttributeRule.newIntegerRule(BURN_IN, true) - }; -} diff --git a/src/dr/evomodel/arg/ARGTree.java b/src/dr/evomodel/arg/ARGTree.java deleted file mode 100644 index 804aa68774..0000000000 --- a/src/dr/evomodel/arg/ARGTree.java +++ /dev/null @@ -1,574 +0,0 @@ -/* - * ARGTree.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.arg; - -import dr.evolution.tree.MutableTreeListener; -import dr.evolution.tree.NodeRef; -import dr.evolution.tree.Tree; -import dr.evolution.tree.TreeUtils; -import dr.evolution.util.MutableTaxonListListener; -import dr.evolution.util.Taxon; -import dr.evomodel.arg.ARGModel.Node; -import dr.util.Attributable; - -import java.util.*; - -public class ARGTree implements Tree { - - //NodeRef root; - - protected Taxon[] taxaList; - protected int taxaCount; - - private final Node initialRoot; - - public ARGModel argModel; -// private Map mapARGNodesToInts; - - private final Map mapARGNodesToTreeNodes; - -// public Map getMappingInts() { return mapARGNodesToInts; } - -// public Map getMappingNodes() { return mapARGNodesToTreeNodes; } - - private int partition = -9; - -// /** -// * Constructor to represent complete ARG as a tree -// * -// * @param arg -// */ -// public ARGTree(ARGModel arg) { -// this.argModel = arg; -// mapNodesARGToTree = new HashMap(arg.getNodeCount()); -// root = arg.new Node((Node) arg.getRoot()); -// } - - -// /** -// * Constructor for specific partition tree -// * -// * @param arg -// * @param partition -// */ - -// ArrayList nodeList; - - public boolean wasRootTrimmed() { - return (root != initialRoot); - } - - - public String toGraphString() { - StringBuffer sb = new StringBuffer(); - for (Node node : nodes) { - sb.append(node.number); - if (node.leftParent != null) - sb.append(" " + node.leftParent.number); - else - sb.append(" 0"); - if (node.rightParent != null) - sb.append(" " + node.rightParent.number); - else - sb.append(" 0"); - if (node.leftChild != null) - sb.append(" " + node.leftChild.number); - else - sb.append(" 0"); - if (node.rightChild != null) - sb.append(" " + node.rightChild.number); - else - sb.append(" 0"); - if (node.taxon != null) - sb.append(" " + node.taxon.toString()); - sb.append("\n"); - } - sb.append("Root = " + ((Node) getRoot()).number + "\n"); - return new String(sb); - } - - public ARGTree(ARGModel arg, int partition) { - this.argModel = arg; - mapARGNodesToTreeNodes = new HashMap(arg.getNodeCount()); - - this.partition = partition; - ARGModel.Node node = arg.new Node(((Node) arg.getRoot()), partition); - initialRoot = node; - - int j = arg.externalNodeCount; - node.stripOutDeadEnds(); - root = node.stripOutSingleChildNodes(node); - node = root; - nodeCount = 2 * j - 1; - externalNodeCount = j; - internalNodeCount = j - 1; - nodes = new Node[nodeCount]; - - do { - node = (Node) TreeUtils.postorderSuccessor(this, node); - if (node.isExternal()) { - // keep same order as ARG, so do not need to reload tipStates/Partials - nodes[node.number] = node; - mapARGNodesToTreeNodes.put(node.mirrorNode,node); - } else { - // Reorder in new post-order succession - - nodes[j] = node; - node.number = j; - j++; - mapARGNodesToTreeNodes.put(node.mirrorNode, node); - } - } while (node != root); - hasRates = false; - } - - - public Map getMapping() { - return mapARGNodesToTreeNodes; - } - -// public Map getMapARGNodesToInts() { -// // Only need to map internal nodes -// Map map = new HashMap(getInternalNodeCount()); -// for(int i=0; i= taxaCount ) -// return null; -// return taxaList[taxonIndex]; -// } - public Taxon getTaxon(int taxonIndex) { - return ((Node) getExternalNode(taxonIndex)).taxon; - } - - - /** - * @return the ID of the taxon of the ith external node. If it doesn't have - * a taxon, returns the ID of the node itself. - */ - public String getTaxonId(int taxonIndex) { - Taxon taxon = getTaxon(taxonIndex); - if (taxon != null) { - return taxon.getId(); - } else { - return null; - } - } - - /** - * returns the index of the taxon with the given id. - */ - public int getTaxonIndex(String id) { - for (int i = 0, n = getTaxonCount(); i < n; i++) { - if (getTaxonId(i).equals(id)) return i; - } - return -1; - } - - /** - * returns the index of the given taxon. - */ - public int getTaxonIndex(Taxon taxon) { - for (int i = 0, n = getTaxonCount(); i < n; i++) { - if (getTaxon(i) == taxon) return i; - } - return -1; - } - - public List asList() { - List taxa = new ArrayList(); - for (int i = 0, n = getTaxonCount(); i < n; i++) { - taxa.add(getTaxon(i)); - } - return taxa; - } - - public Iterator iterator() { - return new Iterator() { - private int index = -1; - - public boolean hasNext() { - return index < getTaxonCount() - 1; - } - - public Taxon next() { - index ++; - return getTaxon(index); - } - - public void remove() { /* do nothing */ } - }; - } - - /** - * @param taxonIndex the index of the taxon whose attribute is being fetched. - * @param name the name of the attribute of interest. - * @return an object representing the named attributed for the taxon of the given - * external node. If the node doesn't have a taxon then the nodes own attribute - * is returned. - */ - public final Object getTaxonAttribute(int taxonIndex, String name) { - Taxon taxon = getTaxon(taxonIndex); - if (taxon != null) { - return taxon.getAttribute(name); - } - return null; - } - - // ************************************************************** - // MutableTaxonList IMPLEMENTATION - // ************************************************************** - - public int addTaxon(Taxon taxon) { - throw new IllegalArgumentException("Cannot add taxon to a TreeModel"); - } - - public boolean removeTaxon(Taxon taxon) { - throw new IllegalArgumentException("Cannot add taxon to a TreeModel"); - } - - public void setTaxonId(int taxonIndex, String id) { - throw new IllegalArgumentException("Cannot set taxon id in a TreeModel"); - } - - public void setTaxonAttribute(int taxonIndex, String name, Object value) { - throw new IllegalArgumentException("Cannot set taxon attribute in a TreeModel"); - } - - public void addMutableTreeListener(MutableTreeListener listener) { - } // Do nothing at the moment - - public void addMutableTaxonListListener(MutableTaxonListListener listener) { - } // Do nothing at the moment - - // ************************************************************** - // Identifiable IMPLEMENTATION - // ************************************************************** - - protected String id = null; - - /** - * @return the id. - */ - public String getId() { - return id; - } - - /** - * Sets the id. - */ - public void setId(String id) { - this.id = id; - } - - // ************************************************************** - // Attributable IMPLEMENTATION - // ************************************************************** - - private Attributable.AttributeHelper treeAttributes = null; - - /** - * Sets an named attribute for this object. - * - * @param name the name of the attribute. - * @param value the new value of the attribute. - */ - public void setAttribute(String name, Object value) { - if (treeAttributes == null) - treeAttributes = new Attributable.AttributeHelper(); - treeAttributes.setAttribute(name, value); - } - - /** - * @param name the name of the attribute of interest. - * @return an object representing the named attributed for this object. - */ - public Object getAttribute(String name) { - if (treeAttributes == null) - return null; - else - return treeAttributes.getAttribute(name); - } - - /** - * @return an iterator of the attributes that this object has. - */ - public Iterator getAttributeNames() { - if (treeAttributes == null) - return null; - else - return treeAttributes.getAttributeNames(); - } - - /** - * @return a string containing a newick representation of the tree - */ - public final String getNewick() { - return TreeUtils.newick(this); - } - - public final String getUniqueNewick(){ - return TreeUtils.uniqueNewick(this,this.getRoot()); - } - - /** - * @return a string containing a newick representation of the tree - */ - public String toString() { - return getNewick(); - } - - public Tree getCopy() { - throw new UnsupportedOperationException("please don't call this function"); - } - - - // *********************************************************************** - // Private members - // *********************************************************************** - - - /** - * root node - */ - protected Node root = null; - protected int storedRootNumber; - - /** - * list of internal nodes (including root) - */ - protected Node[] nodes = null; - protected Node[] storedNodes = null; - - /** - * number of nodes (including root and tips) - */ - protected int nodeCount; - - /** - * number of external nodes - */ - protected int externalNodeCount; - - /** - * number of internal nodes (including root) - */ - protected int internalNodeCount; - - - - - /** - * holds the units of the trees branches. - */ -// private int units = SUBSTITUTIONS; - private Type units; - - protected boolean inEdit = false; - - private final boolean hasRates; - private final boolean hasTraits = false; - - -} diff --git a/src/dr/evomodel/arg/ARGTreeLogger.java b/src/dr/evomodel/arg/ARGTreeLogger.java deleted file mode 100644 index 073078a3ab..0000000000 --- a/src/dr/evomodel/arg/ARGTreeLogger.java +++ /dev/null @@ -1,250 +0,0 @@ -/* - * ARGTreeLogger.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.arg; - -import dr.evolution.tree.Tree; -import dr.evomodel.branchratemodel.BranchRateModel; -import dr.evomodel.coalescent.structure.ColourSamplerModel; -import dr.inference.loggers.LogFormatter; -import dr.inference.loggers.MLLogger; -import dr.inference.loggers.TabDelimitedFormatter; -import dr.inference.model.Likelihood; -import dr.xml.*; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.PrintWriter; - -/** - * A logger that logs tree and clade frequencies from a given partition in an ARG - * - * @author Marc Suchard - */ -public class ARGTreeLogger extends OldTreeLogger { - - public static final String LOG_ARG = "logArgTree"; - public static final String PARTITION = "partition"; - - - private int partition; - - /** - * Constructor - */ - public ARGTreeLogger(Tree tree, int partition, BranchRateModel branchRateModel, String rateLabel, - ColourSamplerModel colourSamplerModel, String colouringLabel, - Likelihood likelihood, String likelihoodLabel, - LogFormatter formatter, int logEvery, boolean nexusFormat, boolean substitutions) { - - super(tree, branchRateModel, rateLabel, colourSamplerModel, colouringLabel, likelihood, likelihoodLabel, formatter, logEvery, nexusFormat, substitutions); - this.partition = partition; - - } - - - @Override - protected String additionalInfo() { - return " [&PARTITION=" + partition + "]" - + " [&YULE=" + getLogYuleProbabilityString() + "]" - + " [&NUM_REC=" + getNumberOfReassortments() + "]" - ; - } - - private int getNumberOfReassortments() { - ARGModel arg = (ARGModel) getTree(); - return arg.getReassortmentNodeCount(); - } - - private String getLogYuleProbabilityString() { - ARGTree tree = new ARGTree((ARGModel) getTree(), partition); -// BetaSplittingModel betaModel = new BetaSplittingModel( -// new Parameter.Default(1.0), tree); -// betaModel.setBeta(0.0); -// double otherLP = 0; - double logProbability = 0; - for (int i = 0, n = tree.getNodeCount(); i < n; i++) { -// System.err.println(n); - ARGModel.Node node = (ARGModel.Node) tree.getNode(i); - int count = node.getDescendentTipCount(); -// System.err.println(count); - if (count > 2) - logProbability -= 2 * Math.log(count - 1); -// otherLP += betaModel.logNodeProbability(tree,node); - } -// System.err.println("me : "+logProbability); -// System.err.println("old: "+otherLP); - return String.format("%5.4f", logProbability); - } - - @Override - protected Tree getPrintTree() { - return new ARGTree((ARGModel) getTree(), partition); - } - - @Override - protected boolean useTaxonLabels() { - return true; - } - - public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { - - public String getParserName() { - return LOG_ARG; - } - - /** - * @return an object based on the XML element it was passed. - */ - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - ARGModel tree = (ARGModel) xo.getChild(ARGModel.class); - - String fileName = null; - String title = null; - boolean nexusFormat = false; - - String colouringLabel = "demes"; - String rateLabel = "rate"; - String likelihoodLabel = "lnP"; - - if (xo.hasAttribute(TITLE)) { - title = xo.getStringAttribute(TITLE); - } - - if (xo.hasAttribute(FILE_NAME)) { - fileName = xo.getStringAttribute(FILE_NAME); - } - - if (xo.hasAttribute(NEXUS_FORMAT)) { - nexusFormat = xo.getBooleanAttribute(NEXUS_FORMAT); - } - - boolean substitutions = false; - if (xo.hasAttribute(BRANCH_LENGTHS)) { - substitutions = xo.getStringAttribute(BRANCH_LENGTHS).equals(SUBSTITUTIONS); - } - - BranchRateModel branchRateModel = (BranchRateModel) xo.getChild(BranchRateModel.class); - - ColourSamplerModel colourSamplerModel = (ColourSamplerModel) xo.getChild(ColourSamplerModel.class); - - Likelihood likelihood = (Likelihood) xo.getChild(Likelihood.class); - - // logEvery of zero only displays at the end - int logEvery = 1; - - if (xo.hasAttribute(LOG_EVERY)) { - logEvery = xo.getIntegerAttribute(LOG_EVERY); - } - - int partition = 0; - - if (xo.hasAttribute(PARTITION)) { - partition = xo.getIntegerAttribute(PARTITION); - } - - if (partition > tree.getMaxPartitionNumber()) - throw new XMLParseException("ARGModel does not contain a partition #" + partition); - - PrintWriter pw = null; - - if (fileName != null) { - - try { - File file = new File(fileName); - String name = file.getName(); - String parent = file.getParent(); - - if (!file.isAbsolute()) { - parent = System.getProperty("user.dir"); - } - -// System.out.println("Writing log file to "+parent+System.getProperty("path.separator")+name); - pw = new PrintWriter(new FileOutputStream(new File(parent, name))); - } catch (FileNotFoundException fnfe) { - throw new XMLParseException("File '" + fileName + "' can not be opened for " + getParserName() + " element."); - } - } else { - pw = new PrintWriter(System.out); - } - - LogFormatter formatter = new TabDelimitedFormatter(pw); - - ARGTreeLogger logger = new ARGTreeLogger(tree, partition, branchRateModel, rateLabel, - colourSamplerModel, colouringLabel, likelihood, likelihoodLabel, - formatter, logEvery, nexusFormat, substitutions); - - if (title != null) { - logger.setTitle(title); - } - - return logger; - } - - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{ - AttributeRule.newIntegerRule(LOG_EVERY), - AttributeRule.newIntegerRule(PARTITION), - new StringAttributeRule(FILE_NAME, - "The name of the file to send log output to. " + - "If no file name is specified then log is sent to standard output", true), - new StringAttributeRule(TITLE, "The title of the log", true), - AttributeRule.newBooleanRule(NEXUS_FORMAT, true, - "Whether to use the NEXUS format for the tree log"), - new StringAttributeRule(BRANCH_LENGTHS, "What units should the branch lengths be in", new String[]{TIME, SUBSTITUTIONS}, true), - new ElementRule(ARGModel.class, "The ARG which is to be logged"), - new ElementRule(BranchRateModel.class, true), - new ElementRule(ColourSamplerModel.class, true), - new ElementRule(Likelihood.class, true) - }; - - public String getParserDescription() { - return "Logs a tree to a file"; - } - - public String getExample() { - return - "\n" + - "<" + getParserName() + " " + LOG_EVERY + "=\"100\" " + FILE_NAME + "=\"log.trees\" " + NEXUS_FORMAT + "=\"true\">\n" + - " \n" + - "\n"; - } - - public Class getReturnType() { - return MLLogger.class; - } - }; - -} \ No newline at end of file diff --git a/src/dr/evomodel/arg/HierarchicalPartitionLikelihood.java b/src/dr/evomodel/arg/HierarchicalPartitionLikelihood.java deleted file mode 100644 index e48d2d8cc8..0000000000 --- a/src/dr/evomodel/arg/HierarchicalPartitionLikelihood.java +++ /dev/null @@ -1,157 +0,0 @@ -/* - * HierarchicalPartitionLikelihood.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.arg; - -import dr.inference.model.Model; -import dr.inference.model.Parameter; -import dr.inference.model.Variable; -import dr.inference.model.Variable.ChangeType; -import dr.math.MathUtils; -import dr.xml.*; - -public class HierarchicalPartitionLikelihood extends ARGPartitionLikelihood { - - public static final String HIERARCHICAL_PARTITION_LIKELIHOOD = "hierarchicalPartitionLikelihood"; - - private Parameter probabilities; - - public HierarchicalPartitionLikelihood(String id, ARGModel arg, Parameter probs) { - super(id, arg); - - this.probabilities = probs; - - addVariable(probs); - addModel(arg); - } - - public double[] generatePartition() { - double[] partition = new double[getNumberOfPartitionsMinusOne() + 1]; - - partition[0] = 0.0; - - for (int i = 0; i < partition.length; i++) - partition[i] = 0.0; - - while (UniformPartitionLikelihood.arraySum(partition) == 0.0) { - for (int i = 1; i < partition.length; i++) { - if (MathUtils.nextDouble() < probabilities.getParameterValue(i - 1)) { - partition[i] = 1.0; - } else { - partition[i] = 0.0; - } - } - } - - - return partition; - } - - public double getLogLikelihood(double[] partition) { - double logLike = 0; - - for (int i = 1; i < partition.length; i++) { - if (partition[i] == 1.0) { - logLike += Math.log(probabilities.getParameterValue(i - 1)); - } else { - logLike += Math.log(1 - probabilities.getParameterValue(i - 1)); - } - } - -// return 1; - - return logLike; - } - - protected void acceptState() { - // nothing to do! - } - - protected void handleModelChangedEvent(Model model, Object object, int index) { - // i'm lazy - - } - - protected void handleVariableChangedEvent(Variable variable, int index, - ChangeType type) { - // I'm lazy, so I compute after each step :) - } - - protected void restoreState() { - //nothing to restore! - } - - @Override - protected void storeState() { - //nothing to store - - } - - public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { - - public String getParserDescription() { - return null; - } - - public Class getReturnType() { - return PoissonPartitionLikelihood.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return new XMLSyntaxRule[]{ - - new ElementRule(ARGModel.class, false), - }; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - String id = ""; - if (xo.hasId()) - id = xo.getId(); - - ARGModel arg = (ARGModel) xo.getChild(ARGModel.class); - - Parameter values = (Parameter) xo.getChild(Parameter.class); - - if (values.getDimension() != arg.getNumberOfPartitions() - 1) { - throw new XMLParseException("The dimension of the parameter must equal the number of partitions minus 1 "); - } - - if (arg.isRecombinationPartitionType()) { - throw new XMLParseException(ARGModel.TREE_MODEL + " must be of type " + ARGModel.REASSORTMENT_PARTITION); - } - - return new HierarchicalPartitionLikelihood(id, arg, values); - } - - public String getParserName() { - return HIERARCHICAL_PARTITION_LIKELIHOOD; - } - - }; - -} diff --git a/src/dr/evomodel/arg/OldTreeLogger.java b/src/dr/evomodel/arg/OldTreeLogger.java deleted file mode 100644 index 671aa9f3ab..0000000000 --- a/src/dr/evomodel/arg/OldTreeLogger.java +++ /dev/null @@ -1,210 +0,0 @@ -/* - * OldTreeLogger.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.arg; - -import dr.evolution.colouring.TreeColouring; -import dr.evolution.tree.Tree; -import dr.evolution.tree.TreeUtils; -import dr.evomodel.branchratemodel.BranchRateModel; -import dr.evomodel.coalescent.structure.ColourSamplerModel; -import dr.inference.loggers.LogFormatter; -import dr.inference.loggers.MCLogger; -import dr.inference.model.Likelihood; - -/** - * A logger that logs tree and clade frequencies. - * - * @author Andrew Rambaut - * @author Alexei Drummond - */ -public class OldTreeLogger extends MCLogger { - - public static final String LOG_TREE = "logTree"; - public static final String NEXUS_FORMAT = "nexusFormat"; - public static final String USING_RATES = "usingRates"; - public static final String BRANCH_LENGTHS = "branchLengths"; - public static final String TIME = "time"; - public static final String SUBSTITUTIONS = "substitutions"; - - // The following were in MCLogger; where did they go? - - public static final String LOG = "log"; - public static final String ECHO = "echo"; - public static final String ECHO_EVERY = "echoEvery"; - public static final String TITLE = "title"; - public static final String FILE_NAME = "fileName"; - public static final String FORMAT = "format"; - public static final String TAB = "tab"; - public static final String HTML = "html"; - public static final String PRETTY = "pretty"; - public static final String LOG_EVERY = "logEvery"; - - public static final String COLUMNS = "columns"; - public static final String COLUMN = "column"; - public static final String LABEL = "label"; - public static final String SIGNIFICANT_FIGURES = "sf"; - public static final String DECIMAL_PLACES = "dp"; - public static final String WIDTH = "width"; - - - private Tree tree; - private BranchRateModel branchRateModel = null; - private String rateLabel; - - private ColourSamplerModel colourSamplerModel = null; - private String colouringLabel; - - private Likelihood likelihood = null; - private String likelihoodLabel; - - private boolean nexusFormat = false; - public boolean usingRates = false; - public boolean substitutions = false; - - /** - * Constructor - */ - public OldTreeLogger(Tree tree, BranchRateModel branchRateModel, String rateLabel, - ColourSamplerModel colourSamplerModel, String colouringLabel, - Likelihood likelihood, String likelihoodLabel, - LogFormatter formatter, int logEvery, boolean nexusFormat, boolean substitutions) { - - super(formatter, logEvery, false); - - this.nexusFormat = nexusFormat; - this.branchRateModel = branchRateModel; - this.rateLabel = rateLabel; - - this.colourSamplerModel = colourSamplerModel; - this.colouringLabel = colouringLabel; - - this.likelihood = likelihood; - this.likelihoodLabel = likelihoodLabel; - - if (branchRateModel != null) { - this.substitutions = substitutions; - } - this.tree = tree; - } - - public void startLogging() { - - if (nexusFormat) { - int taxonCount = tree.getTaxonCount(); - logLine("#NEXUS"); - logLine(""); - logLine("Begin taxa;"); - logLine("\tDimensions ntax=" + taxonCount + ";"); - logLine("\tTaxlabels"); - for (int i = 0; i < taxonCount; i++) { - logLine("\t\t" + tree.getTaxon(i).getId()); - } - logLine("\t\t;"); - logLine("End;"); - logLine(""); - logLine("Begin trees;"); - - if (!useTaxonLabels()) { - // This is needed if the trees use numerical taxon labels - logLine("\tTranslate"); - for (int i = 0; i < taxonCount; i++) { - int k = i + 1; - if (k < taxonCount) { - logLine("\t\t" + k + " " + tree.getTaxonId(i) + ","); - } else { - logLine("\t\t" + k + " " + tree.getTaxonId(i)); - } - } - - - logLine("\t\t;"); - } - } - } - - public void log(long state) { - - if (logEvery <= 0 || ((state % logEvery) == 0)) { - StringBuffer buffer = new StringBuffer("tree STATE_"); - buffer.append(state); - if (likelihood != null) { - buffer.append(" [&"); - buffer.append(likelihoodLabel); - buffer.append("="); - buffer.append(likelihood.getLogLikelihood()); - buffer.append("]"); - } - - buffer.append(additionalInfo()); - - buffer.append(" = [&R] "); - - TreeColouring colouring = null; - if (colourSamplerModel != null) { - colouring = colourSamplerModel.getTreeColouring(); - } - - Tree printTree = getPrintTree(); - - if (substitutions) { - TreeUtils.newick(printTree, printTree.getRoot(), useTaxonLabels(), TreeUtils.BranchLengthType.LENGTHS_AS_SUBSTITUTIONS, - null, branchRateModel, null, null, buffer); - } else { - TreeUtils.newick(printTree, printTree.getRoot(), useTaxonLabels(), TreeUtils.BranchLengthType.LENGTHS_AS_TIME, - null, branchRateModel, null, null, buffer); - } - - buffer.append(";"); - logLine(buffer.toString()); - } - } - - protected String additionalInfo() { - return ""; - } - - protected Tree getPrintTree() { - return tree; - } - - protected Tree getTree() { - return tree; - } - - - protected boolean useTaxonLabels() { - return false; - } - - public void stopLogging() { - - logLine("End;"); - super.stopLogging(); - } - -} \ No newline at end of file diff --git a/src/dr/evomodel/arg/PoissonPartitionLikelihood.java b/src/dr/evomodel/arg/PoissonPartitionLikelihood.java deleted file mode 100644 index be2f5c1341..0000000000 --- a/src/dr/evomodel/arg/PoissonPartitionLikelihood.java +++ /dev/null @@ -1,209 +0,0 @@ -/* - * PoissonPartitionLikelihood.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.arg; - - -import dr.inference.model.Model; -import dr.inference.model.Variable; -import dr.inference.model.Variable.ChangeType; -import dr.inferencexml.distribution.PriorParsers; -import dr.math.MathUtils; -import dr.math.Poisson; -import dr.math.distributions.PoissonDistribution; -import dr.xml.*; -import jebl.math.Binomial; - -public class PoissonPartitionLikelihood extends ARGPartitionLikelihood { - - public static final String POISSON_PARTITION_LIKELIHOOD = "poissonPartitionLikelihood"; - - PoissonDistribution pd; - double mean; - - public PoissonPartitionLikelihood(String id, ARGModel arg, double mean) { - super(id, arg); - - pd = new PoissonDistribution(mean); - this.mean = mean; - } - - public double getLogLikelihood(double[] partition) { - if ((getNumberOfPartitionsMinusOne() + 1) % 2 == 0) { - return getEvenLogLikelihood(partition); - } - - return getOddLogLikelihood(partition); - - } - - private double getEvenLogLikelihood(double[] partition) { - int numberOfZeros = 0; - int numberOfOnes = 0; - - for (double d : partition) { - assert d == 0.0 || d == 1.0; - - if (d == 0.0) - numberOfZeros++; - else - numberOfOnes++; - } - - double poissonValue = (double) Math.min(numberOfZeros, numberOfOnes); - - double logLike = pd.logPdf(poissonValue); - - if (poissonValue < partition.length / 2) { - return logLike - Math.log(Binomial.choose(partition.length, poissonValue)); - } else { - return logLike - Math.log(Binomial.choose(partition.length - 1, poissonValue)); - } - } - - private double getOddLogLikelihood(double[] partition) { - int numberOfZeros = 0; - int numberOfOnes = 0; - - for (double d : partition) { - assert d == 0.0 || d == 1.0; - - if (d == 0.0) - numberOfZeros++; - else - numberOfOnes++; - - } - - double poissonValue = (double) Math.min(numberOfZeros, numberOfOnes); - - return pd.logPdf(poissonValue) - - Math.log(Binomial.choose(partition.length, poissonValue)); - } - - public double[] generatePartition() { - int lengthDividedByTwo = (getNumberOfPartitionsMinusOne() + 1) / 2; - - int value = 0; - - while (value < 1 || value > lengthDividedByTwo) { - value = Poisson.nextPoisson(mean); - } - - int[] x = new int[getNumberOfPartitionsMinusOne() + 1]; - - for (int i = 0; i < value; i++) { - x[i] = 1; - } - - MathUtils.permute(x); - - if (x[0] == 1) { - for (int i = 0; i < x.length; i++) { - if (x[i] == 1) { - x[i] = 0; - } else { - x[i] = 1; - } - } - } - - double[] rValue = new double[x.length]; - - for (int i = 0; i < rValue.length; i++) { - rValue[i] = x[i]; - } - - return rValue; - } - - - public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { - - public String getParserDescription() { - return null; - } - - public Class getReturnType() { - return PoissonPartitionLikelihood.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return new XMLSyntaxRule[]{ - AttributeRule.newDoubleRule(PriorParsers.MEAN, false), - new ElementRule(ARGModel.class, false), - }; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - String id = ""; - if (xo.hasId()) - id = xo.getId(); - - double mean = xo.getDoubleAttribute(PriorParsers.MEAN); - ARGModel arg = (ARGModel) xo.getChild(ARGModel.class); - - if (arg.isRecombinationPartitionType()) { - throw new XMLParseException(ARGModel.TREE_MODEL + " must be of type " + ARGModel.REASSORTMENT_PARTITION); - } - - return new PoissonPartitionLikelihood(id, arg, mean); - } - - public String getParserName() { - return POISSON_PARTITION_LIKELIHOOD; - } - - }; - - protected void acceptState() { - //nothing to do - } - - @Override - protected void handleModelChangedEvent(Model model, Object object, int index) { - //has no submodels - } - - @Override - protected void handleVariableChangedEvent(Variable variable, int index, - ChangeType type) { - //has no parameters - } - - @Override - protected void restoreState() { - //nothing to restore - } - - @Override - protected void storeState() { - // nothing to store - } - - -} diff --git a/src/dr/evomodel/arg/RecombinationPartitionStatistic.java b/src/dr/evomodel/arg/RecombinationPartitionStatistic.java deleted file mode 100644 index 8cb775634d..0000000000 --- a/src/dr/evomodel/arg/RecombinationPartitionStatistic.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * RecombinationPartitionStatistic.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.arg; - -import dr.evomodel.arg.ARGModel.Node; -import dr.evomodel.arg.operators.ARGAddRemoveEventOperator; -import dr.inference.model.CompoundParameter; -import dr.inference.model.Statistic; -import dr.xml.AbstractXMLObjectParser; -import dr.xml.XMLObject; -import dr.xml.XMLObjectParser; -import dr.xml.XMLParseException; -import dr.xml.XMLSyntaxRule; - - -public class RecombinationPartitionStatistic extends Statistic.Abstract{ - - public final static String RECOMBINATION_PARTITION_STATISTIC = "partitionStatistic"; - private int dimension; - private ARGModel arg; - private String[] taxaNames; - - public RecombinationPartitionStatistic(String id, ARGModel arg){ - - setId(id); - - this.arg = arg; - - this.dimension = arg.getExternalNodeCount(); - taxaNames = new String[this.dimension]; - for(int i = 0; i < taxaNames.length; i++){ - taxaNames[i] = "" + ((Node)arg.getExternalNode(i)).taxon; - } - } - - - public int getDimension() { - return dimension; - } - - public String getDimensionName(int dim){ - return "Taxa" + taxaNames[dim]; - } - - public double getStatisticValue(int dim) { - - Node x = (Node)arg.getExternalNode(dim); - - assert x.taxon.toString().equals(taxaNames[dim]); - - boolean c = x.hasReassortmentAncestor(); - - if(c){ - return 1.0; - } - return 0.0; - } - - public static XMLObjectParser PARSER = new AbstractXMLObjectParser(){ - - public String getParserDescription() { - return null; - } - - public Class getReturnType() { - return RecombinationPartitionStatistic.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return null; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - String id = xo.getId(); - - ARGModel arg = (ARGModel)xo.getChild(ARGModel.class); - - return new RecombinationPartitionStatistic(id,arg); - } - - public String getParserName() { - return RECOMBINATION_PARTITION_STATISTIC; - } - - }; - -} diff --git a/src/dr/evomodel/arg/UniformPartitionLikelihood.java b/src/dr/evomodel/arg/UniformPartitionLikelihood.java deleted file mode 100644 index e75c464b05..0000000000 --- a/src/dr/evomodel/arg/UniformPartitionLikelihood.java +++ /dev/null @@ -1,184 +0,0 @@ -/* - * UniformPartitionLikelihood.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.arg; - -import dr.inference.model.Likelihood; -import dr.inference.model.Model; -import dr.inference.model.Variable; -import dr.inference.model.Variable.ChangeType; -import dr.math.MathUtils; -import dr.xml.*; - - -public class UniformPartitionLikelihood extends ARGPartitionLikelihood implements Likelihood { - - public static final String UNIFORM_PARTITION_LIKELIHOOD = "uniformPartitionLikelihood"; - private double logStateCount; - private boolean isRecombination; - - - public UniformPartitionLikelihood(String id, ARGModel arg) { - super(id, arg); - - isRecombination = arg.isRecombinationPartitionType(); - - int numberOfPartitionsMinusOne = getNumberOfPartitionsMinusOne(); - - if (arg.isRecombinationPartitionType()) { - //For example, if we have five partitions, we can have the following - // 0 1 1 1 1 - // 0 0 1 1 1 <-- Equates to four possibilities - // 0 0 0 1 1 - // 0 0 0 0 1 - - logStateCount = Math.log(numberOfPartitionsMinusOne); - } else { - //You basically choose a subset from all possible subset of the final four - //there are 2^numberOfPartitionsMinusOne of these - // - //Except! you cannot choose the empty set. - - - double rValue = Math.pow(2.0, numberOfPartitionsMinusOne) - 1; - - logStateCount = Math.log(rValue); - } - } - - public double[] generatePartition() { - if (isRecombination) { - return generateRecombinationPartition(); - } - return generateReassortmentPartition(); - } - - private double[] generateRecombinationPartition() { - int numberOfPartitionsMinusOne = getNumberOfPartitionsMinusOne(); - - int cut = MathUtils.nextInt(numberOfPartitionsMinusOne); - - int leftValue = 0; //At one time, these values could switch. - int rightValue = 1; - - double[] partition = new double[numberOfPartitionsMinusOne + 1]; - - for (int i = 0; i < cut + 1; i++) - partition[i] = leftValue; - for (int i = cut + 1; i < partition.length; i++) - partition[i] = rightValue; - - return partition; - } - - public static double arraySum(double[] x) { - double a = 0; - for (double b : x) - a += b; - return a; - } - - private double[] generateReassortmentPartition() { - int numberOfPartitions = getNumberOfPartitionsMinusOne() + 1; - - double[] partition = new double[numberOfPartitions]; - - while (arraySum(partition) == 0) { - for (int i = 1; i < partition.length; i++) { - if (MathUtils.nextBoolean()) { - partition[i] = 1.0; - } else { - partition[i] = 0.0; - } - } - } - - partition[0] = 0.0; - - return partition; - } - - - public double getLogLikelihood(double[] partition) { - return -logStateCount; - } - - public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { - - public String getParserDescription() { - return null; - } - - public Class getReturnType() { - return UniformPartitionLikelihood.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return new XMLSyntaxRule[]{ - new ElementRule(ARGModel.class, false), - }; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - ARGModel arg = (ARGModel) xo.getChild(ARGModel.class); - - String id = ""; - if (xo.hasId()) - id = xo.getId(); - - return new UniformPartitionLikelihood(id, arg); - } - - public String getParserName() { - return UNIFORM_PARTITION_LIKELIHOOD; - } - - }; - - protected void acceptState() { - //nothing to do - } - - - protected void handleModelChangedEvent(Model model, Object object, int index) { - //has no submodels - } - - protected void handleVariableChangedEvent(Variable variable, int index, - ChangeType type) { - //has no parameters - } - - protected void restoreState() { - //nothing to restore - } - - protected void storeState() { - // nothing to store - } - -} diff --git a/src/dr/evomodel/arg/beast.properties b/src/dr/evomodel/arg/beast.properties deleted file mode 100644 index 910471c42d..0000000000 --- a/src/dr/evomodel/arg/beast.properties +++ /dev/null @@ -1,32 +0,0 @@ -# -# beast.properties -# -# Copyright © 2002-2024 the BEAST Development Team -# http://beast.community/about -# -# This file is part of BEAST. -# See the NOTICE file distributed with this work for additional -# information regarding copyright ownership and licensing. -# -# BEAST is free software; you can redistribute it and/or modify -# it under the terms of the GNU Lesser General Public License as -# published by the Free Software Foundation; either version 2 -# of the License, or (at your option) any later version. -# -# BEAST is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with BEAST; if not, write to the -# Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, -# Boston, MA 02110-1301 USA -# -# - -name="Ancestral Recombination Graphs" -authors="Marc Suchard & Erik Bloomquist" -description="A system for doing ancestral recombination graphics in BEAST" -citation="Bloomquist & Suchard, in prep." -parsers="parsers.txt" diff --git a/src/dr/evomodel/arg/branchratemodel/ARGDiscretizedBranchRates.java b/src/dr/evomodel/arg/branchratemodel/ARGDiscretizedBranchRates.java deleted file mode 100644 index 8737df5a62..0000000000 --- a/src/dr/evomodel/arg/branchratemodel/ARGDiscretizedBranchRates.java +++ /dev/null @@ -1,303 +0,0 @@ -/* - * ARGDiscretizedBranchRates.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.arg.branchratemodel; - -import dr.evolution.tree.NodeRef; -import dr.evolution.tree.Tree; -import dr.evomodel.arg.ARGModel; -import dr.evomodel.branchratemodel.AbstractBranchRateModel; -import dr.evomodel.branchratemodel.BranchRateModel; -import dr.inference.distribution.ParametricDistributionModel; -import dr.inference.model.AbstractModel; -import dr.inference.model.Model; -import dr.inference.model.Parameter; -import dr.inference.model.Variable; -import dr.xml.*; - -import java.util.logging.Logger; - -/** - * @author Marc Suchard - * @author Alexei Drummond - * @author Andrew Rambaut - */ -public class ARGDiscretizedBranchRates extends AbstractBranchRateModel { - - - public static final String DISCRETIZED_BRANCH_RATES = "argDiscretizedBranchRates"; - public static final String DISTRIBUTION = "distribution"; - public static final String NUM_RATE_CATEGORIES = "numRateCategories"; - public static final String SINGLE_ROOT_RATE = "singleRootRate"; - - private ParametricDistributionModel distributionModel; - private ARGModel tree; - - // The rate categories of each branch - private Parameter rateCategoryParameter; - - // the index of the root node. - private int rootNodeNumber; - private int storedRootNodeNumber; - - private final int categoryCount; - private final double step; - private final double[] rates; - - private boolean ratesKnown = false; -// private boolean orderKnown = false; - - - public ARGDiscretizedBranchRates(ARGModel tree, -// Parameter rateCategoryParameter, -int numRateCategories, -ParametricDistributionModel model) { - - - super(DISCRETIZED_BRANCH_RATES); - this.tree = tree; - -// categoryCount = tree.getNodeCount(); - categoryCount = numRateCategories; - - step = 1.0 / (double) categoryCount; - - rates = new double[categoryCount]; - - this.distributionModel = model; - - this.rateCategoryParameter = rateCategoryParameter; -// if (rateCategoryParameter.getDimension() != tree.getNodeCount() -1 ) { -// throw new IllegalArgumentException("The rate category parameter must be of length nodeCount-1"); -// } -// if (rateCategoryParameter.getDimension() > tree.getNodeCount() -1 ) { - if (numRateCategories > tree.getNodeCount() - 1) { - throw new IllegalArgumentException("The rate category parameter must be less than the length 2*tipCount-1"); - } - -// for (int i = 0; i < rateCategoryParameter.getDimension(); i++) { -// rateCategoryParameter.setParameterValue(i, i); -// } - - ratesKnown = false; -// orderKnown = false; - - addModel(model); - addModel(tree); - -// addVariable(rateCategoryParameter); - - rootNodeNumber = tree.getRoot().getNumber(); - storedRootNodeNumber = rootNodeNumber; - } - - public void handleModelChangedEvent(Model model, Object object, int index) { - if (model == distributionModel) { - ratesKnown = false; - } else if (model == tree) { -// orderKnown = false; - } - fireModelChanged(); - } - - protected final void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) { - fireModelChanged(); - } - - protected void storeState() { - storedRootNodeNumber = rootNodeNumber; - } - - protected void restoreState() { - ratesKnown = false; - rootNodeNumber = storedRootNodeNumber; - } - - protected void acceptState() { - } - - public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { - - public String getParserName() { - return DISCRETIZED_BRANCH_RATES; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - ARGModel tree = (ARGModel) xo.getChild(ARGModel.class); - ParametricDistributionModel distributionModel = (ParametricDistributionModel) xo.getChild(DISTRIBUTION); - -// Parameter rateCategoryParameter = (Parameter)xo.getSocketChild(RATE_CATEGORIES); - - int numRateCategories = xo.getIntegerAttribute(NUM_RATE_CATEGORIES); - - Logger.getLogger("dr.evomodel").info("Using discretized relaxed clock model."); - Logger.getLogger("dr.evomodel").info(" parametric model = " + distributionModel.getModelName()); - Logger.getLogger("dr.evomodel").info(" rate categories = " + numRateCategories); - - if (xo.hasAttribute(SINGLE_ROOT_RATE)) { - //singleRootRate = xo.getBooleanAttribute(SINGLE_ROOT_RATE); - Logger.getLogger("dr.evomodel").warning(" WARNING: single root rate is not implemented!"); - } - - - return new ARGDiscretizedBranchRates(tree, numRateCategories, distributionModel); - } - - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - - public String getParserDescription() { - return - "This element returns an discretized relaxed clock model." + - "The branch rates are drawn from a discretized parametric distribution."; - } - - public Class getReturnType() { - return ARGDiscretizedBranchRates.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{ -// AttributeRule.newBooleanRule(SINGLE_ROOT_RATE, true, "Whether only a single rate should be used for the two children branches of the root"), - new ElementRule(ARGModel.class), - new ElementRule(DISTRIBUTION, ParametricDistributionModel.class, "The distribution model for rates among branches", false), -// new ElementRule(RATE_CATEGORIES, Parameter.class, "The rate categories parameter", false), - AttributeRule.newIntegerRule(NUM_RATE_CATEGORIES), - }; - }; - - public double getBranchRate(Tree tree, NodeRef node) { - - if (tree.isRoot(node)) { - throw new IllegalArgumentException("root node doesn't have a rate!"); - } - - if (!ratesKnown) { - setupRates(); - ratesKnown = true; - } -// if (!orderKnown) { -// shuffleIndices(); -// orderKnown = true; -// } - -// int nodeNumber = node.getNumber(); - -// int rateCategory = 0; -// if (nodeNumber < rootNodeNumber) { -// rateCategory = (int)Math.round(rateCategoryParameter.getParameterValue(nodeNumber)); -// } else if (nodeNumber > rootNodeNumber) { -// rateCategory = (int)Math.round(rateCategoryParameter.getParameterValue(nodeNumber-1)); -// } else { -// throw new IllegalArgumentException("INTERNAL ERROR! node with number " + rootNodeNumber + " should be the root node."); -// } - int rateCategory = (int) tree.getNodeRate(node); -// System.err.println("Node "+nodeNumber+" has rate category "+rateCategory); -// System.err.println("rate = "+rates[rateCategory]+" : "+rateCategory); - return rates[rateCategory]; - } - - /** - * Calculates the actual rates corresponding to the category indices. - */ - private void setupRates() { - -// System.err.println("Setting up rates:"); -// System.err.println("catCount = "+categoryCount); - double z = step / 2.0; - for (int i = 0; i < categoryCount; i++) { - rates[i] = distributionModel.quantile(z); - z += step; -// System.err.println(rates[i]); - } - } - - private void shuffleIndices() { - int newRootNodeNumber = tree.getRoot().getNumber(); - - //if (newRootNodeNumber != rootNodeNumber) { - // System.out.println("old root node number =" + rootNodeNumber); - // System.out.println("new root node number =" + newRootNodeNumber); - //} - - if (rootNodeNumber > newRootNodeNumber) { - - //for (int i = 0; i < rateCategoryParameter.getDimension(); i++) { - // System.out.print((int)Math.round(rateCategoryParameter.getParameterValue(i)) + "\t"); - //} - //System.out.println(); - - int oldRateIndex = (int) Math.round( - rateCategoryParameter.getParameterValue(newRootNodeNumber)); - - int end = Math.min(rateCategoryParameter.getDimension() - 1, rootNodeNumber); - for (int i = newRootNodeNumber; i < end; i++) { - rateCategoryParameter.setParameterValue(i, rateCategoryParameter.getParameterValue(i + 1)); - } - - rateCategoryParameter.setParameterValue(end, oldRateIndex); - - //for (int i = 0; i < rateCategoryParameter.getDimension(); i++) { - // System.out.print((int)Math.round(rateCategoryParameter.getParameterValue(i)) + "\t"); - //} - //System.out.println(); - - } else if (rootNodeNumber < newRootNodeNumber) { - - //System.out.println("old root node number =" + rootNodeNumber); - //System.out.println("new root node number =" + newRootNodeNumber); - - //for (int i = 0; i < rateCategoryParameter.getDimension(); i++) { - // System.out.print((int)Math.round(rateCategoryParameter.getParameterValue(i)) + "\t"); - //} - //System.out.println(); - - int end = Math.min(rateCategoryParameter.getDimension() - 1, newRootNodeNumber); - - int oldRateIndex = (int) Math.round( - rateCategoryParameter.getParameterValue(end)); - - for (int i = end; i > rootNodeNumber; i--) { - rateCategoryParameter.setParameterValue(i, rateCategoryParameter.getParameterValue(i - 1)); - } - - rateCategoryParameter.setParameterValue(rootNodeNumber, oldRateIndex); - - //for (int i = 0; i < rateCategoryParameter.getDimension(); i++) { - // System.out.print((int)Math.round(rateCategoryParameter.getParameterValue(i)) + "\t"); - //} - //System.out.println(); - } - rootNodeNumber = newRootNodeNumber; - } - -} \ No newline at end of file diff --git a/src/dr/evomodel/arg/coalescent/ARGCoalescentLikelihood.java b/src/dr/evomodel/arg/coalescent/ARGCoalescentLikelihood.java deleted file mode 100644 index 5fff89885e..0000000000 --- a/src/dr/evomodel/arg/coalescent/ARGCoalescentLikelihood.java +++ /dev/null @@ -1,349 +0,0 @@ -/* - * ARGCoalescentLikelihood.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.arg.coalescent; - -import dr.evolution.tree.NodeRef; -import dr.evomodel.arg.ARGModel; -import dr.inference.model.Model; -import dr.inference.model.Parameter; -import dr.xml.*; - -import java.util.ArrayList; -import java.util.logging.Logger; - -public class ARGCoalescentLikelihood extends VeryOldCoalescentLikelihood { - - public static final String ARG_COALESCENT_MODEL = "argCoalescentLikelihood"; - public static final String RECOMBINATION_RATE = "recombinationRate"; - public static final String POPULATION_SIZE = "populationSize"; - public static final String ARG_MODEL = "argModel"; - public static final String MAX_REASSORTMENTS = "maxReassortments"; - public static final String ANCESTRAL_RESTRICTION = "ancestralRestriction"; - - public static final int RECOMBINATION = 3; - - private Parameter popSize; - private Parameter recomRate; - protected ARGModel arg; - private int taxaNumber; - protected int maxReassortments; - private boolean ancestralRestriction = false; - - private ArrayList intervals; - private ArrayList storedIntervals; - - public ARGCoalescentLikelihood(String name, ARGModel arg, int max) { - super(name); - this.arg = arg; - - intervals = new ArrayList(); - - taxaNumber = arg.getExternalNodeCount(); - this.maxReassortments = max; - } - - public ARGCoalescentLikelihood(Parameter popSize, Parameter recomRate, - ARGModel arg, boolean setupIntervals, int maxReassort, boolean ancestralRestriction) { - super(ARG_COALESCENT_MODEL); - - this.popSize = popSize; - this.recomRate = recomRate; - this.arg = arg; - this.ancestralRestriction = ancestralRestriction; - addVariable(popSize); - addVariable(recomRate); - - addModel(arg); - intervals = new ArrayList(arg.getNodeCount()); - intervalsKnown = false; - likelihoodKnown = false; - - if (setupIntervals) { - intervalsKnown = true; - calculateIntervals(); - } - - taxaNumber = arg.getExternalNodeCount(); - this.maxReassortments = maxReassort; - } - - public void calculateIntervals() { - intervals.clear(); - intervals.ensureCapacity(arg.getNodeCount()); - - NodeRef x; - for (int i = 0; i < arg.getInternalNodeCount(); i++) { - x = arg.getInternalNode(i); - if (arg.isReassortment(x)) { - intervals.add(new CoalescentInterval(arg.getNodeHeight(x), RECOMBINATION)); - } else { - intervals.add(new CoalescentInterval(arg.getNodeHeight(x), COALESCENT)); - } - } - for (int i = 0; i < arg.getExternalNodeCount(); i++) { - x = arg.getExternalNode(i); - if (arg.getNodeHeight(x) > 0.0) { - intervals.add(new CoalescentInterval(arg.getNodeHeight(x), NEW_SAMPLE)); - } - } - dr.util.HeapSort.sort(intervals); - - - double a = 0, b = 0; - for (int i = 0; i < intervals.size(); i++) { - b = intervals.get(i).length; - intervals.get(i).length = intervals.get(i).length - a; - a = b; - } - - intervalsKnown = true; - } - - public void handleModelChangedEvent(Model model, Object object, int index) { - if (model == arg) { - intervalsKnown = false; - } - likelihoodKnown = false; - } - - public void handleParameterChangedEvent(Parameter parameter, int index) { - likelihoodKnown = false; - } - - public void storeState() { - storedIntervals = new ArrayList(intervals.size()); - for (CoalescentInterval interval : intervals) { - storedIntervals.add(interval.clone()); - } - - intervalsKnown = likelihoodKnown = false; - - - storedIntervalsKnown = intervalsKnown; - storedLikelihoodKnown = likelihoodKnown; - storedLogLikelihood = logLikelihood; - - } - - public void restoreState() { - intervals = storedIntervals; - storedIntervals.clear(); - intervalsKnown = storedIntervalsKnown; - likelihoodKnown = storedLikelihoodKnown; - logLikelihood = storedLogLikelihood; - - intervalsKnown = likelihoodKnown = false; -// if (!intervalsKnown) { -// likelihoodKnown = false; -// } - } - - public boolean currentARGValid(boolean allowDoubleParents) { - if (!intervalsKnown) { - calculateIntervals(); - } - int taxa = taxaNumber; - - for (CoalescentInterval x : intervals) { - if (taxa == 1) - return false; - if (x.type == COALESCENT) - taxa--; - else if (x.type == RECOMBINATION) - taxa++; - else - throw new RuntimeException("Not implemented yet"); - } - if (!allowDoubleParents) { - for (int i = 0, n = arg.getNodeCount(); i < n; i++) { - NodeRef x = arg.getNode(i); - if (arg.isReassortment(x) && arg.getParent(x, 0) == arg.getParent(x, 1)) { - return false; - } - } - } - - return true; - } - - public double getLogLikelihood() { - if (likelihoodKnown) - return logLikelihood; - if (!intervalsKnown) - calculateIntervals(); - - likelihoodKnown = true; - - if (arg.getReassortmentNodeCount() > maxReassortments){ - logLikelihood = Double.NEGATIVE_INFINITY; - }else if(ancestralRestriction && !arg.isAncestral()){ - logLikelihood = Double.NEGATIVE_INFINITY; - }else{ - logLikelihood = calculateLogLikelihood( - popSize.getParameterValue(0), - recomRate.getParameterValue(0)); - } - - - return logLikelihood; - } - - private double chooseTwo(int n) { - return n * (n - 1) / 2.0; - } - - private double calculateLogLikelihood(double pSize, double rRate) { - - double logLike = 0.0; - int numberOfTaxa = taxaNumber; - - for (CoalescentInterval interval : intervals) { - - if (numberOfTaxa == 1) - return Double.NEGATIVE_INFINITY; - - double rate = (double) numberOfTaxa * - (numberOfTaxa - 1 + rRate) / (2.0 * pSize); - - logLike += Math.log(rate) - rate * interval.length; - - if (interval.type == COALESCENT) { - logLike += Math.log((double) (numberOfTaxa - 1) / - (numberOfTaxa - 1 + rRate)) - - Math.log(chooseTwo(numberOfTaxa)); - numberOfTaxa--; - } else if (interval.type == RECOMBINATION) { - logLike += Math.log(rRate / (numberOfTaxa - 1 + rRate)) - - Math.log((double) numberOfTaxa); - - numberOfTaxa++; - } else { - throw new RuntimeException("Not implemented yet"); - } - } - - assert numberOfTaxa == 1; - - return logLike; - } - - private class CoalescentInterval implements Comparable, - Cloneable { - public int type; - public double length; - - public CoalescentInterval(double length, int type) { - this.length = length; - this.type = type; - } - - public int compareTo(CoalescentInterval a) { - - if (a.length > this.length) { - return -1; - } else if (a.length == this.length) { - Logger.getLogger("dr.evomodel.coalescent").severe( - "The current ARG Model has 2 internal nodes " + - "at the same height"); - return 0; - } - return 1; - } - - public String toString() { - if (type == 0) { - return "(" + length + ", Coalescent)"; - } - return "(" + length + ", Recombination)"; - } - - public CoalescentInterval clone() { - return new CoalescentInterval(length, type); - } - - } - - public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { - - public String getParserDescription() { - return "A coalescent likelihood for an ARG model"; - } - - public Class getReturnType() { - return ARGCoalescentLikelihood.class; - } - - public String getParserName() { - return ARG_COALESCENT_MODEL; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private final XMLSyntaxRule[] rules = { - new ElementRule(POPULATION_SIZE, - new XMLSyntaxRule[]{new ElementRule(Parameter.class)}), - new ElementRule(RECOMBINATION_RATE, - new XMLSyntaxRule[]{new ElementRule(Parameter.class)}), - new ElementRule(ARG_MODEL, - new XMLSyntaxRule[]{new ElementRule(ARGModel.class)}), - AttributeRule.newBooleanRule(ANCESTRAL_RESTRICTION,true), - }; - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - XMLObject cxo = xo.getChild(RECOMBINATION_RATE); - Parameter rRate = (Parameter) cxo.getChild(Parameter.class); - - cxo = xo.getChild(POPULATION_SIZE); - Parameter pSize = (Parameter) cxo.getChild(Parameter.class); - - cxo = xo.getChild(ARG_MODEL); - ARGModel argModel = (ARGModel) cxo.getChild(ARGModel.class); - - int maxreassort = Integer.MAX_VALUE; - if (xo.hasAttribute(MAX_REASSORTMENTS)) { - maxreassort = xo.getIntegerAttribute(MAX_REASSORTMENTS); - } - - boolean ancestral = false; - if(xo.hasAttribute(ANCESTRAL_RESTRICTION)) - ancestral = xo.getBooleanAttribute(ANCESTRAL_RESTRICTION); - - return new ARGCoalescentLikelihood(pSize, rRate, argModel, false, maxreassort, ancestral); - } - - - }; - - public String toString() { - return getClass().getSimpleName() + " " + super.toString(); - } - - -} diff --git a/src/dr/evomodel/arg/coalescent/ARGUniformPrior.java b/src/dr/evomodel/arg/coalescent/ARGUniformPrior.java deleted file mode 100644 index 2b51603006..0000000000 --- a/src/dr/evomodel/arg/coalescent/ARGUniformPrior.java +++ /dev/null @@ -1,450 +0,0 @@ -/* - * ARGUniformPrior.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.arg.coalescent; - - -import dr.evomodel.arg.ARGModel; -import dr.xml.*; -import org.apache.commons.math.util.MathUtils; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.logging.Logger; - -public class ARGUniformPrior extends ARGCoalescentLikelihood { - - public static final String ARG_UNIFORM_PRIOR = "argUniformPrior"; - public static final String INITIAL_CALCULATIONS = "initialCalculations"; - public static final int INITIAL_DEFAULT = 5; - - - /** - * First index represents (number of taxa - 3). Second index - * represents (number of reassortments). - */ - public static final double[][] logARGCoalescentCount = { - //3 external taxa - {1.0986122886681098, 4.276666119016055, 8.265650165580329, - 12.882968485504067, 18.022948777876554, 23.61061585799083, - 29.589035299467483, 35.9136593725818, 42.54885778516801, - 49.465568765313016, 56.63967062533004, 64.05083469593846, - 71.6817017141028, 79.51727811078219, 87.54448452157624}, - //4 external taxa - {2.8903717578961645, 7.049254841255837, 11.72325121817378, - 16.888557143580204, 22.489284935076803, 28.475109395164285, - 34.804239049061785, 41.44233437710982, 48.360992220084476, - 55.53645069653148, 62.948589014628716, 70.58017373916618, - 78.41629051730933, 86.44391155847957, 94.65156231759461}, - //5 external taxa - {5.192956850890211, 10.127430784020902, 15.386536070471918, - 21.031563309246433, 27.041414773420907, 33.38480151281157, - 40.03192406503731, 46.95658863790172, 54.13620464676437, - 61.55131458837549, 69.18508096220405, 77.02283620054189, - 85.0517120025277, 93.26034012092553, 101.63861177667185}, - //6 external taxa - {7.90100705199242, 13.480736877978641, 19.249258325378765, - 25.32054548939157, 31.698755104859107, 38.36733349428991, - 45.30602732354885, 52.49523955146093, 59.917151710215464, - 67.55588200276209, 75.39734855785784, 83.42905687418532, - 91.63988547749693, 100.01989325102055, 108.56015364817871}, - //7 external taxa - {10.945529489715843, 17.07892753271249, 23.29838718386135, - 29.753407176990198, 36.467041602426036, 43.43431706668038, - 50.64269194407989, 58.077999881992824, 65.7264083635128, - 73.57505740705963, 81.61221669682189, 89.8272615722345, - 98.21058447998666, 106.75348902699808, 115.44808566836372}, - //8 external taxa - {14.277733999891046, 20.896472983408266, 27.5204956568849, - 34.32463786712059, 41.34646380715327, 48.590254195514014, - 56.04978852563933, 63.71543385947847, 71.57673212169905, - 79.62341044573522, 87.84577046007783, 96.23481579273648, - 104.78226604090887, 113.48052233027693, 122.32261419599219}, - //9 external taxa - {17.861252938347157, 24.912242385415205, 31.903176098451674, - 39.02769936297709, 46.334764858303096, 53.836163974100344, - 61.53092519032464, 69.4132445398445, 77.47555198269822, - 85.70981250210274, 94.10810078400579, 102.66285174696894, - 111.36695890554311, 120.21379947792728, 129.1972243144967}, - //10 external taxa - {21.667915428117478, 29.108649135506738, 36.43531279311537, - 43.855945609774885, 51.42860726365353, 59.171269494486445, - 67.08736948530374, 75.17436983012065, 83.4271948608094, - 91.83976176721744, 100.40570480277214, 109.11872661806457, - 117.97276669219758, 126.96207643311605, 136.08124559689557}, - //11 external taxa - {25.67524861334995, 33.470895149684544, 41.10703544874183, - 48.802991754828916, 56.62422391351782, 64.59385162827832, - 72.71905241455046, 81.00010003398279, 89.43409011267886, - 98.0166551565224, 106.74281045596386, 115.60738869034444, - 124.6052669677749, 133.73148419256228, 142.98129861277982}, - //12 external taxa - {29.864903355376374, 37.986383730127116, 45.90958634624165, - 53.86285360119818, 61.91774245806648, 70.10170706136994, - 78.42512661349667, 86.890712820353, 95.49746436335495, - 104.24253036074631, 113.12215615381358, 122.13218720871606, - 131.26834550980237, 140.52638287915215, 149.90216524590267}, - //13 external taxa - {34.22161218206597, 42.644274889635966, 50.83517511899286, - 59.02998615127507, 67.30534956176908, 75.69240403974487, - 84.20429128794189, 92.84585184006139, 101.61776251108103, - 110.51852076251443, 119.54547309663305, 128.69537701990959, - 137.96471924891867, 147.34989978600277, 156.84733922685047}, - //14 external taxa - {38.732471688582805, 47.43514810013058, 55.87684474986188, - 64.2992772236583, 72.78337269607047, 81.36342882144557, - 90.05498796388106, 98.86476107289788, 107.79491286633757, - 116.84514548111035, 126.01379567653075, 135.29844575074105, - 144.69627736969085, 154.20428208422834, 163.8193886161766}, - //15 external taxa - {43.38643203874033, 52.35074398686485, 61.028354989069626, - 69.6660218145462, 78.34831802900398, 87.11227051188368, - 95.97552137406072, 104.94643415554035, 114.02849935687857, - 123.22250024459373, 132.52766774855348, 141.9423328912873, - 151.46431112672838, 161.0911356940919, 170.82020228928107} - }; - - private ArrayList argNumber; - - public ARGUniformPrior(ARGModel arg, int max, int initial) { - super(ARG_UNIFORM_PRIOR, arg, max); - - addModel(arg); - - argNumber = new ArrayList(15); - - if (arg.getExternalNodeCount() - 3 < logARGCoalescentCount.length) { - Logger.getLogger("dr.evomodel").info("Creating ARGUniformPrior using stored arg counts"); - for (int i = 0, n = arg.getExternalNodeCount() - 3; i < logARGCoalescentCount[n].length; i++) - argNumber.add(logARGCoalescentCount[n][i]); - } else { - Logger.getLogger("dr.evomodel").info("Creating ARGUniformPrior by calculating arg counts"); - for (int i = 0, n = arg.getExternalNodeCount(); i < initial; i++) { - argNumber.add(logNumberARGS(n, i)); - } - } - } - - public double getLogARGNumber(int i) { - if (i >= argNumber.size()) { - argNumber.add(logNumberARGS(arg.getExternalNodeCount(), i)); - } - return argNumber.get(i); - } - - public double getLogLikelihood() { - if (likelihoodKnown) { - return logLikelihood; - } - - likelihoodKnown = true; - logLikelihood = calculateLogLikelihood(); - - - if (arg.getReassortmentNodeCount() > maxReassortments) - logLikelihood = Double.NEGATIVE_INFINITY; - else - logLikelihood = calculateLogLikelihood(); - - if (!currentARGValid(true)) { - logLikelihood = Double.NEGATIVE_INFINITY; - } - - return logLikelihood; - } - - public double calculateLogLikelihood() { - - - double treeHeight = arg.getNodeHeight(arg.getRoot()); - int internalNodes = arg.getInternalNodeCount() - 1; - - - double logLike = logFactorial(internalNodes) - (double) internalNodes * Math.log(treeHeight) - - getLogARGNumber(arg.getReassortmentNodeCount()); - - assert !Double.isInfinite(logLike) && !Double.isNaN(logLike); - - - return logLike; - } - - private double logFactorial(int n) { - double rValue = 0; - - for (int i = n; i > 0; i--) { - rValue += Math.log(i); - } - return rValue; - } - - - private int numberARGS(int taxa, int argNumber) { - int x = taxa; - int n = 2 * argNumber + taxa - 1; - - return shurikoRecursion(x, n); - } - - private int shurikoRecursion(int x, int n) { - int a = 0; - if (x == 0) { - a = 0; - } else if (x == 1) { - if (n == 0) { - a = 1; - } else { - a = 0; - } - } else if (n == 0) { - if (x == 1) { - a = 1; - } else { - a = 0; - } - } else if (x == n + 1) { - a = x * (x - 1) / 2 * shurikoRecursion(x - 1, n - 1); - } else { - a = x * shurikoRecursion(x + 1, n - 1) + x * (x - 1) / 2 * shurikoRecursion(x - 1, n - 1); - } - return a; - } - - public static double logNumberARGS(int start, int reassortments) { - Logger.getLogger("dr.evomodel").warning("Calculating ARG count for " + reassortments + " reassortments. This may take awhile"); - - if (reassortments == 0) { - double a = 0; - for (int i = start; i > 2; i--) { - a += Math.log(i * (i - 1) / 2.0); - } - return a; - } - - int[] max = new int[start - 3 + reassortments * 2]; - int[] x = new int[max.length]; - - int i = 0; - while (i < reassortments) { - x[i] = max[i] = 1; - i++; - } - while (i < max.length) { - x[i] = max[i] = -1; - i++; - } - double before = 100; - - double approx = 0; - while (x[0] != -9 && !stopCombination(x, start)) { - if (testCombination(x, start)) { - before = approx; - int[] y = generateValues(x, start); - approx += reduceThenDivide(y, generateValues(max, start)); - before = approx - before; - } - nextCombination(x); - } - - approx = Math.log(approx); - - int[] y = new int[max.length + 2]; - for (i = 0; i < max.length; i++) - y[i] = max[i]; - y[y.length - 2] = y[y.length - 1] = -1; - - max = generateValues(y, start); - - for (int k = 0; k < y.length; k++) - approx += Math.log(max[k]); - - return approx; - - } - - private static double reduceThenDivide(int[] top, int[] bottom) { - - if (false) { - for (int i = 0; i < top.length; i++) { - for (int j = 0; j < bottom.length; j++) { - int gcd = MathUtils.gcd(top[i], bottom[j]); - - if (gcd > 1) { - top[i] = top[i] / gcd; - bottom[j] = bottom[j] / gcd; - } - } - - } - - } - - Arrays.sort(top); - Arrays.sort(bottom); - - - double a = 1; - for (int i = 0; i < top.length; i++) - a *= (double) top[i] / bottom[i]; - return a; - - } - - private static int[] generateValues(int[] x, int start) { - int[] y = new int[x.length]; - - for (int i = 0; i < x.length; i++) { - if (x[i] == 1) - y[i] = start; - else - y[i] = start * (start - 1) / 2; - - start += x[i]; - - } - return y; - } - - private static boolean testCombination(int[] x, int start) { - - for (int i = 0; i < x.length; i++) { - start += x[i]; - if (start == 1) - return false; - } - return true; - - } - - private static boolean stopCombination(int[] x, int start) { - for (int i = 0; i < x.length; i++) { - if (x[i] == -1) { - start--; - if (start == 1) { - return true; - } - } else { - break; - } - } - return false; - } - - private static void nextCombination(int[] x) { - if (x[x.length - 1] == -1) { - int i = x.length - 1; - - while (i > -1) { - if (x[i] == 1) { - x[i] = -1; - x[i + 1] = 1; - return; - } else - i--; - - } - } else { - int endOnes = 0; - int i = x.length - 1; - while (x[i] == 1) { - endOnes++; - i--; - } - int nextOne = -1; - while (i > -1) { - if (x[i] == 1) { - nextOne = i; - break; - } else - i--; - - } - if (nextOne == -1) { - x[0] = -9; - return; - } - - x[nextOne] = -1; - x[nextOne + 1] = 1; - - for (i = 0; i < endOnes; i++) - x[i + nextOne + 2] = 1; - - i = nextOne + 2 + endOnes; - - while (i < x.length) { - x[i] = -1; - i++; - } - } - } - - - public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { - - public String getParserDescription() { - return "A uniform prior for an ARG model"; - } - - public Class getReturnType() { - return ARGUniformPrior.class; - } - - public String getParserName() { - return ARG_UNIFORM_PRIOR; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{ - new ElementRule(ARGModel.class), - - }; - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - ARGModel argModel = (ARGModel) xo.getChild(ARGModel.class); - - int max = Integer.MAX_VALUE; - if (xo.hasAttribute(MAX_REASSORTMENTS)) { - max = xo.getIntegerAttribute(MAX_REASSORTMENTS); - } - - int initial = INITIAL_DEFAULT; - if (xo.hasAttribute(INITIAL_CALCULATIONS)) { - initial = xo.getIntegerAttribute(INITIAL_CALCULATIONS); - } - - return new ARGUniformPrior(argModel, max, initial); - } - - - }; - - -} diff --git a/src/dr/evomodel/arg/coalescent/VeryOldCoalescentLikelihood.java b/src/dr/evomodel/arg/coalescent/VeryOldCoalescentLikelihood.java deleted file mode 100644 index 966a4a7c3f..0000000000 --- a/src/dr/evomodel/arg/coalescent/VeryOldCoalescentLikelihood.java +++ /dev/null @@ -1,660 +0,0 @@ -/* - * VeryOldCoalescentLikelihood.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.arg.coalescent; - -import dr.evolution.coalescent.DemographicFunction; -import dr.evolution.tree.NodeRef; -import dr.evolution.tree.Tree; -import dr.evolution.util.Units; -import dr.evomodel.coalescent.demographicmodel.DemographicModel; -import dr.evomodel.tree.TreeModel; -import dr.inference.model.*; -import dr.math.Binomial; -import dr.util.ComparableDouble; -import dr.util.HeapSort; -import dr.xml.*; - -import java.util.ArrayList; - - -/** - * A likelihood function for the coalescent. Takes a tree and a demographic model. - *

- * Parts of this class were derived from C++ code provided by Oliver Pybus. - * - * @author Andrew Rambaut - * @author Alexei Drummond - */ -public class VeryOldCoalescentLikelihood extends AbstractModelLikelihood implements Units { - - // PUBLIC STUFF - - public static final String COALESCENT_LIKELIHOOD = "veryOldCoalescentLikelihood"; - public static final String ANALYTICAL = "analytical"; - public static final String MODEL = "model"; - public static final String POPULATION_TREE = "populationTree"; - - /** - * Denotes an interval after which a coalescent event is observed - * (i.e. the number of lineages is smaller in the next interval) - */ - public static final int COALESCENT = 0; - - /** - * Denotes an interval at the end of which a new sample addition is - * observed (i.e. the number of lineages is larger in the next interval). - */ - public static final int NEW_SAMPLE = 1; - - /** - * Denotes an interval at the end of which nothing is - * observed (i.e. the number of lineages is the same in the next interval). - */ - public static final int NOTHING = 2; - - - public VeryOldCoalescentLikelihood(Tree tree, DemographicModel demoModel) { - this(COALESCENT_LIKELIHOOD, tree, demoModel, true); - } - - public VeryOldCoalescentLikelihood(String name, Tree tree, DemographicModel demoModel, boolean setupIntervals) { - - super(name); - - this.tree = tree; - this.demoModel = demoModel; - if (tree instanceof TreeModel) { - addModel((TreeModel) tree); - } - if (demoModel != null) { - addModel(demoModel); - } - if (setupIntervals) setupIntervals(); - - addStatistic(new DeltaStatistic()); - } - - VeryOldCoalescentLikelihood(String name) { - super(name); - } - - // ************************************************************** - // Extendable methods - // ************************************************************** - - /** - * @return the node ref of the MRCA of this coalescent prior in the given tree. - */ - public NodeRef getMRCAOfCoalescent(Tree tree) { - return tree.getRoot(); - } - - /** - * @return an array of noderefs that represent the MRCAs of subtrees to exclude from coalescent prior. - * May return null if no subtrees should be excluded. - */ - public NodeRef[] getExcludedMRCAs(Tree tree) { - return null; - } - - // ************************************************************** - // ModelListener IMPLEMENTATION - // ************************************************************** - - protected void handleModelChangedEvent(Model model, Object object, int index) { - if (model == tree) { - // treeModel has changed so recalculate the intervals - intervalsKnown = false; - } else { - // demoModel has changed so we don't need to recalculate the intervals - } - - likelihoodKnown = false; - } - - // ************************************************************** - // VariableListener IMPLEMENTATION - // ************************************************************** - - protected final void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) { - } // No parameters to respond to - - // ************************************************************** - // Model IMPLEMENTATION - // ************************************************************** - - /** - * Stores the precalculated state: in this case the intervals - */ - protected void storeState() { - System.arraycopy(intervals, 0, storedIntervals, 0, intervals.length); - System.arraycopy(lineageCounts, 0, storedLineageCounts, 0, lineageCounts.length); - storedIntervalsKnown = intervalsKnown; - storedIntervalCount = intervalCount; - storedLikelihoodKnown = likelihoodKnown; - storedLogLikelihood = logLikelihood; - } - - /** - * Restores the precalculated state: that is the intervals of the tree. - */ - protected void restoreState() { - System.arraycopy(storedIntervals, 0, intervals, 0, storedIntervals.length); - System.arraycopy(storedLineageCounts, 0, lineageCounts, 0, storedLineageCounts.length); - intervalsKnown = storedIntervalsKnown; - intervalCount = storedIntervalCount; - likelihoodKnown = storedLikelihoodKnown; - logLikelihood = storedLogLikelihood; - - if (!intervalsKnown) { - likelihoodKnown = false; - } - } - - protected final void acceptState() { - } // nothing to do - - /** - * Adopt the state of the model from source. - */ - protected final void adoptState(Model source) { - // all we need to do is force a recalculation of intervals - makeDirty(); - } - - // ************************************************************** - // Likelihood IMPLEMENTATION - // ************************************************************** - - public final Model getModel() { - return this; - } - - public double getLogLikelihood() { - if (!likelihoodKnown) { - logLikelihood = calculateLogLikelihood(); - likelihoodKnown = true; - } - return logLikelihood; - } - - public final void makeDirty() { - likelihoodKnown = false; - intervalsKnown = false; - } - - /** - * Calculates the log likelihood of this set of coalescent intervals, - * given a demographic model. - */ - public double calculateLogLikelihood() { - - if ( !intervalsKnown ) setupIntervals(); - - if (demoModel == null) return calculateAnalyticalLogLikelihood(); - - double logL = 0.0; - - double currentTime = 0.0; - - DemographicFunction demoFunction = demoModel.getDemographicFunction(); - - for (int j = 0; j < intervalCount; j++) { - - - logL += calculateIntervalLikelihood(demoFunction, intervals[j], currentTime, lineageCounts[j], - getIntervalType(j)); - - // insert zero-length coalescent intervals - int diff = getCoalescentEvents(j) - 1; - for (int k = 0; k < diff; k++) { - logL += calculateIntervalLikelihood(demoFunction, 0.0, currentTime, lineageCounts[j] - k - 1, COALESCENT); - } - - currentTime += intervals[j]; - } - - return logL; - } - - private double calculateAnalyticalLogLikelihood() { - - final double lambda = getLambda(); - final int n = tree.getExternalNodeCount(); - - // assumes a 1/theta prior - //logLikelihood = Math.log(1.0/Math.pow(lambda,n)); - - // assumes a flat prior - double logL = Math.log(1.0 / Math.pow(lambda, n - 1)); - return logL; - } - - /** - * Returns the likelihood of a given *coalescent* interval - */ - public final double calculateIntervalLikelihood(DemographicFunction demoFunction, double width, double timeOfPrevCoal, int lineageCount) { - - return calculateIntervalLikelihood(demoFunction, width, timeOfPrevCoal, lineageCount, COALESCENT); - } - - /** - * Returns the likelihood of a given interval,coalescent or otherwise. - */ - public final double calculateIntervalLikelihood(DemographicFunction demoFunction, double width, double timeOfPrevCoal, - int lineageCount, int type) { - //binom.setMax(lineageCount); - - double timeOfThisCoal = width + timeOfPrevCoal; - -// System.err.printf("s: %7.6f f: %7.6f, %d, %d\n", timeOfPrevCoal, timeOfThisCoal, lineageCount, type); - double intervalArea = demoFunction.getIntegral(timeOfPrevCoal, timeOfThisCoal); - double like = 0; - switch (type) { - case COALESCENT: - like = - -Math.log(demoFunction.getDemographic(timeOfThisCoal)) - - (Binomial.choose2(lineageCount) * intervalArea); - break; - case NEW_SAMPLE: - like = -(Binomial.choose2(lineageCount) * intervalArea); - break; - } - - return like; - } - - /** - * Returns a factor lambda such that the likelihood can be expressed as - * 1/theta^(n-1) * exp(-lambda/theta). This allows theta to be integrated - * out analytically. :-) - */ - private double getLambda() { - double lambda = 0.0; - for (int i = 0; i < getIntervalCount(); i++) { - lambda += (intervals[i] * lineageCounts[i]); - } - lambda /= 2; - - return lambda; - } - - /** - * Recalculates all the intervals from the tree model. - */ - protected final void setupIntervals() { - - double MULTIFURCATION_LIMIT = 1e-9; - - ArrayList times = new ArrayList(); - ArrayList childs = new ArrayList(); - collectAllTimes(tree, getMRCAOfCoalescent(tree), getExcludedMRCAs(tree), times, childs); - int[] indices = new int[times.size()]; - - HeapSort.sort(times, indices); - - int maxIntervalCount = tree.getNodeCount(); - - if (intervals == null) { - intervals = new double[maxIntervalCount]; - lineageCounts = new int[maxIntervalCount]; - storedIntervals = new double[maxIntervalCount]; - storedLineageCounts = new int[maxIntervalCount]; - } - - // start is the time of the first tip - double start = ((ComparableDouble) times.get(indices[0])).doubleValue(); - int numLines = 0; - int i = 0; - intervalCount = 0; - while (i < times.size()) { - - int lineagesRemoved = 0; - int lineagesAdded = 0; - - double finish = ((ComparableDouble) times.get(indices[i])).doubleValue(); - double next = finish; - - while (Math.abs(next - finish) < MULTIFURCATION_LIMIT) { - int children = childs.get(indices[i]); - if (children == 0) { - lineagesAdded += 1; - } else { - lineagesRemoved += (children - 1); - } - i += 1; - if (i < times.size()) { - next = ((ComparableDouble) times.get(indices[i])).doubleValue(); - } else break; - } - //System.out.println("time = " + finish + " removed = " + lineagesRemoved + " added = " + lineagesAdded); - if (lineagesAdded > 0) { - - if (intervalCount > 0 || ((finish - start) > MULTIFURCATION_LIMIT)) { - intervals[intervalCount] = finish - start; - lineageCounts[intervalCount] = numLines; - intervalCount += 1; - } - - start = finish; - } - // add sample event - numLines += lineagesAdded; - - if (lineagesRemoved > 0) { - - intervals[intervalCount] = finish - start; - lineageCounts[intervalCount] = numLines; - intervalCount += 1; - start = finish; - } - // coalescent event - numLines -= lineagesRemoved; - } - intervalsKnown = true; - } - - - /** - * extract coalescent times and tip information into ArrayList times from tree. - * - * @param node the node to start from - * @param excludeBelow an optional array of nodes to exclude (corresponding subtrees) from density. - */ - private static void collectAllTimes(Tree tree, NodeRef node, NodeRef[] excludeBelow, ArrayList times, ArrayList childs) { - - times.add(new ComparableDouble(tree.getNodeHeight(node))); - childs.add(tree.getChildCount(node)); - - for (int i = 0; i < tree.getChildCount(node); i++) { - NodeRef child = tree.getChild(node, i); - if (excludeBelow == null) { - collectAllTimes(tree, child, excludeBelow, times, childs); - } else { - // check if this subtree is included in the coalescent density - boolean include = true; - for(NodeRef anExcludeBelow : excludeBelow) { - if( anExcludeBelow.getNumber() == child.getNumber() ) { - include = false; - break; - } - } - if (include) collectAllTimes(tree, child, excludeBelow, times, childs); - } - } - } - - - /** - * get number of intervals - */ - public final int getIntervalCount() { - return intervalCount; - } - - /** - * Gets an interval. - */ - public final double getInterval(int i) { - if (i >= intervalCount) throw new IllegalArgumentException(); - return intervals[i]; - } - - /** - * Returns the number of uncoalesced lineages within this interval. - * Required for s-coalescents, where new lineages are added as - * earlier samples are come across. - */ - public final int getLineageCount(int i) { - if (i >= intervalCount) throw new IllegalArgumentException(); - return lineageCounts[i]; - } - - /** - * Returns the number coalescent events in an interval - */ - public final int getCoalescentEvents(int i) { - - if (i >= intervalCount) throw new IllegalArgumentException(); - if (i < intervalCount - 1) { - return lineageCounts[i] - lineageCounts[i + 1]; - } else { - return lineageCounts[i] - 1; - } - } - - /** - * Returns the type of interval observed. - */ - public final int getIntervalType(int i) { - - if (i >= intervalCount) throw new IllegalArgumentException(); - int numEvents = getCoalescentEvents(i); - - if (numEvents > 0) return COALESCENT; - else if (numEvents < 0) return NEW_SAMPLE; - else return NOTHING; - } - - /** - * get the total height of the genealogy represented by these - * intervals. - */ - public final double getTotalHeight() { - - double height = 0.0; - for (int j = 0; j < intervalCount; j++) { - height += intervals[j]; - } - return height; - } - - /** - * Checks whether this set of coalescent intervals is fully resolved - * (i.e. whether is has exactly one coalescent event in each - * subsequent interval) - */ - public final boolean isBinaryCoalescent() { - for (int i = 0; i < intervalCount; i++) { - if (getCoalescentEvents(i) != 1) return false; - } - - return true; - } - - /** - * Checks whether this set of coalescent intervals coalescent only - * (i.e. whether is has exactly one or more coalescent event in each - * subsequent interval) - */ - public final boolean isCoalescentOnly() { - for (int i = 0; i < intervalCount; i++) { - if (getCoalescentEvents(i) < 1) return false; - } - return true; - } - - public String toString() { - return Double.toString(getLogLikelihood()); - - } - - // ************************************************************** - // Units IMPLEMENTATION - // ************************************************************** - - - public final Type getUnits() { - return demoModel.getUnits(); - } - - public void setUnits(Type units) { - demoModel.setUnits(units); - - } - - // **************************************************************** - // Inner classes - // **************************************************************** - - public class DeltaStatistic extends Statistic.Abstract { - - public DeltaStatistic() { - super("delta"); - } - - public int getDimension() { - return 1; - } - - public double getStatisticValue(int i) { - throw new RuntimeException("Not implemented"); -// return IntervalList.Utils.getDelta(intervals); - } - - } - - // **************************************************************** - // Private and protected stuff - // **************************************************************** - - public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { - - public String getParserName() { - return COALESCENT_LIKELIHOOD; - } - - public Object parseXMLObject(XMLObject xo) { - - XMLObject cxo = xo.getChild(MODEL); - DemographicModel demoModel = (DemographicModel) cxo.getChild(DemographicModel.class); - - cxo = xo.getChild(POPULATION_TREE); - TreeModel treeModel = (TreeModel) cxo.getChild(TreeModel.class); - - return new VeryOldCoalescentLikelihood(treeModel, demoModel); - } - - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - - public String getParserDescription() { - return "This element represents the likelihood of the tree given the demographic function."; - } - - public Class getReturnType() { - return Likelihood.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private final XMLSyntaxRule[] rules = { - new ElementRule(MODEL, new XMLSyntaxRule[]{ - new ElementRule(DemographicModel.class) - }), - new ElementRule(POPULATION_TREE, new XMLSyntaxRule[]{ - new ElementRule(TreeModel.class) - }), - }; - }; - - // **************************************************************** - // Private and protected stuff - // **************************************************************** - -/* public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { - - public String getParserName() { return COALESCENT_LIKELIHOOD; } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - DemographicModel demoModel = null; - if (xo.hasAttribute(MODEL)) { - demoModel = (DemographicModel)xo.getAttribute(MODEL); - } - TreeModel treeModel = (TreeModel)xo.getAttribute(TREE); - return new VeryOldCoalescentLikelihood(treeModel, demoModel); - } - - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - - public String getParserDescription() { - return "This element represents the likelihood of the tree given the demographic function."; - } - - public Class getReturnType() { return Likelihood.class; } - - public XMLSyntaxRule[] getSyntaxRules() { return rules; } - - private XMLSyntaxRule[] rules = new XMLSyntaxRule[] { - new XORRule( - new EnumAttributeRule(ANALYTICAL, new String[] { "constant" }), - new AttributeRule(MODEL, DemographicModel.class) - ), - new AttributeRule(TREE, TreeModel.class) - }; - };*/ - - /** - * The demographic model. - */ - DemographicModel demoModel = null; - - /** - * The tree. - */ - Tree tree = null; - - /** - * The widths of the intervals. - */ - double[] intervals; - private double[] storedIntervals; - - /** - * The number of uncoalesced lineages within a particular interval. - */ - int[] lineageCounts; - private int[] storedLineageCounts; - - boolean intervalsKnown = false; - protected boolean storedIntervalsKnown = false; - - double logLikelihood; - protected double storedLogLikelihood; - boolean likelihoodKnown = false; - protected boolean storedLikelihoodKnown = false; - - int intervalCount = 0; - private int storedIntervalCount = 0; -} \ No newline at end of file diff --git a/src/dr/evomodel/arg/likelihood/ARGLikelihood.java b/src/dr/evomodel/arg/likelihood/ARGLikelihood.java deleted file mode 100644 index 591d6ed83d..0000000000 --- a/src/dr/evomodel/arg/likelihood/ARGLikelihood.java +++ /dev/null @@ -1,645 +0,0 @@ -/* - * ARGLikelihood.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -/* - * TreeLikelihood.java - * - * (c) 2002-2005 BEAST Development Core Team - * - * This package may be distributed under the - * Lesser Gnu Public Licence (LGPL) - */ - -package dr.evomodel.arg.likelihood; - -import dr.evolution.alignment.PatternList; -import dr.evolution.tree.NodeRef; -import dr.evolution.tree.Tree; -import dr.evolution.util.TaxonList; -import dr.evomodel.arg.ARGModel; -import dr.evomodel.arg.ARGTree; -import dr.evomodel.arg.operators.ARGPartitioningOperator; -import dr.evomodel.branchratemodel.BranchRateModel; -import dr.evomodel.branchratemodel.DefaultBranchRateModel; -import dr.oldevomodel.sitemodel.SiteModel; -import dr.oldevomodel.substmodel.FrequencyModel; -import dr.evomodel.treelikelihood.*; -import dr.inference.model.Likelihood; -import dr.inference.model.Model; -import dr.inference.model.Parameter; -import dr.oldevomodel.treelikelihood.*; -import dr.xml.*; - -import java.util.logging.Logger; -import java.util.*; - -/** - * ARGLikelihood - implements a Likelihood Function for sequences on an ancestral recombination graph. - * - * @author Marc Suchard - */ - -public class ARGLikelihood extends AbstractARGLikelihood { - - public static final String ARG_LIKELIHOOD = "argTreeLikelihood"; - public static final String USE_AMBIGUITIES = "useAmbiguities"; - public static final String STORE_PARTIALS = "storePartials"; - public static final String USE_SCALING = "useScaling"; - - /** - * Constructor. - */ - public ARGLikelihood(PatternList patternList, - ARGModel treeModel, - SiteModel siteModel, - BranchRateModel branchRateModel, - boolean useAmbiguities, - boolean storePartials, - boolean useScaling) { - - super(ARG_LIKELIHOOD, patternList, treeModel); - - partition = treeModel.addLikelihoodCalculator(this); - - this.storePartials = storePartials; - this.useAmbiguities = useAmbiguities; - - try { - this.siteModel = siteModel; - addModel(siteModel); - - this.frequencyModel = siteModel.getFrequencyModel(); - addModel(frequencyModel); - - integrateAcrossCategories = siteModel.integrateAcrossCategories(); - - this.categoryCount = siteModel.getCategoryCount(); - - if (integrateAcrossCategories) { - if (patternList.getDataType() instanceof dr.evolution.datatype.Nucleotides) { - - if (NativeNucleotideLikelihoodCore.isAvailable()) { - - Logger.getLogger("dr.evomodel").info("TreeLikelihood using native nucleotide likelihood core"); - likelihoodCore = new NativeNucleotideLikelihoodCore(); - } else { - - Logger.getLogger("dr.evomodel").info("TreeLikelihood using Java nucleotide likelihood core"); - likelihoodCore = new NucleotideLikelihoodCore(); - } - - } else if (patternList.getDataType() instanceof dr.evolution.datatype.AminoAcids) { - - if (NativeAminoAcidLikelihoodCore.isAvailable()) { - Logger.getLogger("dr.evomodel").info("TreeLikelihood using native amino acid likelihood core"); - likelihoodCore = new NativeAminoAcidLikelihoodCore(); - } else { - Logger.getLogger("dr.evomodel").info("TreeLikelihood using java likelihood core"); - likelihoodCore = new AminoAcidLikelihoodCore(); - } - } else if (patternList.getDataType() instanceof dr.evolution.datatype.Codons) { - Logger.getLogger("dr.evomodel").info("TreeLikelihood using Java codon likelihood core"); -// likelihoodCore = new CodonLikelihoodCore(patternList.getStateCount()); - this.useAmbiguities = true; - throw new RuntimeException("Still need to merge codon likelihood core"); - } else { - if (patternList.getDataType() instanceof dr.evolution.datatype.OldHiddenNucleotides && - NativeCovarionLikelihoodCore.isAvailable()) { - Logger.getLogger("dr.evomodel").info("TreeLikelihood using native covarion likelihood core"); - likelihoodCore = new NativeCovarionLikelihoodCore(); - } else { - Logger.getLogger("dr.evomodel").info("TreeLikelihood using Java general likelihood core"); - likelihoodCore = new GeneralLikelihoodCore(patternList.getStateCount()); - } - - } - } else { - - Logger.getLogger("dr.evomodel").info("TreeLikelihood using Java general likelihood core"); - likelihoodCore = new GeneralLikelihoodCore(patternList.getStateCount()); - } - Logger.getLogger("dr.evomodel").info(" " + (useAmbiguities ? "Using" : "Ignoring") + " ambiguities in tree likelihood."); - Logger.getLogger("dr.evomodel").info(" Partial likelihood scaling " + (useScaling ? "on." : "off.")); - - if (branchRateModel != null) { - this.branchRateModel = branchRateModel; - Logger.getLogger("dr.evomodel").info("Branch rate model used: " + branchRateModel.getModelName()); - } else { - this.branchRateModel = new DefaultBranchRateModel(); - } - addModel(this.branchRateModel); - - probabilities = new double[stateCount * stateCount]; - -// likelihoodCore.initialize(nodeCount, patternCount, categoryCount, integrateAcrossCategories, useScaling); - likelihoodCore.initialize(nodeCount, patternCount, categoryCount, integrateAcrossCategories); - - int extNodeCount = treeModel.getExternalNodeCount(); - int intNodeCount = treeModel.getInternalNodeCount(); - - for (int i = 0; i < extNodeCount; i++) { - // Find the id of tip i in the patternList - String id = treeModel.getTaxonId(i); - int index = patternList.getTaxonIndex(id); - -// System.err.println("id = "+id+" index = "+index); - - if (index == -1) { - throw new TaxonList.MissingTaxonException("Taxon, " + id + ", in tree, " + treeModel.getId() + - ", is not found in patternList, " + patternList.getId()); - } - - if (useAmbiguities) { - setPartials(likelihoodCore, patternList, categoryCount, index, i); - } else { - setStates(likelihoodCore, patternList, index, i); - } - } - -// System.exit(-1); - for (int i = 0; i < intNodeCount; i++) { - likelihoodCore.createNodePartials(extNodeCount + i); - } - } catch (TaxonList.MissingTaxonException mte) { - throw new RuntimeException(mte.toString()); - } - - } - - // ************************************************************** - // ModelListener IMPLEMENTATION - // ************************************************************** - - - private static final boolean NO_CACHING = false; - - /** - * Handles model changed events from the submodels. - */ - protected void handleModelChangedEvent(Model model, Object object, int index) { - - if (NO_CACHING) { - reconstructTree = true; - updateAllNodes(); - } - - if (model == treeModel) { - if (object instanceof ARGModel.ARGTreeChangedEvent) { - ARGModel.ARGTreeChangedEvent event = (ARGModel.ARGTreeChangedEvent) object; - if (event.isSizeChanged() ) { - updateAllNodes(); // TODO Update only affected portion of tree - reconstructTree = true; - } else if (event.isNodeChanged()) { - // If a node event occurs the node and its two child nodes - // are flagged for updating (this will result in everything - // above being updated as well. Node events occur when a node - // is added to a branch, removed from a branch or its height or - // rate changes. - - NodeRef treeNode = mapARGNodesToTreeNodes.get(event.getNode()); - if ( treeNode != null ) { - if (event.isHeightChanged() || event.isRateChanged()) { - updateNodeAndChildren(treeNode); - } else { - reconstructTree = true; -// updateNodeAndChildren(treeNode); // TODO This doesn't work with sizeChange; why??? - updateAllNodes(); - } - } - } else if (event.isTreeChanged()) { - // Full tree events result in a complete updating of the tree likelihood - // These include adding and removing nodes - // TODO ARG rearrangements still call this; they should not - reconstructTree = true; - updateAllNodes(); - } else { - // Other event types are ignored (probably trait changes). - throw new RuntimeException("Another tree event has occured (possibly a trait change)."); - } - } else if (object instanceof ARGPartitioningOperator.PartitionChangedEvent) { - final boolean[] updatePartition = ((ARGPartitioningOperator.PartitionChangedEvent) object).getUpdatedPartitions(); - if (updatePartition[partition]) { - reconstructTree = true; - updateAllNodes(); // TODO Probably does not affect entire tree; fix - } - } else if (object instanceof Parameter) { - // ignore, most of these are handled in isNodeChanged() - } else - throw new RuntimeException("Unexpected ARGModel update "+object.getClass()); - - } else if (model == branchRateModel) { - // TODO Only update affected branches - updateAllNodes(); - } else if (model == frequencyModel) { - updateAllNodes(); - } else if (model instanceof SiteModel) { - updateAllNodes(); - } else { - throw new RuntimeException("Unknown componentChangedEvent"); - } - - super.handleModelChangedEvent(model, object, index); - } - - // ************************************************************** - // Model IMPLEMENTATION - // ************************************************************** - - /** - * Stores the additional state other than model components - */ - protected void storeState() { - - if (storePartials) { - likelihoodCore.storeState(); - } - super.storeState(); - } - - /** - * Restore the additional stored state - */ - protected void restoreState() { - - if (storePartials) { - likelihoodCore.restoreState(); - } else { - updateAllNodes(); - } - reconstructTree = true; // currently the tree is not cached, because the ARG that generates it is cached - super.restoreState(); - } - - private int getUnusedInt(Map inMap) { - Collection intSet = inMap.values(); - int i = tree.getExternalNodeCount(); - while( intSet.contains(i) ) - i++; - return i; - } - - - private Set unsetNodes = null; - - private void reconstructTree() { - - oldTree = tree; - oldMapARGNodesToInts = mapARGNodesToInts; - - tree = new ARGTree(treeModel, partition); - reconstructTree = false; - mapARGNodesToInts = new HashMap(tree.getInternalNodeCount()); - mapARGNodesToTreeNodes = tree.getMapping(); - - if (oldTree == null) { - // First initialization - for(int i=0; i(); - else - unsetNodes.clear(); - - // Copy over numbers for nodes that still exist in tree - for (int i = 0; i < tree.getInternalNodeCount(); i++) { - NodeRef newNode = tree.getInternalNode(i); - NodeRef argNode = treeModel.getMirrorNode(newNode); - - if (oldMapARGNodesToInts.containsKey(argNode)) { // was in old tree - - int oldNumber = oldMapARGNodesToInts.get(argNode); - treeModel.setNodeNumber(newNode,oldNumber); - mapARGNodesToInts.put(argNode,oldNumber); - } else // was not in old tree - unsetNodes.add(newNode); - } - - // Set unused numbers for nodes that are new and mark for update - for (NodeRef node : unsetNodes) { - int newNumber = getUnusedInt(mapARGNodesToInts); - treeModel.setNodeNumber(node,newNumber); - mapARGNodesToInts.put(node,newNumber); - updateNode[newNumber] = true; - } - } - } - - // ************************************************************** - // Likelihood IMPLEMENTATION - // ************************************************************** - - /** - * Calculate the log likelihood of the current state. - * - * @return the log likelihood. - */ - protected double calculateLogLikelihood() { - - if (reconstructTree) { - reconstructTree(); - } - - NodeRef root = tree.getRoot(); - - if (rootPartials == null) { - rootPartials = new double[patternCount * stateCount]; - } - - if (patternLogLikelihoods == null) { - patternLogLikelihoods = new double[patternCount]; - } - - if (!integrateAcrossCategories) { - if (siteCategories == null) { - siteCategories = new int[patternCount]; - } - for (int i = 0; i < patternCount; i++) { - siteCategories[i] = siteModel.getCategoryOfSite(i); - } - } - - try { - traverse(tree, root); - } catch (NegativeBranchLengthException e) { - System.err.println("Negative branch length found, trying to return 0 likelihood"); - return Double.NEGATIVE_INFINITY; - } - - //******************************************************************** - // after traverse all nodes and patterns have been updated -- - //so change flags to reflect this. - for (int i = 0; i < nodeCount; i++) { - updateNode[i] = false; - } - //******************************************************************** - - double logL = 0.0; - - for (int i = 0; i < patternCount; i++) { -// System.err.printf("Pattern %2d: %5.4f %5.4f\n",i,patternLogLikelihoods[i],patternWeights[i]); - logL += patternLogLikelihoods[i] * patternWeights[i]; - } - - return logL; - } - - class NegativeBranchLengthException extends Exception { - - } - - /** - * Traverse the tree calculating partial likelihoods. - * - * @return whether the partials for this node were recalculated. - */ - private boolean traverse(Tree tree, NodeRef node) throws NegativeBranchLengthException { - - boolean update = false; - - int nodeNum = node.getNumber(); -// System.err.println(nodeNum); - - NodeRef parent = tree.getParent(node); - - - - // First update the transition probability matrix(ices) for this branch - if (parent != null && updateNode[nodeNum]) { - - - double branchRate = branchRateModel.getBranchRate(tree, node); - - // Get the operational time of the branch - double branchTime = branchRate * (tree.getNodeHeight(parent) - tree.getNodeHeight(node)); - if (branchTime < 0.0) { - if (!DEBUG) { - throw new RuntimeException("Negative branch length: " + branchTime); - } else{ - throw new NegativeBranchLengthException(); - } - } - - for (int i = 0; i < categoryCount; i++) { - double branchLength = siteModel.getRateForCategory(i) * branchTime; - siteModel.getSubstitutionModel().getTransitionProbabilities(branchLength, probabilities); - likelihoodCore.setNodeMatrix(nodeNum, i, probabilities); - } - - update = true; - } - - // If the node is internal, update the partial likelihoods. - if (!tree.isExternal(node)) { - - int nodeCount = tree.getChildCount(node); - if (nodeCount != 2) - throw new RuntimeException("binary trees only!"); - - // Traverse down the two child nodes - NodeRef child1 = tree.getChild(node, 0); - boolean update1 = traverse(tree, child1); - - NodeRef child2 = tree.getChild(node, 1); - boolean update2 = traverse(tree, child2); - - // If either child node was updated then update this node too - if (update1 || update2) { - - int childNum1 = child1.getNumber(); - int childNum2 = child2.getNumber(); - - if (integrateAcrossCategories) { - likelihoodCore.calculatePartials(childNum1, childNum2, nodeNum); - } else { - likelihoodCore.calculatePartials(childNum1, childNum2, nodeNum, - siteCategories); - } - - if (parent == null) { - // No parent this is the root of the tree - - // calculate the pattern likelihoods - double[] frequencies = frequencyModel.getFrequencies(); - - if (integrateAcrossCategories) { - - // moved this call to here, because non-integrating siteModels don't need to support it - AD - double[] proportions = siteModel.getCategoryProportions(); - likelihoodCore.integratePartials(nodeNum, proportions, rootPartials); - } else { - likelihoodCore.getPartials(nodeNum, rootPartials); - } - - likelihoodCore.calculateLogLikelihoods(rootPartials, frequencies, patternLogLikelihoods); - } - - update = true; - } - } - - return update; - - } - - /** - * The XML parser - */ - public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { - - public String getParserName() { - return ARG_LIKELIHOOD; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - boolean useAmbiguities = false; - boolean storePartials = true; - boolean useScaling = false; - if (xo.hasAttribute(USE_AMBIGUITIES)) { - useAmbiguities = xo.getBooleanAttribute(USE_AMBIGUITIES); - } - if (xo.hasAttribute(STORE_PARTIALS)) { - storePartials = xo.getBooleanAttribute(STORE_PARTIALS); - } - if (xo.hasAttribute(USE_SCALING)) { - useScaling = xo.getBooleanAttribute(USE_SCALING); - } - PatternList patternList = (PatternList) xo.getChild(PatternList.class); - ARGModel treeModel = (ARGModel) xo.getChild(ARGModel.class); - SiteModel siteModel = (SiteModel) xo.getChild(SiteModel.class); - - BranchRateModel branchRateModel = (BranchRateModel) xo.getChild(BranchRateModel.class); - - return new ARGLikelihood(patternList, treeModel, siteModel, branchRateModel, useAmbiguities, storePartials, useScaling); - } - - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - - public String getParserDescription() { - return "This element represents the likelihood of a patternlist on a tree given the site model."; - } - - public Class getReturnType() { - return Likelihood.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private final XMLSyntaxRule[] rules = { - AttributeRule.newBooleanRule(USE_AMBIGUITIES, true), - AttributeRule.newBooleanRule(STORE_PARTIALS, true), - AttributeRule.newBooleanRule(USE_SCALING, true), - new ElementRule(PatternList.class), - new ElementRule(ARGModel.class), - new ElementRule(SiteModel.class), - new ElementRule(BranchRateModel.class, true) - }; - }; - - /** - * XML Serializer for parallelization - * - */ - -// public Element toXML() { -// Element likelihoodElement -// } - - // ************************************************************** - // INSTANCE VARIABLES - // ************************************************************** - - /** - * the frequency model for these sites - */ - protected FrequencyModel frequencyModel = null; - - /** - * the site model for these sites - */ - protected SiteModel siteModel = null; - - /** - * the branch rate model - */ - protected BranchRateModel branchRateModel = null; - - private boolean storePartials = false; - - private boolean integrateAcrossCategories = false; - - /** - * the categories for each site - */ - protected int[] siteCategories = null; - - /** - * the root partial likelihoods - */ - protected double[] rootPartials = null; - - /** - * the pattern likelihoods - */ - protected double[] patternLogLikelihoods = null; - - /** - * the number of rate categories - */ - protected int categoryCount; - - /** - * an array used to store transition probabilities - */ - protected double[] probabilities; - - /** - * the LikelihoodCore - */ - protected LikelihoodCore likelihoodCore; - - private boolean useAmbiguities; - - private boolean reconstructTree = true; - private ARGTree tree = null; - private ARGTree oldTree; - - private Map mapARGNodesToInts = null; - private Map oldMapARGNodesToInts; - - private Map mapARGNodesToTreeNodes = null; - - private static final boolean DEBUG = true; -} \ No newline at end of file diff --git a/src/dr/evomodel/arg/likelihood/AbstractARGLikelihood.java b/src/dr/evomodel/arg/likelihood/AbstractARGLikelihood.java deleted file mode 100644 index f73376684f..0000000000 --- a/src/dr/evomodel/arg/likelihood/AbstractARGLikelihood.java +++ /dev/null @@ -1,336 +0,0 @@ -/* - * AbstractARGLikelihood.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -/* - * AbstractARGLikelihood.java - * - * (c) 2002-2005 BEAST Development Core Team - * - * This package may be distributed under the - * Lesser Gnu Public Licence (LGPL) - */ - -package dr.evomodel.arg.likelihood; - -import dr.evolution.alignment.PatternList; -import dr.evolution.datatype.DataType; -import dr.evolution.tree.NodeRef; -import dr.evomodel.arg.ARGModel; -import dr.oldevomodel.treelikelihood.LikelihoodCore; -import dr.inference.model.*; - -/** - * AbstractTreeLikelihood - a base class for likelihood calculators of sites on a tree. - * - * @author Andrew Rambaut - */ - -public abstract class AbstractARGLikelihood extends AbstractModelLikelihood implements ParallelLikelihood { - - public AbstractARGLikelihood(String name, PatternList patternList, - ARGModel treeModel) { - - super(name); - - this.patternList = patternList; - this.dataType = patternList.getDataType(); - patternCount = patternList.getPatternCount(); - stateCount = dataType.getStateCount(); - - patternWeights = patternList.getPatternWeights(); - - this.treeModel = treeModel; - addModel(treeModel); - - nodeCount = treeModel.getNodeCount(); - - updateNode = new boolean[nodeCount]; - for (int i = 0; i < nodeCount; i++) { - updateNode[i] = true; - } - - } - - /** - * Sets the partials from a sequence in an alignment. - */ - protected final void setStates(LikelihoodCore likelihoodCore, PatternList patternList, - int sequenceIndex, int nodeIndex) { - int i; - - int[] states = new int[patternCount]; - - for (i = 0; i < patternCount; i++) { - - states[i] = patternList.getPatternState(sequenceIndex, i); - //System.err.print(states[i]+" "); - } - - likelihoodCore.setNodeStates(nodeIndex, states); - } - - /** - * Sets the partials from a sequence in an alignment. - */ - protected final void setPartials(LikelihoodCore likelihoodCore, PatternList patternList, - int categoryCount, - int sequenceIndex, int nodeIndex) { - int i, j; - - double[] partials = new double[patternCount * stateCount]; - - boolean[] stateSet; - - int v = 0; - for (i = 0; i < patternCount; i++) { - - int state = patternList.getPatternState(sequenceIndex, i); - stateSet = dataType.getStateSet(state); - - for (j = 0; j < stateCount; j++) { - if (stateSet[j]) { - partials[v] = 1.0; - } else { - partials[v] = 0.0; - } - v++; - } - } - - likelihoodCore.setNodePartials(nodeIndex, partials); - } - - /** - * Set update flag for a node and its children - */ - protected void updateNode(NodeRef node) { - - updateNode[node.getNumber()] = true; - likelihoodKnown = false; - } - - /** - * Set update flag for a node and its children - */ - protected void updateNodeAndChildren(NodeRef node) { - updateNode[node.getNumber()] = true; - - for (int i = 0; i < treeModel.getChildCount(node); i++) { - NodeRef child = treeModel.getChild(node, i); - updateNode[child.getNumber()] = true; - } - likelihoodKnown = false; - } - - /** - * Set update flag for a node and its children - */ - protected void updateNodeAndDescendents(NodeRef node) { - updateNode[node.getNumber()] = true; - - for (int i = 0; i < treeModel.getChildCount(node); i++) { - NodeRef child = treeModel.getChild(node, i); - updateNodeAndDescendents(child); - } - - likelihoodKnown = false; - } - - /** - * Set update flag for all nodes - */ - protected void updateAllNodes() { - for (int i = 0; i < nodeCount; i++) { - updateNode[i] = true; - } - likelihoodKnown = false; - } - - /** - * Set update flag for a pattern - */ - protected void updatePattern(int i) { - if (updatePattern != null) { - updatePattern[i] = true; - } - likelihoodKnown = false; - } - - /** - * Set update flag for all patterns - */ - protected void updateAllPatterns() { - if (updatePattern != null) { - for (int i = 0; i < patternCount; i++) { - updatePattern[i] = true; - } - } - likelihoodKnown = false; - } - - public final double[] getPatternWeights() { - return patternWeights; - } - - // ************************************************************** - // VariableListener IMPLEMENTATION - // ************************************************************** - - protected void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) { - // do nothing - } - - // ************************************************************** - // Model IMPLEMENTATION - // ************************************************************** - - protected void handleModelChangedEvent(Model model, Object object, int index) { - likelihoodKnown = false; - } - - /** - * Stores the additional state other than model components - */ - protected void storeState() { - - storedLikelihoodKnown = likelihoodKnown; - storedLogLikelihood = logLikelihood; - } - - /** - * Restore the additional stored state - */ - protected void restoreState() { - - likelihoodKnown = storedLikelihoodKnown; - logLikelihood = storedLogLikelihood; - } - - protected void acceptState() { - } // nothing to do - - // ************************************************************** - // Likelihood IMPLEMENTATION - // ************************************************************** - - public final Model getModel() { - return this; - } - - public final double getLogLikelihood() { - if (!likelihoodKnown) { - logLikelihood = calculateLogLikelihood(); - likelihoodKnown = true; - } - return logLikelihood; - } - - /** - * Forces a complete recalculation of the likelihood next time getLikelihood is called - */ - public void makeDirty() { - likelihoodKnown = false; - updateAllNodes(); - updateAllPatterns(); - } - - public void setLikelihood(double likelihood) { - this.logLikelihood = likelihood; - likelihoodKnown = true; - } - - - public boolean getLikelihoodKnown() { - return likelihoodKnown; - } - - protected abstract double calculateLogLikelihood(); - - public String toString() { - - return Double.toString(getLogLikelihood()); - - } - - - // ************************************************************** - // INSTANCE VARIABLES - // ************************************************************** - - /** - * the tree - */ - protected ARGModel treeModel = null; - - /** - * the partition * - */ - protected int partition; - - /** - * the patternList - */ - protected PatternList patternList = null; - - protected DataType dataType = null; - - /** - * the pattern weights - */ - protected double[] patternWeights; - - /** - * the number of patterns - */ - protected int patternCount; - - /** - * the number of states in the data - */ - protected int stateCount; - - /** - * the number of nodes in the tree - */ - protected int nodeCount; - - /** - * Flags to specify which patterns are to be updated - */ - protected boolean[] updatePattern = null; - - /** - * Flags to specify which nodes are to be updated - */ - protected boolean[] updateNode; - - private double logLikelihood; - private double storedLogLikelihood; - private boolean likelihoodKnown = false; - private boolean storedLikelihoodKnown = false; - -} \ No newline at end of file diff --git a/src/dr/evomodel/arg/operators/ARGAddRemoveEventOperator.java b/src/dr/evomodel/arg/operators/ARGAddRemoveEventOperator.java deleted file mode 100644 index 969e6d9066..0000000000 --- a/src/dr/evomodel/arg/operators/ARGAddRemoveEventOperator.java +++ /dev/null @@ -1,1646 +0,0 @@ -/* - * ARGAddRemoveEventOperator.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -/* - * AddRemoveSubtreeOperator.java - * - * (c) 2002-2005 BEAST Development Core Team - * - * This package may be distributed under the - * Lesser Gnu Public Licence (LGPL) - */ - -package dr.evomodel.arg.operators; - -import dr.evolution.tree.MutableTree; -import dr.evolution.tree.NodeRef; -import dr.evolution.tree.TreeUtils; -import dr.evomodel.arg.ARGModel; -import dr.evomodel.arg.ARGModel.Node; -import dr.evomodel.arg.ARGPartitionLikelihood; -import dr.evomodel.arg.ARGRatePrior; -import dr.evomodelxml.tree.TreeModelParser; -import dr.inference.model.CompoundParameter; -import dr.inference.model.Parameter; -import dr.inference.operators.AbstractAdaptableOperator; -import dr.inference.operators.AdaptationMode; -import dr.inference.operators.MCMCOperator; -import dr.math.MathUtils; -import dr.xml.*; - -import java.util.ArrayList; -import java.util.logging.Logger; - - -/** - * Adds and removes re-assortment events. - * - * @author Erik Bloomquist - * @author Marc Suchard - */ - -public class ARGAddRemoveEventOperator extends AbstractAdaptableOperator { - - public static final String ADD_PROBABILITY = "addProbability"; - public static final String ARG_EVENT_OPERATOR = "ARGEventOperator"; - public static final String INTERNAL_NODES = "internalNodes"; - public static final String INTERNAL_AND_ROOT = "internalNodesPlusRoot"; - public static final String NODE_RATES = TreeModelParser.NODE_RATES; - public static final String BELOW_ROOT_PROBABILITY = "belowRootProbability"; - public static final String FLIP_MEAN = "flipMean"; - public static final String JOINT_PARTITIONING = "jointPartitioning"; - public static final String RELAXED = "relaxed"; - - public static final double LOG_TWO = Math.log(2.0); - - - private boolean relaxed = false; - - private ARGModel arg = null; - private double size = 0.0; //Translates into add probability of 50% - private double probBelowRoot = 0.9; //Transformed in constructor for computational efficiency - - private ARGPartitionLikelihood partLike; - private ARGRatePrior ratePrior; - - - // private int mode = AdaptableMCMCOperator.ADAPTATION_OFF; - private CompoundParameter internalNodeParameters; - private CompoundParameter internalAndRootNodeParameters; - private CompoundParameter nodeRates; - - private int tossSize = -1; - - - public ARGAddRemoveEventOperator(ARGModel arg, int weight, double size, AdaptationMode mode, - CompoundParameter param1, - CompoundParameter param2, - CompoundParameter param3, - double belowRootProbability, - ARGPartitionLikelihood partLike, - ARGRatePrior ratePrior, - int tossSize) { - super(mode, 0.5); - this.arg = arg; - this.size = size; - this.internalNodeParameters = param1; - this.internalAndRootNodeParameters = param2; - this.nodeRates = param3; - - this.partLike = partLike; - this.ratePrior = ratePrior; - - if (ratePrior != null) { - relaxed = true; - } - -// this.isRecombination = arg.isRecombinationPartitionType(); -//// this.mode = mode; -// this.flipMean = flipMean; -// -// if (flipMean > -1) { -// this.pd = new PoissonDistribution(flipMean); -// logPoissonNormalizingFactor = Math.log(pd.cdf(arg.getNumberOfPartitions() - 1) - pd.cdf(0)); -// } -// -// if (isRecombination) { -// logPartitionSize = Math.log(arg.getNumberOfPartitions() - 1); -// } else if (arg.getNumberOfPartitions() > 40) { -// //The -1 factor only matters for smaller problems, -// //so we ignore when partition size gets big. -// //Difference is very, very tiny. -// logPartitionSize = (arg.getNumberOfPartitions() - 1) * LOG_TWO; -// } else { -// logPartitionSize = Math.log(Math.pow(2, arg.getNumberOfPartitions() - 1) - 1); -// } - - setWeight(weight); - - this.probBelowRoot = belowRootProbability; - - //This is for computational efficiency - probBelowRoot = -Math.log(1 - Math.sqrt(probBelowRoot)); - - this.tossSize = tossSize; - } - - - /** - * Do a add/remove re-assortment node operation - * - * @return the log-transformed hastings ratio - */ - public double doOperation() { - double logq = 0; - - try { - if (MathUtils.nextDouble() < 1.0 / (1 + Math.exp(-size))) { - logq = AddOperation() - size; - } else { - logq = RemoveOperation() + size; - } - } catch (NoReassortmentEventException nree) { - throw new RuntimeException(""); - } - - assert !Double.isInfinite(logq) && !Double.isNaN(logq); - - - return logq; - } - - private double AddOperation() { - double logHastings = 0; - - - double treeHeight = arg.getNodeHeight(arg.getRoot()); - double newBifurcationHeight = Double.POSITIVE_INFINITY; - double newReassortmentHeight = Double.POSITIVE_INFINITY; - - double theta = probBelowRoot / treeHeight; - - while (newBifurcationHeight > treeHeight && newReassortmentHeight > treeHeight) { - newBifurcationHeight = MathUtils.nextExponential(theta); - newReassortmentHeight = MathUtils.nextExponential(theta); - } - - logHastings += theta * (newBifurcationHeight + newReassortmentHeight) - LOG_TWO - - 2.0 * Math.log(theta) + Math.log(1 - Math.exp(-2.0 * treeHeight * theta)); - -// This is the ugly mixture proposal -// double meanRoot = 4.0 / treeHeight; -// double case1 = 0.95; -// -// if(MathUtils.nextDouble() < case1){ -// newReassortmentHeight = MathUtils.nextDouble() * treeHeight; -// newBifurcationHeight = MathUtils.nextDouble() * treeHeight; -// -// logHastings += 2.0*Math.log(treeHeight) - Math.log(2.0*case1); -// }else{ -// newReassortmentHeight = MathUtils.nextDouble() * treeHeight; -// double additional = MathUtils.nextExponential(meanRoot); -// logHastings += Math.log(treeHeight) + additional*meanRoot - -// Math.log((1-case1)*meanRoot); -// -// newBifurcationHeight = additional + treeHeight; -// } - - if (newBifurcationHeight < newReassortmentHeight) { - double temp = newBifurcationHeight; - newBifurcationHeight = newReassortmentHeight; - newReassortmentHeight = temp; - } - - //2. Find the possible re-assortment and bifurcation points. - ArrayList potentialBifurcationChildren = new ArrayList(); - ArrayList potentialReassortmentChildren = new ArrayList(); - - int totalPotentialBifurcationChildren = findPotentialAttachmentPoints( - newBifurcationHeight, potentialBifurcationChildren); - int totalPotentialReassortmentChildren = findPotentialAttachmentPoints( - newReassortmentHeight, potentialReassortmentChildren); - - assert totalPotentialBifurcationChildren > 0; - assert totalPotentialReassortmentChildren > 0; - - logHastings += Math.log((double) potentialBifurcationChildren.size() * - potentialReassortmentChildren.size()); - - //3. Choose your re-assortment location. - Node reassortChild = (Node) potentialReassortmentChildren.get(MathUtils - .nextInt(totalPotentialReassortmentChildren)); - - Node reassortLeftParent = reassortChild.leftParent; - Node reassortRightParent = reassortChild.rightParent; - Node reassortSplitParent = reassortChild.leftParent; - - boolean splitReassortLeftParent = true; - - if (!reassortChild.bifurcation) { - boolean[] tester = {arg.getNodeHeight(reassortLeftParent) > newReassortmentHeight, - arg.getNodeHeight(reassortRightParent) > newReassortmentHeight}; - - if (tester[0] && tester[1]) { - if (MathUtils.nextBoolean()) { - splitReassortLeftParent = false; - reassortSplitParent = reassortRightParent; - } -// logHastings += LOG_TWO; - } else if (tester[0]) { - //nothing to do, setup above - } else if (tester[1]) { - splitReassortLeftParent = false; - reassortSplitParent = reassortRightParent; - } else { - assert false; - } - } - - -// if (recParentL != recParentR) { -// boolean[] tester = {arg.getNodeHeight(recParentL) > newReassortmentHeight, -// arg.getNodeHeight(recParentR) > newReassortmentHeight}; -// -// if (tester[0] && tester[1]) { -// if (MathUtils.nextBoolean()) { -// recParent = recParentR; -// } -// -// logHastings += LOG_TWO; -// } else if (tester[0]) { -// recParent = recParentL; -// } else { -// recParent = recParentR; -// } -// } - - //4. Choose your bifurcation location. - - Node bifurcationChild = (Node) potentialBifurcationChildren.get(MathUtils - .nextInt(potentialBifurcationChildren.size())); - - - Node bifurcationLeftParent = bifurcationChild.leftParent; - Node bifurcationRightParent = bifurcationChild.rightParent; - Node bifurcationSplitParent = bifurcationLeftParent; - - boolean splitBifurcationLeftParent = true; - - if (!bifurcationChild.bifurcation) { - boolean[] tester = {arg.getNodeHeight(bifurcationLeftParent) > newBifurcationHeight, - arg.getNodeHeight(bifurcationRightParent) > newBifurcationHeight}; - - if (tester[0] && tester[1]) { - if (MathUtils.nextBoolean()) { - splitBifurcationLeftParent = false; - bifurcationSplitParent = bifurcationRightParent; - } -// logHastings += LOG_TWO; - } else if (tester[0]) { - //nothing to do - } else if (tester[1]) { - splitBifurcationLeftParent = false; - bifurcationSplitParent = bifurcationRightParent; - } else { - assert false; - } - } - - boolean attachNewReassortNewBifurcationThroughLeft = MathUtils.nextBoolean(); - - //During the delete step, this guy gets cancelled out! - logHastings += LOG_TWO; - - -// if (sisParentL != sisParentR) { -// boolean[] tester = {arg.getNodeHeight(sisParentL) > newBifurcationHeight, -// arg.getNodeHeight(sisParentR) > newBifurcationHeight}; -// -// if (tester[0] && tester[1]) { -// if (MathUtils.nextBoolean()) { -// sisParent = sisParentR; -// } -// logHastings += LOG_TWO; -// } else if (tester[0]) { -// sisParent = sisParentL; -// } else { -// sisParent = sisParentR; -// } -// } - - //5. Make the new nodes. - //Note: The height stuff is taken care of below. - - Node newReassortment = arg.new Node(); - newReassortment.bifurcation = false; - - double[] reassortmentValues = {1.0}; - - if (relaxed) { - reassortmentValues = ratePrior.generateValues(); - } - -// logHastings += ratePrior.getAddHastingsRatio(reassortmentValues); - - newReassortment.rateParameter = new Parameter.Default(reassortmentValues); - - newReassortment.rateParameter.addBounds(new Parameter.DefaultBounds( - Double.POSITIVE_INFINITY, 0, reassortmentValues.length)); - - newReassortment.number = arg.getNodeCount() + 1; - - - Node newBifurcation = arg.new Node(); - - double[] bifurcationValues = {1.0}; - - if (relaxed) { - bifurcationValues = ratePrior.generateValues(); - logHastings += ratePrior.getAddHastingsRatio(bifurcationValues); - } - - newBifurcation.rateParameter = new Parameter.Default(bifurcationValues); - - newBifurcation.rateParameter.addBounds(new Parameter.DefaultBounds( - Double.POSITIVE_INFINITY, 0, bifurcationValues.length)); - - newBifurcation.number = arg.getNodeCount(); - - //6. Begin editing the tree. - arg.beginTreeEdit(); - - adjustRandomPartitioning(); - - if (newBifurcationHeight < treeHeight) { - - if (bifurcationChild == reassortChild) { - if (bifurcationChild.bifurcation) { - bifurcationChild.leftParent = bifurcationChild.rightParent = newReassortment; - newReassortment.leftChild = newReassortment.rightChild = bifurcationChild; - newReassortment.leftParent = newReassortment.rightParent = newBifurcation; - newBifurcation.leftChild = newBifurcation.rightChild = newReassortment; - newBifurcation.leftParent = newBifurcation.rightParent = bifurcationSplitParent; - - if (bifurcationSplitParent.bifurcation) { - if (bifurcationSplitParent.leftChild == bifurcationChild) { - bifurcationSplitParent.leftChild = newBifurcation; - } else { - bifurcationSplitParent.rightChild = newBifurcation; - } - } else { - bifurcationSplitParent.leftChild = bifurcationSplitParent.rightChild = newBifurcation; - } - - logHastings -= LOG_TWO; - } else { - if (splitBifurcationLeftParent && splitReassortLeftParent) { - bifurcationChild.leftParent = newReassortment; - newReassortment.leftChild = newReassortment.rightChild = bifurcationChild; - newReassortment.leftParent = newReassortment.rightParent = newBifurcation; - - newBifurcation.leftChild = newBifurcation.rightChild = newReassortment; - newBifurcation.leftParent = newBifurcation.rightParent = bifurcationSplitParent; - - if (bifurcationSplitParent.bifurcation) { - if (bifurcationSplitParent.leftChild == bifurcationChild) { - bifurcationSplitParent.leftChild = newBifurcation; - } else { - bifurcationSplitParent.rightChild = newBifurcation; - } - } else { - bifurcationSplitParent.leftChild = bifurcationSplitParent.rightChild = newBifurcation; - } - - - } else if (splitBifurcationLeftParent) { - //bifurcation on left, reassortment on right - - bifurcationChild.leftParent = newBifurcation; - bifurcationChild.rightParent = newReassortment; - - newBifurcation.leftChild = bifurcationChild; - newBifurcation.rightChild = newReassortment; - newBifurcation.leftParent = newBifurcation.rightParent = bifurcationSplitParent; - - if (bifurcationSplitParent.bifurcation) { - if (bifurcationSplitParent.leftChild == bifurcationChild) { - bifurcationSplitParent.leftChild = newBifurcation; - } else { - bifurcationSplitParent.rightChild = newBifurcation; - } - } else { - bifurcationSplitParent.leftChild = bifurcationSplitParent.rightChild = newBifurcation; - } - - newReassortment.leftChild = newReassortment.rightChild = bifurcationChild; - - if (attachNewReassortNewBifurcationThroughLeft) { - newReassortment.leftParent = newBifurcation; - newReassortment.rightParent = reassortSplitParent; - } else { - newReassortment.rightParent = newBifurcation; - newReassortment.leftParent = reassortSplitParent; - } - - if (reassortSplitParent.bifurcation) { - if (reassortSplitParent.leftChild == reassortChild) { - reassortSplitParent.leftChild = newReassortment; - } else { - reassortSplitParent.rightChild = newReassortment; - } - } else { - reassortSplitParent.leftChild = reassortSplitParent.rightChild = newReassortment; - } - - - } else if (splitReassortLeftParent) { - //bifurcation on right, reassortment on left - - bifurcationChild.rightParent = newBifurcation; - bifurcationChild.leftParent = newReassortment; - - newBifurcation.leftChild = bifurcationChild; - newBifurcation.rightChild = newReassortment; - newBifurcation.leftParent = newBifurcation.rightParent = bifurcationSplitParent; - - if (bifurcationSplitParent.bifurcation) { - if (bifurcationSplitParent.leftChild == bifurcationChild) { - bifurcationSplitParent.leftChild = newBifurcation; - } else { - bifurcationSplitParent.rightChild = newBifurcation; - } - } else { - bifurcationSplitParent.leftChild = bifurcationSplitParent.rightChild = newBifurcation; - } - - newReassortment.leftChild = newReassortment.rightChild = bifurcationChild; - - if (attachNewReassortNewBifurcationThroughLeft) { - newReassortment.leftParent = newBifurcation; - newReassortment.rightParent = reassortSplitParent; - } else { - newReassortment.rightParent = newBifurcation; - newReassortment.leftParent = reassortSplitParent; - } - - if (reassortSplitParent.bifurcation) { - if (reassortSplitParent.leftChild == reassortChild) { - reassortSplitParent.leftChild = newReassortment; - } else { - reassortSplitParent.rightChild = newReassortment; - } - } else { - reassortSplitParent.leftChild = reassortSplitParent.rightChild = newReassortment; - } - - - } else { - - bifurcationChild.rightParent = newReassortment; - newReassortment.leftChild = newReassortment.rightChild = bifurcationChild; - newReassortment.leftParent = newReassortment.rightParent = newBifurcation; - - newBifurcation.leftChild = newBifurcation.rightChild = newReassortment; - newBifurcation.leftParent = newBifurcation.rightParent = bifurcationSplitParent; - - if (bifurcationSplitParent.bifurcation) { - if (bifurcationSplitParent.leftChild == bifurcationChild) { - bifurcationSplitParent.leftChild = newBifurcation; - } else { - bifurcationSplitParent.rightChild = newBifurcation; - } - } else { - bifurcationSplitParent.leftChild = bifurcationSplitParent.rightChild = newBifurcation; - } - - logHastings -= LOG_TWO; - - } - } - - } else { - - - newReassortment.leftChild = newReassortment.rightChild = reassortChild; - newBifurcation.leftParent = newBifurcation.rightParent = bifurcationSplitParent; - newBifurcation.leftChild = newReassortment; - newBifurcation.rightChild = bifurcationChild; - - if (attachNewReassortNewBifurcationThroughLeft) { - newReassortment.leftParent = newBifurcation; - newReassortment.rightParent = reassortSplitParent; - } else { - newReassortment.rightParent = newBifurcation; - newReassortment.leftParent = reassortSplitParent; - } - - if (reassortChild.bifurcation) { - reassortChild.leftParent = reassortChild.rightParent = newReassortment; - } else if (splitReassortLeftParent) { - reassortChild.leftParent = newReassortment; - } else { - reassortChild.rightParent = newReassortment; - } - - if (reassortSplitParent.bifurcation) { - if (reassortSplitParent.leftChild == reassortChild) { - reassortSplitParent.leftChild = newReassortment; - } else { - reassortSplitParent.rightChild = newReassortment; - } - } else { - reassortSplitParent.leftChild = reassortSplitParent.rightChild = newReassortment; - } - - if (bifurcationChild.bifurcation) { - bifurcationChild.leftParent = bifurcationChild.rightParent = newBifurcation; - } else if (splitBifurcationLeftParent) { - bifurcationChild.leftParent = newBifurcation; - } else { - bifurcationChild.rightParent = newBifurcation; - } - - if (bifurcationSplitParent.bifurcation) { - if (bifurcationSplitParent.leftChild == bifurcationChild) { - bifurcationSplitParent.leftChild = newBifurcation; - } else { - bifurcationSplitParent.rightChild = newBifurcation; - } - } else { - bifurcationSplitParent.leftChild = bifurcationSplitParent.rightChild = newBifurcation; - } - - - } - - Parameter partition = new Parameter.Default(arg.getNumberOfPartitions()); - drawRandomPartitioning(partition); - - - newReassortment.partitioning = partition; - - newBifurcation.heightParameter = new Parameter.Default(newBifurcationHeight); - newReassortment.heightParameter = new Parameter.Default(newReassortmentHeight); - newBifurcation.setupHeightBounds(); - newReassortment.setupHeightBounds(); - - - arg.expandARG(newBifurcation, newReassortment, - internalNodeParameters, - internalAndRootNodeParameters, - nodeRates); - - -// arg.expandARGWithRecombinant(newBifurcation, newReassortment, -// internalNodeParameters, -// internalAndRootNodeParameters, -// nodeRates); - assert nodeCheck() : arg.toARGSummary(); - - } else { - - assert newReassortmentHeight < treeHeight; - - - //New bifurcation takes the place of the old root. - //Much easier to program. - - newReassortment.heightParameter = new Parameter.Default(newReassortmentHeight); - newReassortment.setupHeightBounds(); - - bifurcationChild = newBifurcation; - if (arg.isRoot(reassortSplitParent)) - reassortSplitParent = newBifurcation; - - - Node root = (Node) arg.getRoot(); - Node rootLeftChild = root.leftChild; - Node rootRightChild = root.rightChild; - - arg.singleRemoveChild(root, rootLeftChild); - arg.singleRemoveChild(root, rootRightChild); - arg.singleAddChild(newBifurcation, rootLeftChild); - arg.singleAddChild(newBifurcation, rootRightChild); - - if (reassortSplitParent.isBifurcation()) - arg.singleRemoveChild(reassortSplitParent, reassortChild); - else - arg.doubleRemoveChild(reassortSplitParent, reassortChild); - - arg.doubleAddChild(newReassortment, reassortChild); - arg.singleAddChild(root, newBifurcation); - - Parameter partitioning = new Parameter.Default(arg.getNumberOfPartitions()); - drawRandomPartitioning(partitioning); - - - arg.addChildAsRecombinant(root, reassortSplitParent, newReassortment, partitioning); - - if (attachNewReassortNewBifurcationThroughLeft) { - newReassortment.leftParent = root; - newReassortment.rightParent = reassortSplitParent; - } else { - newReassortment.leftParent = reassortSplitParent; - newReassortment.rightParent = root; - } - - newBifurcation.heightParameter = new Parameter.Default(root.getHeight()); - - newBifurcation.setupHeightBounds(); - root.heightParameter.setParameterValue(0, newBifurcationHeight); - - - arg.expandARG(newBifurcation, newReassortment, - internalNodeParameters, - internalAndRootNodeParameters, - nodeRates); - - -// arg.expandARGWithRecombinant(newBifurcation, newReassortment, -// internalNodeParameters, -// internalAndRootNodeParameters, -// nodeRates); - - assert nodeCheck(); - - - } - - - //6a. This is when we do not create a new root. -// if (newBifurcationHeight < treeHeight) { -// newBifurcation.heightParameter = new Parameter.Default(newBifurcationHeight); -// newReassortment.heightParameter = new Parameter.Default(newReassortmentHeight); -// newBifurcation.setupHeightBounds(); -// newReassortment.setupHeightBounds(); -// -// if (sisParent.bifurcation) -// arg.singleRemoveChild(sisParent, bifurcationChild); -// else -// arg.doubleRemoveChild(sisParent, bifurcationChild); -// if (bifurcationChild != reassortChild) { -// if (recParent.bifurcation) -// arg.singleRemoveChild(recParent, reassortChild); -// else -// arg.doubleRemoveChild(recParent, reassortChild); -// } -// if (sisParent.bifurcation) -// arg.singleAddChild(sisParent, newBifurcation); -// else -// arg.doubleAddChild(sisParent, newBifurcation); -// if (bifurcationChild != reassortChild) -// arg.singleAddChild(newBifurcation, bifurcationChild); -// arg.doubleAddChild(newReassortment, reassortChild); -// -// Parameter partitioning = new Parameter.Default(arg.getNumberOfPartitions()); -// drawRandomPartitioning(partitioning); -// -// if (bifurcationChild != reassortChild) { -// arg.addChildAsRecombinant(newBifurcation, recParent, -// newReassortment, partitioning); -// } else { -// arg.addChildAsRecombinant(newBifurcation, newBifurcation, -// newReassortment, partitioning); -// } -// arg.expandARGWithRecombinant(newBifurcation, newReassortment, -// internalNodeParameters, -// internalAndRootNodeParameters, -// nodeRates); -// assert nodeCheck(); -// -// //6b. But here we do. -// } else if (newReassortmentHeight < treeHeight) { -// -// newReassortment.heightParameter = new Parameter.Default(newReassortmentHeight); -// newReassortment.setupHeightBounds(); -// -// bifurcationChild = newBifurcation; -// if (arg.isRoot(recParent)) -// recParent = newBifurcation; -// -// -// Node root = (Node) arg.getRoot(); -// Node rootLeftChild = root.leftChild; -// Node rootRightChild = root.rightChild; -// -// arg.singleRemoveChild(root, rootLeftChild); -// arg.singleRemoveChild(root, rootRightChild); -// arg.singleAddChild(newBifurcation, rootLeftChild); -// arg.singleAddChild(newBifurcation, rootRightChild); -// -// if (recParent.isBifurcation()) -// arg.singleRemoveChild(recParent, reassortChild); -// else -// arg.doubleRemoveChild(recParent, reassortChild); -// -// arg.doubleAddChild(newReassortment, reassortChild); -// arg.singleAddChild(root, newBifurcation); -// -// Parameter partitioning = new Parameter.Default(arg.getNumberOfPartitions()); -// drawRandomPartitioning(partitioning); -// -// -// arg.addChildAsRecombinant(root, recParent, newReassortment, partitioning); -// -// newBifurcation.heightParameter = new Parameter.Default(root.getHeight()); -// -// newBifurcation.setupHeightBounds(); -// root.heightParameter.setParameterValue(0, newBifurcationHeight); -// -// -// arg.expandARGWithRecombinant(newBifurcation, newReassortment, -// internalNodeParameters, internalAndRootNodeParameters, -// nodeRates); -// -// assert nodeCheck(); -// -// } else { -// -// Node root = (Node) arg.getRoot(); -// Node rootLeftChild = root.leftChild; -// Node rootRightChild = root.rightChild; -// -// arg.singleRemoveChild(root, rootLeftChild); -// arg.singleRemoveChild(root, rootRightChild); -// arg.singleAddChild(newBifurcation, rootLeftChild); -// arg.singleAddChild(newBifurcation, rootRightChild); -// -// arg.doubleAddChild(newReassortment, newBifurcation); -// arg.doubleAddChild(root, newReassortment); -// -// Parameter partitioning = new Parameter.Default(arg.getNumberOfPartitions()); -// drawRandomPartitioning(partitioning); -// -// newReassortment.partitioning = partitioning; -// -// newBifurcation.heightParameter = new Parameter.Default(arg.getNodeHeight(root)); -// newReassortment.heightParameter = new Parameter.Default(newReassortmentHeight); -// root.heightParameter.setParameterValueQuietly(0, newBifurcationHeight); -// -// newBifurcation.setupHeightBounds(); -// newReassortment.setupHeightBounds(); -// -// arg.expandARGWithRecombinant(newBifurcation, newReassortment, -// internalNodeParameters, internalAndRootNodeParameters, -// nodeRates); -// -// assert nodeCheck(); -// -// } - - arg.pushTreeSizeIncreasedEvent(); - - arg.endTreeEdit(); - try { - arg.checkTreeIsValid(); - } catch (MutableTree.InvalidTreeException ite) { - throw new RuntimeException(ite.toString() + "\n" + arg.toString() - + "\n" + TreeUtils.uniqueNewick(arg, arg.getRoot())); - } - - //Do all the backwards stuff now. :( - - assert nodeCheck(); - - logHastings -= Math.log((double) findPotentialNodesToRemove(null)); -// logHastings -= Math.log((double)arg.getReassortmentNodeCount()); - -// if (newReassortment.leftParent != newReassortment.rightParent){ -// if(newReassortment.leftParent.bifurcation -// && newReassortment.rightParent.bifurcation) -// logHastings -= LOG_TWO; -// } - - assert nodeCheck(); - - assert !Double.isNaN(logHastings) && !Double.isInfinite(logHastings); - - if (newReassortment.leftParent.bifurcation && newReassortment.rightParent.bifurcation - && newReassortment.leftParent != newReassortment.rightParent) { - logHastings -= LOG_TWO; - } - - //You're done, return the hastings ratio! - -// System.out.println(logHastings); - - logHastings += getPartitionAddHastingsRatio(newReassortment.partitioning.getParameterValues()); - - return logHastings; - } - - private int findPotentialAttachmentPoints(double time, ArrayList list) { - int count = 0; - - for (int i = 0, n = arg.getNodeCount(); i < n; i++) { - NodeRef nr = arg.getNode(i); - if (!arg.isRoot(nr)) { - if (arg.getNodeHeight(nr) < time) { - Node left = (Node) arg.getParent(nr, 0); - Node right = (Node) arg.getParent(nr, 1); - if (arg.isBifurcation(nr)) { - assert left == right; - if (arg.getNodeHeight(left) > time) { - if (list != null) - list.add(nr); - count++; - } - } else { - if (arg.getNodeHeight(left) > time) { - if (list != null) - list.add(nr); - count++; - } - if (arg.getNodeHeight(right) > time) { - if (list != null) - list.add(nr); - count++; - } - } - } - } else { - if (arg.getNodeHeight(nr) < time) { - if (list != null) - list.add(nr); - count++; - } - } - } - - return count; - } - - - private int findPotentialNodesToRemove(ArrayList list) { - int count = 0; - int n = arg.getNodeCount(); - - - for (int i = 0; i < n; i++) { - Node node = (Node) arg.getNode(i); - Node lp = node.leftParent; - Node rp = node.rightParent; - - if (node.isReassortment() && (lp.bifurcation || rp.bifurcation)) { - if (list != null) - list.add(node); - count++; - } - } - - return count; - } - - - private double RemoveOperation() throws NoReassortmentEventException { - - double logHastings = 0; - - // 1. Draw reassortment node uniform randomly - - ArrayList potentialNodes = new ArrayList(); - int totalPotentials = findPotentialNodesToRemove(potentialNodes); - - if (totalPotentials == 0) - throw new NoReassortmentEventException(); - -// logHastings += Math.log((double)arg.getReassortmentNodeCount()); - logHastings += Math.log((double) totalPotentials); - -// double diff =(double)arg.getReassortmentNodeCount() - totalPotentials; -// -// if(MathUtils.nextDouble() < diff/totalPotentials) -// throw new NoReassortmentEventException(); - - - Node recNode = (Node) potentialNodes.get(MathUtils.nextInt(totalPotentials)); - - double[] removePartitioningValues = recNode.partitioning.getParameterValues(); - - double beforeReassortmentHeight = recNode.getHeight(); - double beforeBifurcationHeight = 0; - double beforeTreeHeight = arg.getNodeHeight(arg.getRoot()); - - arg.beginTreeEdit(); - - boolean doneSomething = false; - Node recParent = recNode.leftParent; - Node recChild = recNode.leftChild; - - Node beforeReassortChild = recNode.leftChild; - Node beforeBifurcationChild = recNode.leftParent; - - - if (recNode.leftParent == recNode.rightParent) { - if (!arg.isRoot(recNode.leftParent)) { - beforeBifurcationHeight = recParent.getHeight(); - - Node recGrandParent = recParent.leftParent; - - arg.doubleRemoveChild(recGrandParent, recParent); - arg.doubleRemoveChild(recNode, recChild); - if (recGrandParent.bifurcation) - arg.singleAddChild(recGrandParent, recChild); - else - arg.doubleAddChild(recGrandParent, recChild); - doneSomething = true; - - beforeBifurcationChild = beforeReassortChild; - } else { - //You should never go here. - - assert recChild.bifurcation; - assert false; - } - logHastings += LOG_TWO; - - } else { - - Node recDeleteParent = null; - Node recKeepParent = null; - - - if (recNode.leftParent.bifurcation && recNode.rightParent.bifurcation) { - if (MathUtils.nextBoolean()) { - recDeleteParent = recNode.rightParent; - recKeepParent = recNode.leftParent; - } else { - recDeleteParent = recNode.leftParent; - recKeepParent = recNode.rightParent; - } - logHastings += LOG_TWO; - } else if (recNode.rightParent.bifurcation) { - recDeleteParent = recNode.rightParent; - recKeepParent = recNode.leftParent; - } else { - recDeleteParent = recNode.leftParent; - recKeepParent = recNode.rightParent; - } - - beforeBifurcationChild = recDeleteParent.leftChild; - if (beforeBifurcationChild == recNode) { - beforeBifurcationChild = recDeleteParent.rightChild; - } - - beforeBifurcationHeight = recDeleteParent.getHeight(); - - - if (arg.isRoot(recDeleteParent)) { - - Node oldRoot = (Node) arg.getOtherChild(recDeleteParent, recNode); - Node oldRootLeft = oldRoot.leftChild; - Node oldRootRight = oldRoot.rightChild; - - if (oldRoot == recKeepParent) { - - arg.singleRemoveChild(recDeleteParent, recNode); - arg.singleRemoveChild(recDeleteParent, oldRoot); - arg.singleRemoveChild(oldRoot, oldRootLeft); - arg.singleRemoveChild(oldRoot, oldRootRight); - - arg.singleAddChild(recDeleteParent, oldRootLeft); - arg.singleAddChild(recDeleteParent, oldRootRight); - - arg.singleRemoveChild(recDeleteParent, recNode); - arg.doubleRemoveChild(recNode, recChild); - - arg.singleAddChild(recDeleteParent, recChild); - - recDeleteParent.setHeight(oldRoot.getHeight()); - - recDeleteParent = oldRoot; - - } else { - arg.singleRemoveChild(recDeleteParent, recNode); - arg.singleRemoveChild(recDeleteParent, oldRoot); - arg.singleRemoveChild(oldRoot, oldRootLeft); - arg.singleRemoveChild(oldRoot, oldRootRight); - - arg.singleAddChild(recDeleteParent, oldRootLeft); - arg.singleAddChild(recDeleteParent, oldRootRight); - - if (recKeepParent.bifurcation) - arg.singleRemoveChild(recKeepParent, recNode); - else - arg.doubleRemoveChild(recKeepParent, recNode); - - arg.doubleRemoveChild(recNode, recChild); - - if (recKeepParent.bifurcation) - arg.singleAddChild(recKeepParent, recChild); - else - arg.doubleAddChild(recKeepParent, recChild); - - recDeleteParent.setHeight(oldRoot.getHeight()); - recDeleteParent = oldRoot; - - } - - - } else { - Node recGrandParent = recDeleteParent.leftParent; - - Node otherChild = recDeleteParent.leftChild; - if (otherChild == recNode) - otherChild = recDeleteParent.rightChild; - - if (recGrandParent.bifurcation) - arg.singleRemoveChild(recGrandParent, recDeleteParent); - else - arg.doubleRemoveChild(recGrandParent, recDeleteParent); - - arg.singleRemoveChild(recDeleteParent, otherChild); - if (recKeepParent.bifurcation) - arg.singleRemoveChild(recKeepParent, recNode); - else - arg.doubleRemoveChild(recKeepParent, recNode); - arg.doubleRemoveChild(recNode, recChild); - if (otherChild != recChild) { - if (recGrandParent.bifurcation) - arg.singleAddChild(recGrandParent, otherChild); - else - arg.doubleAddChild(recGrandParent, otherChild); - if (recKeepParent.bifurcation) - arg.singleAddChild(recKeepParent, recChild); - else - arg.doubleAddChild(recKeepParent, recChild); - } else { - if (recGrandParent.bifurcation) - arg.singleAddChildWithOneParent(recGrandParent, otherChild); - else - arg.doubleAddChildWithOneParent(recGrandParent, otherChild); - if (recKeepParent.bifurcation) - arg.singleAddChildWithOneParent(recKeepParent, recChild); - else - arg.doubleAddChildWithOneParent(recKeepParent, recChild); - } - } - - doneSomething = true; - recParent = recDeleteParent; - } - - if (relaxed) { - - double[] rateValues = recParent.rateParameter.getParameterValues(); - logHastings -= ratePrior.getAddHastingsRatio(rateValues); - } - - - if (doneSomething) { - try { - arg.contractARG(recParent, recNode, - internalNodeParameters, internalAndRootNodeParameters, nodeRates); - -// arg.contractARGWithRecombinant(recParent, recNode, -// internalNodeParameters, internalAndRootNodeParameters, nodeRates); - } catch (Exception e) { - System.err.println(e.getMessage()); - System.err.println(e); - System.exit(-1); - } - } - - - int max = Math.max(recParent.getNumber(), recNode.getNumber()); - int min = Math.min(recParent.getNumber(), recNode.getNumber()); - - for (int i = 0, n = arg.getNodeCount(); i < n; i++) { - Node x = (Node) arg.getNode(i); - if (x.getNumber() > max) { - x.number--; - } - if (x.getNumber() > min) { - x.number--; - } - } - - - adjustRandomPartitioning(); - - - arg.pushTreeSizeDecreasedEvent(); - - arg.endTreeEdit(); - try { - arg.checkTreeIsValid(); - } catch (MutableTree.InvalidTreeException ite) { - throw new RuntimeException(ite.toString() + "\n" + arg.toString() - + "\n" + TreeUtils.uniqueNewick(arg, arg.getRoot())); - } - - assert nodeCheck() : arg.toARGSummary(); - - //Do the backwards stuff now :( - - double afterTreeHeight = arg.getNodeHeight(arg.getRoot()); - -// This is the ugly mixture proposal -// double meanRoot = 4.0 / afterTreeHeight; -// double case1 = 0.95; -// -// if(beforeBifurcationHeight < afterTreeHeight){ -// logHastings -= 2.0*Math.log(afterTreeHeight) - Math.log(2.0*case1); -// }else{ -// double additional = beforeBifurcationHeight - afterTreeHeight; -// logHastings -= Math.log(afterTreeHeight) + additional*meanRoot - -// Math.log((1-case1)*meanRoot); -// } - - double theta = probBelowRoot / afterTreeHeight; - - logHastings -= theta * (beforeBifurcationHeight + beforeReassortmentHeight) - LOG_TWO - - 2.0 * Math.log(theta) + Math.log(1 - Math.exp(-2.0 * afterTreeHeight * theta)); - - - logHastings -= Math.log((double) findPotentialAttachmentPoints(beforeBifurcationHeight, null) - * findPotentialAttachmentPoints(beforeReassortmentHeight, null)); - - - logHastings -= getPartitionAddHastingsRatio(removePartitioningValues); - - logHastings -= LOG_TWO; - -// if (!beforeBifurcationChild.bifurcation && -// arg.getNodeHeight(beforeBifurcationChild.leftParent) > beforeBifurcationHeight && -// arg.getNodeHeight(beforeBifurcationChild.rightParent) > beforeBifurcationHeight) { -// logHastings -= LOG_TWO; -// -// } - -// if (!beforeReassortChild.bifurcation && -// arg.getNodeHeight(beforeReassortChild.leftParent) > beforeReassortmentHeight && -// arg.getNodeHeight(beforeReassortChild.rightParent) > beforeReassortmentHeight) { -// logHastings -= LOG_TWO; -// } - assert nodeCheck(); - assert !Double.isNaN(logHastings) && !Double.isInfinite(logHastings); - - return logHastings; - } - - private double getPartitionAddHastingsRatio(double[] values) { - return -partLike.getLogLikelihood(values); - } - - private void adjustRandomPartitioning() { - if (tossSize < 1) { - return; - } - - if (arg.getReassortmentNodeCount() > 0) { - int total = arg.getReassortmentNodeCount(); - Parameter xyz = arg.getPartitioningParameters().getParameter(MathUtils.nextInt(total)); - - - if (arg.isRecombinationPartitionType()) { - adjustRecombinationPartition(xyz); - } else { - adjustReassortmentPartition(xyz); - } - } - - } - - private void adjustRecombinationPartition(Parameter part) { - double[] values = part.getParameterValues(); - - Logger.getLogger("dr.evomodel").severe("NOT IMPLENTED"); - } - - public static double arraySum(double[] n) { - double b = 0; - for (double a : n) - b += a; - return b; - } - - private void adjustReassortmentPartition(Parameter part) { - double[] values = part.getParameterValues(); - - boolean stop = false; - - if (values.length == 2) { - // Only option is to swap partitions - double tmp = values[0]; - values[0] = values[1]; - values[1] = tmp; - } else { - - while (!stop) { - values = part.getParameterValues(); - - ArrayList list = new ArrayList(); - - while (list.size() < tossSize) { - int z = MathUtils.nextInt(values.length - 1) + 1; - if (!list.contains(z)) { - list.add(z); - } - } - - - for (int z : list) { - if (values[z] == 0) { - values[z] = 1; - } else { - values[z] = 0; - } - } - - - if (arraySum(values) > 0) { - stop = true; - } - } - } - - for (int i = 0; i < values.length; i++) { - - - part.setParameterValueQuietly(i, values[i]); - } - - ARGPartitioningOperator.checkValidReassortmentPartition(part); - - - } - - private void drawRandomPartitioning(Parameter partitioning) { - double[] values = partLike.generatePartition(); - - for (int i = 0; i < values.length; i++) - partitioning.setParameterValueQuietly(i, values[i]); - - } - -// private int arraySum(int[] n) { -// int b = 0; -// for (int a : n) -// b += a; -// return b; -// } -// -// -// -// private void drawReassortmentPartitionAllFlip(Parameter partition) { -// int numberOfPartitionsMinusOne = arg.getNumberOfPartitions() - 1; -// -// int[] n = new int[numberOfPartitionsMinusOne]; -// -// while (arraySum(n) == 0) { -// for (int i = 0; i < n.length; i++) { -// if (MathUtils.nextBoolean()) { -// n[i] = 1; -// } else { -// n[i] = 0; -// } -// } -// } -// -// partition.setParameterValueQuietly(0, 0); -// -// for (int i = 0; i < numberOfPartitionsMinusOne; i++) { -// partition.setParameterValueQuietly(i + 1, n[i]); -// } -// -// -// -// assert ARGPartitioningOperator.checkValidReassortmentPartition(partition); -// -// } -// -// private int nextFlipSize() { -// int x = Poisson.nextPoisson(flipMean); -// while (x > arg.getNumberOfPartitions() - 1 || x == 0) { -// x = Poisson.nextPoisson(flipMean); -// } -// -// assert x != arg.getNumberOfPartitions(); -// assert x != 0; -// -// -// return x; -// } -// -// private void drawReassortmentPartitionFixedFlip(Parameter partition) { -// int numberOfPartitionsMinusOne = arg.getNumberOfPartitions() - 1; -// int flipSize = nextFlipSize(); -// -// if (flipSize == numberOfPartitionsMinusOne) { -// for (int i = 1; i <= flipSize; i++) -// partition.setParameterValueQuietly(i, 1.0); -// return; -// } -// -// double replaceValue = 1.0; -// if (MathUtils.nextBoolean()) { -// replaceValue = 0.0; -// -// for (int i = 1; i <= numberOfPartitionsMinusOne; i++) { -// partition.setParameterValueQuietly(i, 1.0); -// } -// } -// -// -// ArrayList a = new ArrayList(flipSize); -// while (a.size() < flipSize) { -// int b = MathUtils.nextInt(numberOfPartitionsMinusOne) + 1; -// if (!a.contains(b)) { -// a.add(b); -// } -// } -// -// -// for (int b : a) { -// partition.setParameterValueQuietly(b, replaceValue); -// } -// -// } -// -// private void drawRecombinationPartition(Parameter partition) { -// int lengthMinusOne = arg.getNumberOfPartitions() - 1; -// -// int cut = MathUtils.nextInt(lengthMinusOne); -// -// int leftValue = 0; //At one time, these values could switch. -// int rightValue = 1; -// -// for (int i = 0; i < cut + 1; i++) -// partition.setParameterValueQuietly(i, leftValue); -// for (int i = cut + 1; i < partition.getDimension(); i++) -// partition.setParameterValueQuietly(i, rightValue); -// } - - /* Draws a new partitioning. - * With probability singlePartitionProbability, one bit is set; - * otherwise, all bits are selected via a random permutation - * - */ - /* private double drawRandomReassortment(Parameter partitioning) { - int len = arg.getNumberOfPartitions(); - double logq = 0; - if (MathUtils.nextDouble() < singlePartitionProbability) { - if (partitioning != null) - partitioning.setParameterValueQuietly(MathUtils.nextInt(len), 1.0); - return Math.log(len); - } - int[] permutation = MathUtils.permuted(len); - int cut = MathUtils.nextInt(len - 1); - for (int i = 0; i < len; i++) { - logq += Math.log(i + 1); - if (i > cut && partitioning != null) - partitioning.setParameterValueQuietly(permutation[i], 1.0); - } - logq += Math.log(len - 1); - return logq; - } */ - - /* Draws a new partitioning. - * A break-pt is drawn uniformly - * - */ - /* private double drawRandomRecombination(Parameter partitioning) { - int len = arg.getNumberOfPartitions(); - double logq = 0; - double leftValue = MathUtils.nextInt(2); - double rightValue = 1.0 - leftValue; - logq += Math.log(2); - if (partitioning != null) { - int cut = MathUtils.nextInt(len - 1); - for (int i = 0; i <= cut; i++) - partitioning.setParameterValueQuietly(i, leftValue); - for (int i = cut + 1; i < len; i++) - partitioning.setParameterValueQuietly(i, rightValue); - } - logq += Math.log(len - 1); - return logq; - } */ - - - public boolean nodeCheck() { - for (int i = 0, n = arg.getNodeCount(); i < n; i++) { - Node x = (Node) arg.getNode(i); - - if (x.leftParent != x.rightParent && - x.leftChild != x.rightChild) { - return false; - } - if (x.leftParent != null) { - if (x.leftParent.leftChild.getNumber() != i && - x.leftParent.rightChild.getNumber() != i) - return false; - } - if (x.rightParent != null) { - if (x.rightParent.leftChild.getNumber() != i && - x.rightParent.rightChild.getNumber() != i) - return false; - } - if (x.leftChild != null) { - if (x.leftChild.leftParent.getNumber() != i && - x.leftChild.rightParent.getNumber() != i) - return false; - } - if (x.rightChild != null) { - if (x.rightChild.leftParent.getNumber() != i && - x.rightChild.rightParent.getNumber() != i) - return false; - } - } - - return true; - } - - - public void sanityCheck() { - int len = arg.getNodeCount(); - for (int i = 0; i < len; i++) { - Node node = (Node) arg.getNode(i); - if (node.bifurcation) { - boolean equalChild = (node.leftChild == node.rightChild); - if ((equalChild && node.leftChild != null)) { - if (!node.leftChild.bifurcation && ((node.leftChild).leftParent == node)) - ; - else { - System.err.println("Node " + (i + 1) + " is insane."); - System.err.println(arg.toGraphString()); - System.exit(-1); - } - } - } else { - if ((node.leftChild != node.rightChild)) { - System.err.println("Node " + (i + 1) + " is insane."); - System.err.println(arg.toGraphString()); - System.exit(-1); - } - } - if (!node.isRoot()) { - double d; - d = node.getHeight(); - } - } - } - - - //// - ////Coercible MCMC Operator stuff - //// - - - public double getSize() { - return size; - } - - public void setSize(double size) { - this.size = size; - } - - @Override - protected double getAdaptableParameterValue() { - return size; - } - - public void setAdaptableParameterValue(double value) { - setSize(value); - } - - public double getRawParameter() { - return size; - } - - @Override - public String getAdaptableParameterName() { - return null; - } - -// public int getMode() { -// return mode; -// } - - public String getOperatorName() { - return ARG_EVENT_OPERATOR; - } - - public static dr.xml.XMLObjectParser PARSER = new dr.xml.AbstractXMLObjectParser() { - - public String getParserName() { - return ARG_EVENT_OPERATOR; - } - - //public String[] getParserNames(){ - // return new String[]{getParserName(),"argEventOperator",}; - //} - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - -// int mode = AdaptableMCMCOperator.DEFAULT; -// if (xo.hasAttribute(AUTO_OPTIMIZE)) { -// if (xo.getBooleanAttribute(AUTO_OPTIMIZE)) { -// mode = AdaptableMCMCOperator.ADAPTATION_ON; -// } else { -// mode = AdaptableMCMCOperator.ADAPTATION_OFF; -// } -// } - - AdaptationMode mode = AdaptationMode.parseMode(xo); - - ARGModel treeModel = (ARGModel) xo.getChild(ARGModel.class); - - CompoundParameter parameter1 = (CompoundParameter) xo.getChild(INTERNAL_NODES).getChild(0); - CompoundParameter parameter2 = (CompoundParameter) xo.getChild(INTERNAL_AND_ROOT).getChild(0); - CompoundParameter parameter3 = (CompoundParameter) xo.getChild(NODE_RATES).getChild(0); - - int weight = xo.getIntegerAttribute("weight"); - double size = xo.getDoubleAttribute(ADD_PROBABILITY); - if (size > 0 && size < 1) - size = Math.log(size / (1.0 - size)); - else - throw new XMLParseException(ADD_PROBABILITY + " must be between 0 and 1"); - - double belowRootProb = 0.9; - if (xo.hasAttribute(BELOW_ROOT_PROBABILITY)) { - belowRootProb = xo.getDoubleAttribute(BELOW_ROOT_PROBABILITY); - if (belowRootProb >= 1 || belowRootProb <= 0) { - throw new XMLParseException(BELOW_ROOT_PROBABILITY + " must fall in (0,1)"); - } - } - - ARGPartitionLikelihood partitionLike = (ARGPartitionLikelihood) xo.getChild(ARGPartitionLikelihood.class); - - int tossSize = 0; - if (xo.hasAttribute(ARGPartitioningOperator.TOSS_SIZE)) { - tossSize = xo.getIntegerAttribute(ARGPartitioningOperator.TOSS_SIZE); - Logger.getLogger("dr.evomodel").info(ARG_EVENT_OPERATOR + " is joint with " + ARGPartitioningOperator.OPERATOR_NAME); - if (tossSize <= 0 || tossSize >= treeModel.getNumberOfPartitions()) { - throw new XMLParseException("Toss size is incorrect"); - } - } - - ARGRatePrior ratePrior = null; - - if (xo.hasAttribute(RELAXED)) { - ratePrior = (ARGRatePrior) xo.getChild(ARGRatePrior.class); - } - - return new ARGAddRemoveEventOperator(treeModel, weight, size, - mode, parameter1, parameter2, parameter3, - belowRootProb, partitionLike, ratePrior, tossSize); - } - - public String getParserDescription() { - return "An operator that slides a subarg."; - } - - public Class getReturnType() { - return ObsoleteARGAddRemoveEventOperator.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private final XMLSyntaxRule[] rules;{ - rules = new XMLSyntaxRule[]{ - AttributeRule.newDoubleRule(ADD_PROBABILITY, false, - "The probability that the operator adds a new" - + " reassortment event"), - AttributeRule.newBooleanRule(JOINT_PARTITIONING, true), - AttributeRule.newIntegerRule(ARGPartitioningOperator.TOSS_SIZE, true), - AttributeRule.newDoubleRule(ADD_PROBABILITY, true), - AttributeRule.newBooleanRule(AUTO_OPTIMIZE, true), - AttributeRule.newIntegerRule(WEIGHT, false), - new ElementRule(ARGModel.class, false), - new ElementRule(ARGPartitionLikelihood.class, false), - new ElementRule(ARGRatePrior.class, true), - new ElementRule(INTERNAL_NODES, - new XMLSyntaxRule[]{ - new ElementRule(CompoundParameter.class)}), - new ElementRule(INTERNAL_AND_ROOT, - new XMLSyntaxRule[]{ - new ElementRule(CompoundParameter.class)}), - new ElementRule(NODE_RATES, - new XMLSyntaxRule[]{ - new ElementRule(CompoundParameter.class)}), - }; - } - }; - - private class NoReassortmentEventException extends Exception { - public NoReassortmentEventException(String message) { - super(message); - } - - public NoReassortmentEventException() { - super(""); - } - - private static final long serialVersionUID = 1L; - - } - -} - diff --git a/src/dr/evomodel/arg/operators/ARGExchangeOperator.java b/src/dr/evomodel/arg/operators/ARGExchangeOperator.java deleted file mode 100644 index d2f046a43d..0000000000 --- a/src/dr/evomodel/arg/operators/ARGExchangeOperator.java +++ /dev/null @@ -1,418 +0,0 @@ -/* - * ARGExchangeOperator.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.arg.operators; - -import dr.evolution.tree.MutableTree; -import dr.evolution.tree.NodeRef; -import dr.evomodel.arg.ARGModel; -import dr.evomodel.operators.ExchangeOperator; -import dr.inference.operators.MCMCOperator; -import dr.inference.operators.SimpleMCMCOperator; -import dr.math.MathUtils; -import dr.xml.*; - -import java.util.ArrayList; - -/** - * Implements branch exchange operations. - * There is a NARROW and WIDE variety. - * The narrow exchange is very similar to a rooted-tree - * nearest-neighbour interchange but with the restriction - * that node height must remain consistent. - *

- * KNOWN BUGS: WIDE operator cannot be used on trees with 4 or less tips! - */ -public class ARGExchangeOperator extends SimpleMCMCOperator { - - public static final String NARROW_EXCHANGE = "argNarrowExchange"; - public static final String WIDE_EXCHANGE = "argWideExchange"; - - public static final int NARROW = 0; - public static final int WIDE = 1; - - private static final int MAX_TRIES = 10000; - - private int mode = NARROW; - private ARGModel tree; - - public ARGExchangeOperator(int mode, ARGModel tree, int weight) { - this.mode = mode; - this.tree = tree; - setWeight(weight); - } - - public double doOperation() { - - double logHastings = 0.0; - int tipCount = tree.getExternalNodeCount(); - - if (mode == NARROW) { - if (tree.getReassortmentNodeCount() < 2) - logHastings = narrow(); - else - return 0.0; - } else { - logHastings = wide(); - } - - - if (tree.getExternalNodeCount() != tipCount) { - throw new RuntimeException("Lost some tips in " + ((mode == NARROW) ? "NARROW mode." : "WIDE mode.")); - } - - assert !Double.isInfinite(logHastings) && !Double.isNaN(logHastings); - - return logHastings; - } - - public int getAllValidNarrowMoves() { - NodeRef iP = null, j = null, jP = null; - ArrayList nodes = new ArrayList(tree.getNodeCount()); - ArrayList moves = new ArrayList(tree.getNodeCount()); - - for (int k = 0, n = tree.getNodeCount(); k < n; k++) { - NodeRef x = tree.getNode(k); - if (!tree.isRoot(x) && !tree.isRoot(tree.getParent(x, 0)) - && !tree.isRoot(tree.getParent(x, 1))) { - nodes.add(x); - } - } - NarrowMove a; - for (NodeRef i : nodes) { - for (int k = 0; k < 2; k++) { - iP = tree.getParent(i, k); - for (int m = 0; m < 2; m++) { - jP = tree.getParent(iP, m); - j = tree.getOtherChild(jP, iP); - a = new NarrowMove(i, iP, j, jP); - if (validMove(a) && !moves.contains(a)) - moves.add(a); - } - } - } - assert moves.size() > 0; - return moves.size(); - } - - private boolean validMove(NarrowMove move) { - if (move.j != move.iP && move.i != move.j && - (tree.getNodeHeight(move.j) < tree.getNodeHeight(move.iP)) && - (tree.getNodeHeight(move.i) < tree.getNodeHeight(move.jP))) { - return true; - - } - return false; - } - - private class NarrowMove { - public NodeRef i; - public NodeRef j; - public NodeRef iP; - public NodeRef jP; - - public NarrowMove(NodeRef i, NodeRef iP, NodeRef j, NodeRef jP) { - this.i = i; - this.j = j; - this.iP = iP; - this.jP = jP; - - } - - public boolean equals(Object o) { - if (!(o instanceof NarrowMove)) { - return false; - } - - NarrowMove move = (NarrowMove) o; - - if (this.i == move.i && this.j == move.j && - this.iP == move.iP && this.jP == move.jP) { - return true; - } - if (this.i == move.j && this.j == move.i && - this.iP == move.jP && this.jP == move.iP) { - return true; - } - - return false; - } - - public String toString() { - return "(" + i.toString() + ", " + iP.toString() + - ", " + jP.toString() + ", " + j.toString() + ")"; - } - - } - - /** - * WARNING: Assumes strictly bifurcating tree. - */ - public double narrow() { - - NodeRef i = null, iP = null, j = null, jP = null; - int tries = 0; - - //Echoose - - int beforeMoves = getAllValidNarrowMoves(); - - while (tries < MAX_TRIES) { - i = tree.getNode(MathUtils.nextInt(tree.getNodeCount())); - while (tree.getRoot() == i || tree.getParent(i, 0) == tree.getRoot() || tree.getParent(i, 1) == tree.getRoot()) { - i = tree.getNode(MathUtils.nextInt(tree.getNodeCount())); - } - - iP = tree.getParent(i, 0); - if (tree.isReassortment(i) && MathUtils.nextBoolean()) - iP = tree.getParent(i, 1); - - jP = tree.getParent(iP, 0); - if (tree.isReassortment(iP) && MathUtils.nextBoolean()) - jP = tree.getParent(iP, 1); - - j = tree.getChild(jP, 0); - if (j == iP) { - j = tree.getChild(jP, 1); - } - - if (j != iP && i != j && // can still occur if i is child of doubly-linked reassortment - (tree.getNodeHeight(j) < tree.getNodeHeight(iP)) && (tree.getNodeHeight(i) < tree.getNodeHeight(jP))) { - // todo fix height check for cases where i and j get switched - break; - } - tries += 1; - } - //System.out.println("tries = " + tries); - - //Eupdate - if (tries < MAX_TRIES) { - try { - eupdateARG(i, j, iP, jP); - } catch (ARGOperatorFailedException e) { - return Double.NEGATIVE_INFINITY; - } - - tree.pushTreeChangedEvent(iP); - tree.pushTreeChangedEvent(jP); - } else { - //throw new ARGOperatorFailedException("Couldn't find valid narrow move on this tree!!"); - return Double.NEGATIVE_INFINITY; - } - - return Math.log((double) beforeMoves / getAllValidNarrowMoves()); - } - - /** - * WARNING: Assumes strictly bifurcating tree. - */ - public double wide() { - - NodeRef i = null, iP = null, j = null, jP = null; - int tries = 0; - - //Echoose - - while (tries < MAX_TRIES) { - i = tree.getNode(MathUtils.nextInt(tree.getNodeCount())); - while (tree.getRoot() == i) { - i = tree.getNode(MathUtils.nextInt(tree.getNodeCount())); - } - - j = tree.getNode(MathUtils.nextInt(tree.getNodeCount())); - while (j == i || j == tree.getRoot()) { - j = tree.getNode(MathUtils.nextInt(tree.getNodeCount())); - } - - iP = tree.getParent(i); - jP = tree.getParent(j); - - if ((iP != jP) && (i != jP) && (j != iP) && - (tree.getNodeHeight(j) < tree.getNodeHeight(iP)) && - (tree.getNodeHeight(i) < tree.getNodeHeight(jP))) { - break; - } - tries += 1; - } - //System.out.println("tries = " + tries); - - //Eupdate - if (tries < MAX_TRIES) { - try { - eupdateARG(i, j, iP, jP); - } catch (ARGOperatorFailedException e) { - return Double.NEGATIVE_INFINITY; - } - } else { -// throw new ARGOperatorFailedException("Couldn't find valid wide move on this tree!"); - return Double.NEGATIVE_INFINITY; - } - return 0.0; - } - - public int getMode() { - return mode; - } - - public String getOperatorName() { - return ((mode == NARROW) ? "Narrow" : "Wide") + " Exchange"; - } - - private void eupdateARG(NodeRef i, NodeRef j, NodeRef iP, NodeRef jP) throws ARGOperatorFailedException { - - // There are three different cases: - // 1) neither i nor j are reassortments, 2) either i or j are reassortments, 3) both i and j are reassortments - - tree.beginTreeEdit(); - - boolean iBifurcation = tree.isBifurcation(i); - boolean jBifurcation = tree.isBifurcation(j); - - if (iBifurcation && jBifurcation) { - tree.removeChild(iP, i); - tree.removeChild(jP, j); - tree.addChild(jP, i); - tree.addChild(iP, j); - } else if (!iBifurcation && !jBifurcation) { -// tree.singleRemoveChild(iP, i); -// tree.singleRemoveChild(jP, j); -// tree.singleAddChild(jP, i); -// tree.singleAddChild(iP, j); - } else { - if (jBifurcation) { - // one reassortment; force i to be bifurcation and j to be reassortment - NodeRef t = i; - NodeRef tP = iP; - i = j; - iP = jP; - j = t; - jP = tP; - } -// System.err.println(tree.toGraphString()); -// ARGModel.Node iNode = (ARGModel.Node) i; -// ARGModel.Node jNode = (ARGModel.Node) j; -// System.err.println("i = "+iNode.number+" : j = "+jNode.number); - /* tree.removeChild(iP, i); - tree.singleRemoveChild(jP, j); - tree.addChild(jP, i); - tree.singleAddChild(iP, j);*/ - } - - tree.endTreeEdit(); - try { - tree.checkTreeIsValid(); - } catch (MutableTree.InvalidTreeException ite) { - throw new ARGOperatorFailedException(ite.toString()); - } - } - - public double getMinimumAcceptanceLevel() { - if (mode == NARROW) return 0.05; - else return 0.01; - } - - public double getMinimumGoodAcceptanceLevel() { - if (mode == NARROW) return 0.05; - else return 0.01; - } - - public static XMLObjectParser NARROW_EXCHANGE_PARSER = new AbstractXMLObjectParser() { - - public String getParserName() { - return NARROW_EXCHANGE; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - ARGModel treeModel = (ARGModel) xo.getChild(ARGModel.class); - int weight = xo.getIntegerAttribute("weight"); - - return new ARGExchangeOperator(NARROW, treeModel, weight); - } - - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - - public String getParserDescription() { - return "This element represents a narrow exchange operator. " + - "This operator swaps a random subtree with its uncle."; - } - - public Class getReturnType() { - return ExchangeOperator.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{ - AttributeRule.newIntegerRule("weight"), - new ElementRule(ARGModel.class) - }; - - }; - - public static XMLObjectParser WIDE_EXCHANGE_PARSER = new AbstractXMLObjectParser() { - - public String getParserName() { - return WIDE_EXCHANGE; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - ARGModel treeModel = (ARGModel) xo.getChild(ARGModel.class); - int weight = xo.getIntegerAttribute("weight"); - - return new ARGExchangeOperator(WIDE, treeModel, weight); - } - - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - - public String getParserDescription() { - return "This element represents a wide exchange operator. " + - "This operator swaps two random subtrees."; - } - - public Class getReturnType() { - return ExchangeOperator.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{ - AttributeRule.newIntegerRule("weight"), - new ElementRule(ARGModel.class) - }; - - }; -} \ No newline at end of file diff --git a/src/dr/evomodel/arg/operators/ARGOperatorFailedException.java b/src/dr/evomodel/arg/operators/ARGOperatorFailedException.java deleted file mode 100644 index 654f5e3e02..0000000000 --- a/src/dr/evomodel/arg/operators/ARGOperatorFailedException.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * ARGOperatorFailedException.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.arg.operators; - -/** - * @author Andrew Rambaut - */ -public class ARGOperatorFailedException extends Exception { - public ARGOperatorFailedException(String message) { - super(message); - } -} diff --git a/src/dr/evomodel/arg/operators/ARGPartitioningOperator.java b/src/dr/evomodel/arg/operators/ARGPartitioningOperator.java deleted file mode 100644 index fd51a9ea27..0000000000 --- a/src/dr/evomodel/arg/operators/ARGPartitioningOperator.java +++ /dev/null @@ -1,291 +0,0 @@ -/* - * ARGPartitioningOperator.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.arg.operators; - -import dr.evomodel.arg.ARGModel; -import dr.inference.model.CompoundParameter; -import dr.inference.model.Parameter; -import dr.inference.operators.SimpleMCMCOperator; -import dr.math.MathUtils; -import dr.xml.*; - -import java.util.ArrayList; -import java.util.logging.Logger; - -public class ARGPartitioningOperator extends SimpleMCMCOperator { - - private final CompoundParameter partitioningParameters; - private final ARGModel arg; - - public final static String OPERATOR_NAME = "argPartitionOperator"; - public static final String TOSS_SIZE = "tossSize"; - public static final String TOSS_ALL = "tossAll"; - - private final boolean tossAll; - private final boolean isRecombination; - private final int tossSize; - - public ARGPartitioningOperator(ARGModel arg, int tossSize, int weight, boolean tossAll) { - super.setWeight(weight); - - this.arg = arg; - this.partitioningParameters = arg.getPartitioningParameters(); - this.tossSize = tossSize; - this.isRecombination = arg.isRecombinationPartitionType(); - - this.tossAll = tossAll; - } - - /** - * @return the parameter this operator acts on. - */ - public Parameter getParameter() { - return partitioningParameters; - } - - - public final double doOperation() { - double logq = 0; - - final int len = partitioningParameters.getParameterCount(); - - if (len == 0) { - return 0; - } - - boolean[] updatePartition = new boolean[arg.getNumberOfPartitions()]; - - if(tossAll){ - for(int i = 0 ; i < len; i++){ - logq += doFlip(i,updatePartition); - } - }else{ - logq = doFlip(MathUtils.nextInt(len),updatePartition); - } - - arg.fireModelChanged(new PartitionChangedEvent(partitioningParameters, updatePartition)); - return logq; - } - - private double doFlip(int i, boolean[] updatePartition) { - if (isRecombination) { - return doRecombination(partitioningParameters.getParameter(i),updatePartition); - } - - return doReassortment(partitioningParameters.getParameter(i),updatePartition); - - } - - - private double doRecombination(Parameter partition, boolean[] updatePartition) { - - assert checkValidRecombinationPartition(partition); - - int currentBreakLocation = 0; - for (int i = 0, n = arg.getNumberOfPartitions(); i < n; i++) { - if (partition.getParameterValue(i) == 1) { - currentBreakLocation = i; - break; - } - } - - assert currentBreakLocation > 0; - - if (MathUtils.nextBoolean()) { - //Move break right 1 - partition.setParameterValueQuietly(currentBreakLocation, 0.0); - updatePartition[currentBreakLocation] = true; - } else { - partition.setParameterValueQuietly(currentBreakLocation - 1, 1.0); - updatePartition[currentBreakLocation-1] = true; - } - - if (!checkValidRecombinationPartition(partition)) { - return Double.NEGATIVE_INFINITY; - } - - - return 0; - } - - public static boolean checkValidRecombinationPartition(Parameter partition) { - int l = partition.getDimension(); -// if ((partition.getParameterValue(0) == 0 && partition.getParameterValue(l - 1) == 1)) -// return true; -// -// return false; - return (partition.getParameterValue(0) == 0 && partition.getParameterValue(l - 1) == 1); - } - - - private double doReassortment(Parameter partition, boolean[] updatePartition) { - - assert checkValidReassortmentPartition(partition); - - ArrayList list = new ArrayList(tossSize); - - while (list.size() < tossSize) { - int a = MathUtils.nextInt(arg.getNumberOfPartitions() - 1) + 1; - if (!list.contains(a)) { - list.add(a); - } - } - - - for (int a : list) { - if (partition.getParameterValue(a) == 0) { - partition.setParameterValueQuietly(a, 1); - } else { - partition.setParameterValueQuietly(a, 0); - } - updatePartition[a] = true; - } - - - if (!checkValidReassortmentPartition(partition)) { - return Double.NEGATIVE_INFINITY; - } - - return 0; - } - - public static boolean checkValidReassortmentPartition(Parameter partition) { - if (partition.getParameterValue(0) != 0) - return false; - - double[] a = partition.getParameterValues(); - - double sum = 0; - - for (double b : a) - sum += b; - -// if (sum == 0 || sum == a.length) -// return false; -// -// return true; - return !(sum == 0 || sum == a.length); - - } - - @Override - public String getOperatorName() { - return OPERATOR_NAME; - } - - public String getPerformanceSuggestion() { - return null; - } - - public class PartitionChangedEvent { - Parameter partitioning; - boolean[] updatePartition; - - public PartitionChangedEvent(Parameter partitioning, boolean[] updatePartition) { - this.partitioning = partitioning; - this.updatePartition = updatePartition; - } - - public Parameter getParameter() { - return partitioning; - } - - public boolean[] getUpdatedPartitions() { - return updatePartition; - } - } - - public static dr.xml.XMLObjectParser PARSER = new dr.xml.AbstractXMLObjectParser() { - - public String getParserName() { - return OPERATOR_NAME; - } - - public String[] getParserNames() { - return new String[]{ - OPERATOR_NAME, - "tossPartitioningOperator", - }; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - int weight = xo.getIntegerAttribute(WEIGHT); - - ARGModel arg = (ARGModel) xo.getChild(ARGModel.class); - - int tossSize = 1; - if (xo.hasAttribute(TOSS_SIZE)) { - tossSize = xo.getIntegerAttribute(TOSS_SIZE); - - if (tossSize <= 0 || tossSize >= arg.getNumberOfPartitions()) { - throw new XMLParseException("Toss size is incorrect"); - } - } - - boolean tossAll = false; - if(xo.hasAttribute(TOSS_ALL)){ - tossAll = xo.getBooleanAttribute(TOSS_ALL); - } - - Logger.getLogger("dr.evomodel").info("Creating ARGPartitionOperator: " + TOSS_SIZE + "=" + tossSize + - " " + TOSS_ALL + "=" + tossAll); - - - return new ARGPartitioningOperator(arg, tossSize, weight, tossAll); - } - - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - - public String getParserDescription() { - return "An operator that picks a new partitioning uniformly at random."; - } - - public Class getReturnType() { - return ARGPartitioningOperator.class; - } - - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private final XMLSyntaxRule[] rules = { - AttributeRule.newIntegerRule(WEIGHT), - AttributeRule.newIntegerRule(TOSS_SIZE,true), - AttributeRule.newBooleanRule(TOSS_ALL,true), - new ElementRule(ARGModel.class) - }; - }; - - public String toString() { - return "tossPartitioningOperator(" + partitioningParameters.getParameterName() + ")"; - } -} diff --git a/src/dr/evomodel/arg/operators/ARGReassortmentOperator.java b/src/dr/evomodel/arg/operators/ARGReassortmentOperator.java deleted file mode 100644 index c5c0e47800..0000000000 --- a/src/dr/evomodel/arg/operators/ARGReassortmentOperator.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * ARGReassortmentOperator.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.arg.operators; - -import dr.evomodel.arg.ARGModel; -import dr.evomodelxml.tree.TreeModelParser; -import dr.inference.model.CompoundParameter; -import dr.inference.operators.SimpleMCMCOperator; -import dr.math.MathUtils; - -import java.util.logging.Logger; - -public class ARGReassortmentOperator extends SimpleMCMCOperator { - - public static final String ADD_PROBABILITY = "addProbability"; - public static final String ARG_REASSORTMENT_OPERATOR = "argReassortmentOperator"; - public static final String INTERNAL_NODES = "internalNodes"; - public static final String INTERNAL_AND_ROOT = "internalNodesPlusRoot"; - public static final String NODE_RATES = TreeModelParser.NODE_RATES; - public static final String CHOOSE_BRANCHES_FIRST = "chooseBranchesFirst"; - public static final double LOG_TWO = Math.log(2.0); - - private double singlePartitionProbability = 0.0; - private double probBelowRoot = 0.9; - private double size = 0.0; //Used to choose add step - private boolean branchesFirst; - - private ARGModel arg; - - private CompoundParameter internalNodeParameters; - private CompoundParameter internalAndRootNodeParameters; - private CompoundParameter nodeRates; - - public ARGReassortmentOperator(ARGModel arg, int weight, boolean branchesFirst, - double singlePartProb, double addProbability, - CompoundParameter internalNodeParameters, - CompoundParameter internalAndRootNodeParameters, - CompoundParameter nodeRates) { - this.arg = arg; - this.internalNodeParameters = internalNodeParameters; - this.internalAndRootNodeParameters = internalAndRootNodeParameters; - this.nodeRates = nodeRates; - - this.branchesFirst = branchesFirst; - this.singlePartitionProbability = singlePartProb; - - setWeight(weight); - - this.size = addProbability; - - //Transformed for computation reasons - probBelowRoot = -Math.log(1 - Math.sqrt(probBelowRoot)); - } - - - public double doOperation() { - double logHastings = 0; - - if (MathUtils.nextDouble() < 1.0 / (1 + Math.exp(-size))) - logHastings = addOperation() - size; - else - logHastings = removeOperation() + size; - - return logHastings; - } - - private double addOperation() { - if (branchesFirst) - return addOperationBranchesFirst(); - - return addOperationHeightsFirst(); - } - - private double addOperationBranchesFirst() { - - double logHastings = 0; - double treeHeight = arg.getNodeHeight(arg.getRoot()); - double newBifurcationHeight = Double.POSITIVE_INFINITY; - double newReassortmentHeight = Double.POSITIVE_INFINITY; - - double theta = probBelowRoot / treeHeight; - - while (newBifurcationHeight > treeHeight && newReassortmentHeight > treeHeight) { - newBifurcationHeight = MathUtils.nextExponential(theta); - newReassortmentHeight = MathUtils.nextExponential(theta); - } - - logHastings += theta * (newBifurcationHeight + newReassortmentHeight) - LOG_TWO - - 2.0 * Math.log(theta) + Math.log(1 - Math.exp(-2.0 * treeHeight * theta)); - - if (newBifurcationHeight < newReassortmentHeight) { - double temp = newBifurcationHeight; - newBifurcationHeight = newReassortmentHeight; - newReassortmentHeight = temp; - } - - return 0; - } - - private double addOperationHeightsFirst() { - - return 0; - } - - private double removeOperation() { - - return 0; - } - - public String getOperatorName() { - return ARG_REASSORTMENT_OPERATOR; - } - - public String getPerformanceSuggestion() { - return "Try changing the add probability probability"; - } - - private class NoReassortmentEventException extends Exception { - private static final long serialVersionUID = 1L; - - public NoReassortmentEventException() { - super(""); - } - } -} diff --git a/src/dr/evomodel/arg/operators/ARGSubtreeSlideOperator.java b/src/dr/evomodel/arg/operators/ARGSubtreeSlideOperator.java deleted file mode 100644 index 849ff4da96..0000000000 --- a/src/dr/evomodel/arg/operators/ARGSubtreeSlideOperator.java +++ /dev/null @@ -1,632 +0,0 @@ -/* - * ARGSubtreeSlideOperator.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -/* - * RGSubtreeSlideOperator.java - * - * (c) 2002-2005 BEAST Development Core Team - * - * This package may be distributed under the - * Lesser Gnu Public Licence (LGPL) - */ -package dr.evomodel.arg.operators; - -import dr.evolution.tree.MutableTree; -import dr.evolution.tree.NodeRef; -import dr.evolution.tree.Tree; -import dr.evomodel.arg.ARGModel; -import dr.evomodel.arg.ARGModel.Node; -import dr.evomodel.operators.SubtreeSlideOperator; -import dr.inference.operators.*; -import dr.math.MathUtils; -import dr.xml.*; - -import java.util.ArrayList; - -/** - * Implements the subtree slide move. - * - * @author Alexei Drummond - */ -public class ARGSubtreeSlideOperator extends AbstractAdaptableOperator { -// SimpleMCMCOperator implements AdaptableMCMCOperator { - - public static final String SUBTREE_SLIDE = "argSubtreeSlide"; - // public static final String - public static final String SWAP_RATES = "swapRates"; - public static final String SWAP_TRAITS = "swapTraits"; - public static final String DIRICHLET_BRANCHES = "branchesAreScaledDirichlet"; - - private ARGModel tree = null; - private double size = 1.0; - private boolean gaussian = false; - private boolean swapRates; - private boolean swapTraits; - private boolean scaledDirichletBranches; -// private int mode = AdaptableMCMCOperator.DEFAULT; -// AdaptationMode model; - - public ARGSubtreeSlideOperator(ARGModel tree, int weight, double size, boolean gaussian, boolean swapRates, - boolean swapTraits, boolean scaledDirichletBranches, AdaptationMode mode) { - super(mode); - this.tree = tree; - setWeight(weight); - - this.size = size; - this.gaussian = gaussian; - this.swapRates = swapRates; - this.swapTraits = swapTraits; - this.scaledDirichletBranches = scaledDirichletBranches; - -// this.mode = mode; - } - - public void sanityCheck() { - int len = tree.getNodeCount(); - for (int i = 0; i < len; i++) { - Node node = (Node) tree.getNode(i); - if (node.bifurcation) { - boolean equalChild = (node.leftChild == node.rightChild); - if ((equalChild && node.leftChild != null)) { - if (!node.leftChild.bifurcation && ((node.leftChild).leftParent == node)) - ; - else { - System.err.println("Node " + (i + 1) + " is insane."); - System.err.println(tree.toGraphString()); - System.exit(-1); - } - } - } else { - if ((node.leftChild != node.rightChild)) { - System.err.println("Node " + (i + 1) + " is insane."); - System.err.println(tree.toGraphString()); - System.exit(-1); - } - } - } - } - - /** - * Do a probablistic subtree slide move. - * - * @return the log-transformed hastings ratio - */ - public double doOperation() { - -// System.err.println("Starting Subtree Slide Operation."); - double logq = 0; - - double oldTreeHeight = tree.getNodeHeight(tree.getRoot()); - - NodeRef i, newParent, newChild; - - // 1. choose a random node avoiding root - ArrayList potentialSubtrees = new ArrayList(); - int numPotentialSubtrees = this.getSlideableSubtrees(tree, potentialSubtrees); - // System.err.println("Slide:\n"+tree.toGraphString()); - i = potentialSubtrees.get(MathUtils.nextInt(numPotentialSubtrees)); - - // logq = - Math.log(numPotentialSubtrees); - - NodeRef iP = tree.getParent(i); - - // TODO Start rewriting here. - NodeRef CiP = getOtherChild(tree, iP, i); - NodeRef PiP; - if (tree.isBifurcation(iP)) - PiP = tree.getParent(iP); - else { - PiP = tree.getParent(iP, MathUtils.nextInt(2)); - logq -= Math.log(2); // TODO check if really necessary. - } - - // 2. choose a delta to move - double delta = getDelta(); - double oldHeight = tree.getNodeHeight(iP); - double newHeight = oldHeight + delta; - - //newHeight = tree.getNodeHeight(tree.getRoot()) + delta; - - // 3. if the move is up - if (delta > 0) { - - // 3.1 if the topology will change - if (PiP != null && tree.getNodeHeight(PiP) < newHeight) { - - // find new parent - newParent = PiP; - newChild = iP; - while (tree.getNodeHeight(newParent) < newHeight) { - newChild = newParent; - if (tree.isBifurcation(newParent)) - newParent = tree.getParent(newParent); - else { - newParent = tree.getParent(newParent, MathUtils.nextInt(2)); - logq -= Math.log(2); // TODO check if correct. - } - if (newParent == null) break; - } - - //System.err.println("No problem climbing"); - -// logq += Math.log(numPotentialSubtrees); - - tree.beginTreeEdit(); - - // 3.1.1 if creating a new root - if (tree.isRoot(newChild)) { - - if (true) { - tree.endTreeEdit(); - try { - tree.checkTreeIsValid(); - } catch (MutableTree.InvalidTreeException e) { - e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. - } - throw new RuntimeException("Temporarily disable re-rooting"); - } - - //Parameter rootParameter = ((Node)newChild).heightParameter; - //Parameter otherParameter = ((Node)iP).heightParameter; - //tree.swapHeightParameters(newChild,iP); - tree.doubleRemoveChild(iP, CiP); // iP is always bifurcation - tree.doubleRemoveChild(PiP, iP); // PiP can be reassortment - tree.doubleAddChild(iP, newChild); // iP and newChild are always bifurcations, i still connected to iP - if (tree.isBifurcation(PiP)) - tree.addChild(PiP, CiP); - else - tree.addChild(PiP, CiP); - tree.setRoot(iP); - //System.err.println("Creating new root!"); - } - // 3.1.2 no new root - else { - boolean doubly = tree.isBifurcationDoublyLinked(newParent); - - tree.doubleRemoveChild(iP, CiP); // iP bifurcation - tree.doubleRemoveChild(PiP, iP); // PiP can be reassortment - tree.doubleRemoveChild(newParent, newChild); - //tree.doubleAddChild(iP, newChild); - - tree.doubleAddChild(PiP, CiP); - if (!doubly) { - tree.doubleAddChild(iP, newChild); - tree.doubleAddChild(newParent, iP); - } else { - tree.singleAddChild(newParent, iP); - tree.singleAddChildWithOneParent(iP, newChild); - tree.singleAddChild(newParent, newChild); - } - // System.err.println("No new root!"); - } - - // System.err.println("i ="+((Node)i).number); - // System.err.println("iP ="+((Node)iP).number); - // if( newParent != null ) - // System.err.println("newParent ="+((Node)newParent).number+" "+tree.getNodeHeight(newParent)); - // else - // System.err.println("newParent is above root"); - // System.err.println("newChild ="+((Node)newChild).number+" "+tree.getNodeHeight(newChild)); - - - tree.setNodeHeight(iP, newHeight); - // System.err.println("iP height ="+tree.getNodeHeight(iP)); - - // System.err.println("Intermediate slide up:\n"+tree.toGraphString()); - - tree.endTreeEdit(); - try { - tree.checkTreeIsValid(); - } catch (MutableTree.InvalidTreeException ite) { - throw new RuntimeException(ite.toString()); - } - - // 3.1.3 count the hypothetical sources of this destination. - int possibleSources = intersectingEdges(tree, newChild, iP, oldHeight, null); - // System.err.println("possible sources = " + possibleSources); - - logq -= Math.log(possibleSources); - } else { - // 3.2 - // just change the node height - tree.setNodeHeight(iP, newHeight); - logq = 0.0; // TODO check is losing -Log(2) is correct. - } - -// System.err.println("Sanity check up-slide"); -// sanityCheck(); - } - // 4 if we are sliding the subtree down. - else { - // logq = 0; - - // 4.0 is it a valid move? - if (tree.getNodeHeight(i) > newHeight) { - return Double.NEGATIVE_INFINITY; - } - - // 4.1 will the move change the topology - if (tree.getNodeHeight(CiP) > newHeight) { - // System.err.println("Starting down-slide:\n"+tree.toGraphString()); - ArrayList newChildren = new ArrayList(); - int possibleDestinations = intersectingEdges(tree, CiP, iP, newHeight, newChildren); - - // if no valid destinations then return a failure - if (newChildren.size() == 0) //{ return Double.NEGATIVE_INFINITY; } - throw new RuntimeException("no valid destinations"); - - // pick a random parent/child destination edge uniformly from options - int childIndex = MathUtils.nextInt(newChildren.size()); - NodeRef[] draw = (NodeRef[]) newChildren.get(childIndex); - newChild = draw[1]; - newParent = draw[0]; - // ((NodeRef[])newChildren.get(childIndex))[1]; - //int choice = MathUtils.nextInt(2); - NodeRef oops = null; -// if( tree.isBifurcation(newChild) ) -// newParent = tree.getParent(newChild); -// else { -// //newParent = tree.getParent(newChild,MathUtils.nextInt(2)); -// newParent = tree.getParent(newChild,choice); -// if( tree.getNodeHeight(newParent) < newHeight ) -// newParent = tree.getParent(newChild,1-choice); -// oops = tree.getParent(newChild,1-choice); -// System.err.println("Grabbing random child."); -// logq -= Math.log(2); // TODO check ratio -// } -// //NodeRef oops - //newParent = - -// logq += Math.log(possibleDestinations); - - tree.beginTreeEdit(); - - // 4.1.1 if iP was root - if (tree.isRoot(iP)) { - // new root is CiP, but root cannot be a reassortment - if (!tree.isBifurcation(CiP)) - throw new RuntimeException("root cannot be a reassortment"); - boolean doubly = tree.isBifurcationDoublyLinked(newParent); - tree.doubleRemoveChild(iP, CiP); - tree.doubleRemoveChild(newParent, newChild); - - // System.err.println("Down-slide disconnect:\n"+tree.toGraphString()); - if (tree.isBifurcation(newChild)) - tree.doubleAddChild(iP, newChild); - else - tree.singleAddChildWithOneParent(iP, newChild); - if (!doubly) - tree.doubleAddChild(newParent, iP); - else { - tree.singleAddChild(newParent, iP); - tree.singleAddChildWithOneParent(newParent, newChild); - } - //tree.doubleAddChild(newParent, iP); - //tree.swapHeightParameters(iP,CiP); // TODO - tree.setRoot(CiP); -// System.err.println("DOWN: Creating new root!"); // TODO still not tested - } else { - boolean doubly = tree.isBifurcationDoublyLinked(newParent); // or is it CiP = newParent? - tree.doubleRemoveChild(iP, CiP); - tree.doubleRemoveChild(PiP, iP); - tree.doubleRemoveChild(newParent, newChild); - // System.err.println("Down-slide disconnect:\n"+tree.toGraphString()); - if (tree.isBifurcation(newChild)) - tree.doubleAddChild(iP, newChild); - else - tree.singleAddChildWithOneParent(iP, newChild); - tree.doubleAddChild(PiP, CiP); - if (!doubly) - tree.doubleAddChild(newParent, iP); // Only works if iP is bifurcation - else { - tree.singleAddChild(newParent, iP); - tree.singleAddChildWithOneParent(newParent, newChild); - } -// System.err.println("DOWN: no new root!"); - /* if( true ) { - - try { - tree.endTreeEdit(); - } catch(MutableTree.InvalidTreeException ite) { - throw new RuntimeException(ite.toString()); - } - throw new OperatorFailedException(""); - } */ - } - - tree.setNodeHeight(iP, newHeight); -// System.err.println("i = " + ((Node) i).number); -// System.err.println("iP = " + ((Node) iP).number); -// System.err.println("CiP = " + ((Node) CiP).number); -// System.err.println("newChild = " + ((Node) newChild).number + " " -// + tree.getNodeHeight(newChild)); -// System.err.println("newParent = " + ((Node) newParent).number + " " -// + tree.getNodeHeight(newParent)); -// if (oops != null) -// System.err.println("oops = " + ((Node) oops).number + " " -// + tree.getNodeHeight(oops)); -// System.err.println("newHeight = " + newHeight); - // System.err.println("After slide down:\n"+tree.toGraphString()); - - tree.endTreeEdit(); - try { - tree.checkTreeIsValid(); - } catch (MutableTree.InvalidTreeException ite) { - throw new RuntimeException(ite.toString()); - } - - //logq = -Math.log((double) possibleDestinations); - logq += Math.log((double) possibleDestinations); - - - } else { - try { - tree.setNodeHeight(iP, newHeight); - } catch (Exception e) { -// System.err.println("iP =" + ((Node) iP).number); -// System.err.println("newHeight =" + newHeight); - //System.exit(-1); - } - logq = 0.0; - } - // System.err.println("After slide down:\n"+tree.toGraphString()); -// System.err.println("Sanity check in down-slide."); -// sanityCheck(); - } -/* - if (swapRates) { - NodeRef j = tree.getNode(MathUtils.nextInt(tree.getNodeCount())); - if (j != i) { - double tmp = tree.getNodeRate(i); - tree.setNodeRate(i, tree.getNodeRate(j)); - tree.setNodeRate(j, tmp); - } - - } - - if (swapTraits) { - NodeRef j = tree.getNode(MathUtils.nextInt(tree.getNodeCount())); - if (j != i) { - double tmp = tree.getNodeTrait(i); - tree.setNodeTrait(i, tree.getNodeTrait(j)); - tree.setNodeTrait(j, tmp); - } - - } -*/ - - // todo fix - // Reject all trees in which the root is doubly- - if (tree.isBifurcationDoublyLinked(tree.getRoot())) - throw new RuntimeException("invalid slide"); - - // todo -- check all ARGTree.Roots - if (!tree.validRoot()) - throw new RuntimeException("Roots are invalid"); - - if (logq == Double.NEGATIVE_INFINITY) - throw new RuntimeException("invalid slide"); -// System.err.println("Ending Subtree Slide Operation."); - //System.err.println("logq = "+logq); - // logq = 0; - - - if (scaledDirichletBranches) { - if (oldTreeHeight != tree.getNodeHeight(tree.getRoot())) - throw new RuntimeException("Temporarily disabled."); // TODO calculate Hastings ratio - } - - - return logq; - } - - private double getDelta() { - if (!gaussian) { - return (MathUtils.nextDouble() * size) - (size / 2.0); - } else { - return MathUtils.nextGaussian() * size; - } - } - - private int getSlideableSubtrees(ARGModel tree, ArrayList potentials) { - int count = 0; - for (int i = 0, n = tree.getNodeCount(); i < n; i++) { - NodeRef node = tree.getNode(i); - if (!tree.isRoot(node) && tree.isBifurcation(node) - && tree.isBifurcation(tree.getParent(node))) { - if (potentials != null) - potentials.add(node); - count++; - } - } - return count; - } - - private int intersectingEdges(ARGModel tree, NodeRef node, NodeRef parent, double height, ArrayList directChildren) { - - // if( tree.isBifurcation(node) ) { - //ree.getParent(node); tree.getMinParentNodeHeight(node); - //NodeRef parent = tree.getParent(node); - if (tree.getNodeHeight(parent) < height) return 0; - - if (tree.getNodeHeight(node) < height) { - if (directChildren != null) { - NodeRef[] addition = new NodeRef[2]; - addition[0] = parent; - addition[1] = node; - directChildren.add(addition); - } - //directChildren.add(node); - return 1; - } - - int count = 0; - //for (int i = 0; i < tree.getChildCount(node); i++) { - count += intersectingEdges(tree, tree.getChild(node, 0), node, height, directChildren); - if (tree.isBifurcation(node)) - count += intersectingEdges(tree, tree.getChild(node, 1), node, height, directChildren); - - return count; - } - // Handle reassortment nodes -// // Only the parental edge which routines flows down is important -// NodeRef parent0 = tree.getParent(node,0); -// NodeRef parent1 = tree.getParent(node,1); -// double thisHeight = tree.getNodeHeight(node); -// double height0 = tree.getNodeHeight(parent0); -// double height1 = tree.getNodeHeight(parent1); -// -// if( (height0 < height) && (height1 < height) ) return 0; -// int count = 0; -// if( (thisHeight < height) && (height0 >= height) ) { -// if( directChildren !=null ) { -// NodeRef[] addition = new NodeRef[2]; -// addition[0] = parent0; -// addition[1] = node; -// directChildren.add(addition); -// } -// //directChildren.add(node); -// count += 1; -// } -// if( (thisHeight < height) && (height1 >= height) ) { -// if( directChildren != null ) { -// NodeRef[] addition = new NodeRef[2]; -// addition[0] = parent1; -// addition[1] = node; -// directChildren.add(addition); -// } -// //directChildren.add(node); -// count += 1; -// } -// if( count > 0 ) -// return count; -// -// return intersectingEdges(tree, tree.getChild(node,0), height, directChildren); -// } - - /** - * @return the other child of the given parent. - */ - private NodeRef getOtherChild(Tree tree, NodeRef parent, NodeRef child) { - - if (tree.getChild(parent, 0) == child) { - return tree.getChild(parent, 1); - } else { - return tree.getChild(parent, 0); - } - } - - public double getSize() { - return size; - } - - public void setSize(double size) { - this.size = size; - } - - @Override - protected double getAdaptableParameterValue() { - return Math.log(getSize()); - } - - public void setAdaptableParameterValue(double value) { - setSize(Math.exp(value)); - } - - public double getRawParameter() { - return getSize(); - } - -// public int getMode() { -// return mode; -// } - - public String getAdaptableParameterName() { - return "size"; - } - - public String getOperatorName() { - return SUBTREE_SLIDE; - } - - public static dr.xml.XMLObjectParser PARSER = new dr.xml.AbstractXMLObjectParser() { - - public String getParserName() { - return SUBTREE_SLIDE; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - boolean swapRates = false; - boolean swapTraits = false; - boolean scaledDirichletBranches = false; - - AdaptationMode mode = AdaptationMode.parseMode(xo); - - if (xo.hasAttribute(SWAP_RATES)) { - swapRates = xo.getBooleanAttribute(SWAP_RATES); - } - if (xo.hasAttribute(SWAP_TRAITS)) { - swapTraits = xo.getBooleanAttribute(SWAP_TRAITS); - } - - if (xo.hasAttribute(DIRICHLET_BRANCHES)) { - scaledDirichletBranches = xo.getBooleanAttribute(DIRICHLET_BRANCHES); - } - - ARGModel treeModel = (ARGModel) xo.getChild(ARGModel.class); - int weight = xo.getIntegerAttribute("weight"); - double size = xo.getDoubleAttribute("size"); - boolean gaussian = xo.getBooleanAttribute("gaussian"); - return new ARGSubtreeSlideOperator(treeModel, weight, size, gaussian, swapRates, - swapTraits, scaledDirichletBranches, mode); - } - - public String getParserDescription() { - return "An operator that slides a subtree."; - } - - public Class getReturnType() { - return SubtreeSlideOperator.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private final XMLSyntaxRule[] rules = { - AttributeRule.newIntegerRule("weight"), - AttributeRule.newDoubleRule("size"), - AttributeRule.newBooleanRule("gaussian"), - AttributeRule.newBooleanRule(SWAP_RATES, true), - AttributeRule.newBooleanRule(SWAP_TRAITS, true), - AttributeRule.newBooleanRule(AUTO_OPTIMIZE, true), - new ElementRule(ARGModel.class) - }; - }; - -} diff --git a/src/dr/evomodel/arg/operators/ARGSwapOperator.java b/src/dr/evomodel/arg/operators/ARGSwapOperator.java deleted file mode 100644 index 5a8933b7c3..0000000000 --- a/src/dr/evomodel/arg/operators/ARGSwapOperator.java +++ /dev/null @@ -1,639 +0,0 @@ -/* - * ARGSwapOperator.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.arg.operators; - -import dr.evolution.tree.MutableTree; -import dr.evolution.tree.NodeRef; -import dr.evomodel.arg.ARGModel; -import dr.evomodel.arg.ARGModel.Node; -import dr.inference.operators.SimpleMCMCOperator; -import dr.math.MathUtils; -import dr.xml.*; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.logging.Logger; - -/** - * This method moves the arg model around. Use of both the - * reassortment and bifurcation modes, as well as the event operator, - * satisfies irreducibility. - * - * @author ebloomqu - * @author Marc A. Suchard - */ -public class ARGSwapOperator extends SimpleMCMCOperator { - - public static final String ARG_SWAP_OPERATOR = "argSwapOperator"; - public static final String SWAP_TYPE = "type"; - public static final String BIFURCATION_SWAP = "bifurcationSwap"; - public static final String REASSORTMENT_SWAP = "reassortmentSwap"; - public static final String DUAL_SWAP = "dualSwap"; - public static final String FULL_SWAP = "fullSwap"; - public static final String NARROW_SWAP = "narrowSwap"; - - private ARGModel arg; - private String mode; - - public ARGSwapOperator(ARGModel arg, String mode, int weight) { - this.arg = arg; - this.mode = mode; - - setWeight(weight); - } - - - public double doOperation() { - - if (mode.equals(NARROW_SWAP)) { - return narrowSwap(); - } - - - if ((mode.equals(REASSORTMENT_SWAP) || mode.equals(DUAL_SWAP)) && - arg.getReassortmentNodeCount() == 0) { - return 0.0; - } - - ArrayList bifurcationNodes = new ArrayList(arg.getNodeCount()); - ArrayList reassortmentNodes = new ArrayList(arg.getNodeCount()); - - setupBifurcationNodes(bifurcationNodes); - setupReassortmentNodes(reassortmentNodes); - - if (mode.equals(BIFURCATION_SWAP)) { - return bifurcationSwap(bifurcationNodes.get(MathUtils.nextInt(bifurcationNodes.size()))); - } else if (mode.equals(REASSORTMENT_SWAP)) { - return reassortmentSwap(reassortmentNodes.get(MathUtils.nextInt(reassortmentNodes.size()))); - } else if (mode.equals(DUAL_SWAP)) { - reassortmentSwap(reassortmentNodes.get(MathUtils.nextInt(reassortmentNodes.size()))); - return bifurcationSwap(bifurcationNodes.get(MathUtils.nextInt(bifurcationNodes.size()))); - } - - bifurcationNodes.addAll(reassortmentNodes); - - Collections.sort(bifurcationNodes, NodeSorter); - - for (NodeRef x : bifurcationNodes) { - if (arg.isBifurcation(x)) - bifurcationSwap(x); - else - reassortmentSwap(x); - } - - return 0; - } - - private double narrowSwap() { - ArrayList possibleSwaps = new ArrayList(arg.getNodeCount()); - findAllNarrowSwaps(possibleSwaps); - int possibleSwapsBefore = possibleSwaps.size(); - - if (possibleSwapsBefore == 0) - return 0; - - doNarrowSwap(possibleSwaps.get(MathUtils.nextInt(possibleSwaps.size()))); - - possibleSwaps.clear(); - findAllNarrowSwaps(possibleSwaps); - - return Math.log((double) possibleSwapsBefore / possibleSwaps.size()); - } - - public int findAllNarrowSwaps(ArrayList moves) { - - for (int i = 0, n = arg.getInternalNodeCount(); i < n; i++) { - Node x = (Node) arg.getInternalNode(i); - if (x.bifurcation && !x.isRoot() && x.leftParent.bifurcation) { - NarrowSwap a = new NarrowSwap(x.leftChild, x, x.leftParent); - NarrowSwap b = new NarrowSwap(x.rightChild, x, x.leftParent); - - if (a.isValid()) - moves.add(a); - if (b.isValid()) - moves.add(b); - } - } - return moves.size(); - } - - private void doNarrowSwap(NarrowSwap swap) { - arg.beginTreeEdit(); - - String before = arg.toARGSummary(); - - if (swap.c == swap.pb) { - Node c = (Node) swap.c; - Node p = (Node) swap.p; - Node gp = (Node) swap.gp; - - if (c.leftParent == p) { - c.leftParent = gp; - c.rightParent = p; - } else { - c.leftParent = p; - c.rightParent = gp; - } - } else if (arg.getChild(swap.p, 0) == arg.getChild(swap.p, 1)) { - Node p = (Node) swap.p; - Node c = (Node) swap.c; - - if (MathUtils.nextBoolean()) - p.leftChild = c.leftParent = null; - else - p.rightChild = c.rightParent = null; - arg.removeChild(swap.gp, swap.pb); - - arg.singleAddChild(swap.gp, swap.c); - arg.singleAddChild(swap.p, swap.pb); - } else { - arg.removeChild(swap.gp, swap.pb); - arg.removeChild(swap.p, swap.c); - arg.singleAddChild(swap.gp, swap.c); - arg.singleAddChild(swap.p, swap.pb); - } - - assert nodeCheck() : swap + " " + before + " " + arg.toARGSummary(); - - arg.pushTreeChangedEvent(swap.gp); - arg.pushTreeChangedEvent(swap.p); - - arg.endTreeEdit(); - try { - arg.checkTreeIsValid(); - } catch (MutableTree.InvalidTreeException ite) { - System.out.println(swap); - System.out.println(before); - System.err.println(ite.getMessage()); - System.exit(-1); - } catch (NullPointerException e) { - System.out.println(swap); - System.out.println(before); - System.err.println(e.getMessage()); - System.exit(-1); - } - } - - private class NarrowSwap { - public NodeRef c; - public NodeRef p; - public NodeRef gp; - public NodeRef pb; - - public NarrowSwap(NodeRef child, NodeRef parent, NodeRef gParent) { - c = child; - p = parent; - gp = gParent; - pb = arg.getOtherChild(gParent, parent); - } - - public boolean isValid() { -// if (arg.getNodeHeight(pb) < arg.getNodeHeight(p)) -// return true; -// return false; - return (arg.getNodeHeight(pb) < arg.getNodeHeight(p)); - } - - public String toString() { - return "Child: " + c.toString() + - ", Parent: " + p.toString() + - ", G-parent: " + gp.toString() + - ", P-brother: " + pb.toString(); - } - - } - - - private double bifurcationSwap(NodeRef x) { - Node startNode = (Node) x; - -// Node keepChild = startNode.leftChild; - Node moveChild = startNode.rightChild; - - if (MathUtils.nextBoolean()) { -// keepChild = moveChild; - moveChild = startNode.leftChild; - } - - ArrayList possibleNodes = new ArrayList(arg.getNodeCount()); - - findNodesAtHeight(possibleNodes, startNode.getHeight()); - - assert !possibleNodes.contains(startNode); - assert possibleNodes.size() > 0; - - - Node swapNode = (Node) possibleNodes.get(MathUtils.nextInt(possibleNodes.size())); - Node swapNodeParent = swapNode.leftParent; - - - arg.beginTreeEdit(); - - String before = arg.toARGSummary(); - - - if (swapNode.bifurcation) { - swapNodeParent = swapNode.leftParent; - - arg.singleRemoveChild(startNode, moveChild); - - if (swapNodeParent.bifurcation) { - arg.singleRemoveChild(swapNodeParent, swapNode); - arg.singleAddChild(swapNodeParent, moveChild); - } else { - arg.doubleRemoveChild(swapNodeParent, swapNode); - arg.doubleAddChild(swapNodeParent, moveChild); - } - - arg.singleAddChild(startNode, swapNode); - - } else { - boolean leftSide = true; - boolean[] sideOk = {swapNode.leftParent.getHeight() > startNode.getHeight(), - swapNode.rightParent.getHeight() > startNode.getHeight()}; - - if (sideOk[0] && sideOk[1]) { - if (MathUtils.nextBoolean()) { - swapNodeParent = swapNode.rightParent; - leftSide = false; - } - } else if (sideOk[1]) { - swapNodeParent = swapNode.rightParent; - leftSide = false; - } - - //Double linked parents - if (swapNode.leftParent == swapNode.rightParent) { - arg.singleRemoveChild(startNode, moveChild); - - if (leftSide) { - swapNode.leftParent = null; - swapNodeParent.leftChild = null; - } else { - swapNode.rightParent = null; - swapNodeParent.rightChild = null; - } - - arg.singleAddChild(startNode, swapNode); - arg.singleAddChild(swapNodeParent, moveChild); - } else if (swapNode.leftParent == startNode || swapNode.rightParent == startNode) { - arg.singleRemoveChild(startNode, moveChild); - - if (swapNodeParent.bifurcation) { - arg.singleRemoveChild(swapNodeParent, swapNode); - arg.singleAddChild(swapNodeParent, moveChild); - } else { - arg.doubleRemoveChild(swapNodeParent, swapNode); - arg.doubleAddChild(swapNodeParent, moveChild); - } - - if (startNode.leftChild == null) - startNode.leftChild = swapNode; - else - startNode.rightChild = swapNode; - - if (swapNode.leftParent == null) - swapNode.leftParent = startNode; - else - swapNode.rightParent = startNode; - - } else { - arg.singleRemoveChild(startNode, moveChild); - - if (swapNodeParent.bifurcation) { - arg.singleRemoveChild(swapNodeParent, swapNode); - arg.singleAddChild(swapNodeParent, moveChild); - } else { - arg.doubleRemoveChild(swapNodeParent, swapNode); - arg.doubleAddChild(swapNodeParent, moveChild); - } - arg.singleAddChild(startNode, swapNode); - } - } - - arg.pushTreeChangedEvent(); // TODO Send only changed nodes -// arg.pushTreeChangedEvent(startNode); -// arg.pushTreeChangedEvent(swapNodeParent); - - assert nodeCheck(); - - arg.endTreeEdit(); - try { - arg.checkTreeIsValid(); - } catch (MutableTree.InvalidTreeException ite) { - System.out.println(before); - System.err.println(ite.getMessage()); - System.exit(-1); - } - - return 0; - } - - private double reassortmentSwap(NodeRef x) { - Node startNode = (Node) x; - Node startChild = startNode.leftChild; - - ArrayList possibleNodes = new ArrayList(arg.getNodeCount()); - - findNodesAtHeight(possibleNodes, startNode.getHeight()); - - assert !possibleNodes.contains(startNode); - assert possibleNodes.size() > 0; - - Node swapNode = (Node) possibleNodes.get(MathUtils.nextInt(possibleNodes.size())); - - Node swapParent; - - arg.beginTreeEdit(); - - if (swapNode.bifurcation) { - swapParent = swapNode.leftParent; - - arg.doubleRemoveChild(startNode, startChild); - - if (swapParent.bifurcation) - arg.singleRemoveChild(swapParent, swapNode); - else - arg.doubleRemoveChild(swapParent, swapNode); - - arg.doubleAddChild(startNode, swapNode); - - - if (startChild.bifurcation) { - startChild.leftParent = swapParent; - startChild.rightParent = swapParent; - } else { - if (startChild.leftParent == null) { - startChild.leftParent = swapParent; - } else { - startChild.rightParent = swapParent; - } - } - if (!swapParent.bifurcation) { - swapParent.leftChild = startChild; - swapParent.rightChild = startChild; - } else { - if (swapParent.leftChild == null) { - swapParent.leftChild = startChild; - } else { - swapParent.rightChild = startChild; - } - } - - } else { - - boolean leftSide = true; - boolean[] sideOk = {swapNode.leftParent.getHeight() > startNode.getHeight(), - swapNode.rightParent.getHeight() > startNode.getHeight()}; - - swapParent = swapNode.leftParent; - - if (sideOk[0] && sideOk[1]) { - if (MathUtils.nextBoolean()) { - leftSide = false; - swapParent = swapNode.rightParent; - } - } else if (sideOk[1]) { - leftSide = false; - swapParent = swapNode.rightParent; - } - - if (swapNode.leftParent == swapNode.rightParent) { - arg.doubleRemoveChild(startNode, startChild); - - if (leftSide) { - swapParent.leftChild = swapNode.leftParent = null; - swapParent.leftChild = startChild; - swapNode.leftParent = startNode; - } else { - swapParent.rightChild = swapNode.rightParent = null; - swapParent.rightChild = startChild; - swapNode.rightParent = startNode; - } - - startNode.leftChild = startNode.rightChild = swapNode; - - if (startChild.bifurcation) { - startChild.leftParent = startChild.rightParent = swapParent; - } else { - if (startChild.leftParent == null) - startChild.leftParent = swapParent; - else - startChild.rightParent = swapParent; - } - } else { - arg.doubleRemoveChild(startNode, startChild); - - if (swapParent.bifurcation) - arg.singleRemoveChild(swapParent, swapNode); - else - arg.doubleRemoveChild(swapParent, swapNode); - - startNode.leftChild = startNode.rightChild = swapNode; - - if (leftSide) - swapNode.leftParent = startNode; - else - swapNode.rightParent = startNode; - - if (swapParent.bifurcation) { - if (swapParent.leftChild == null) - swapParent.leftChild = startChild; - else - swapParent.rightChild = startChild; - } else { - swapParent.leftChild = swapParent.rightChild = startChild; - } - - if (startChild.bifurcation) { - startChild.leftParent = startChild.rightParent = swapParent; - } else { - if (startChild.leftParent == null) - startChild.leftParent = swapParent; - else - startChild.rightParent = swapParent; - } - - } - - } - - arg.pushTreeChangedEvent(); // TODO Limit tree hit - - arg.endTreeEdit(); - try { - arg.checkTreeIsValid(); - } catch (MutableTree.InvalidTreeException ite) { - System.err.println(ite.getMessage()); - System.exit(-1); - } - - - return 0; - } - - private void setupBifurcationNodes(ArrayList list) { - for (int i = 0, n = arg.getNodeCount(); i < n; i++) { - NodeRef x = arg.getNode(i); - if (arg.isInternal(x) && arg.isBifurcation(x) && !arg.isRoot(x)) { - list.add(x); - } - } - } - - private void setupReassortmentNodes(ArrayList list) { - for (int i = 0, n = arg.getNodeCount(); i < n; i++) { - NodeRef x = arg.getNode(i); - if (arg.isReassortment(x)) { - list.add(x); - } - } - } - - - private void findNodesAtHeight(ArrayList x, double height) { - for (int i = 0, n = arg.getNodeCount(); i < n; i++) { - Node test = (Node) arg.getNode(i); - if (test.getHeight() < height) { - if (test.bifurcation) { - if (test.leftParent.getHeight() > height) { - x.add(test); - } - } else { - if (test.leftParent.getHeight() > height) { - x.add(test); - } - if (test.rightParent.getHeight() > height) { - x.add(test); - } - } - } - } - } - - - public String getOperatorName() { - return mode; - } - - public String getPerformanceSuggestion() { - return ""; - } - - private Comparator NodeSorter = new Comparator() { - - public int compare(NodeRef o1, NodeRef o2) { - double[] heights = {arg.getNodeHeight(o1), arg.getNodeHeight(o2)}; - - if (heights[0] < heights[1]) { - return -1; - } else if (heights[0] > heights[1]) { - return 1; - } - - return 0; - } - }; - - public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { - - public String getParserDescription() { - return "Swaps nodes on a tree"; - } - - public Class getReturnType() { - return ARGSwapOperator.class; - } - - private String[] validFormats = {BIFURCATION_SWAP, REASSORTMENT_SWAP, - DUAL_SWAP, FULL_SWAP, NARROW_SWAP}; - - private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{ - AttributeRule.newIntegerRule(WEIGHT), - new StringAttributeRule(SWAP_TYPE, "The mode of the operator", - validFormats, false), - new ElementRule(ARGModel.class), - - }; - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - int weight = xo.getIntegerAttribute(WEIGHT); - - String mode = xo.getStringAttribute(SWAP_TYPE); - - Logger.getLogger("dr.evomodel").info("Creating ARGSwapOperator: " + mode); - - ARGModel arg = (ARGModel) xo.getChild(ARGModel.class); - return new ARGSwapOperator(arg, mode, weight); - } - - public String getParserName() { - return ARG_SWAP_OPERATOR; - } - - }; - - public boolean nodeCheck() { - for (int i = 0, n = arg.getNodeCount(); i < n; i++) { - Node x = (Node) arg.getNode(i); - - if (x.leftParent != x.rightParent && - x.leftChild != x.rightChild) { - return false; - } - if (x.leftParent != null) { - if (x.leftParent.leftChild.getNumber() != i && - x.leftParent.rightChild.getNumber() != i) - return false; - } - if (x.rightParent != null) { - if (x.rightParent.leftChild.getNumber() != i && - x.rightParent.rightChild.getNumber() != i) - return false; - } - if (x.leftChild != null) { - if (x.leftChild.leftParent.getNumber() != i && - x.leftChild.rightParent.getNumber() != i) - return false; - } - if (x.rightChild != null) { - if (x.rightChild.leftParent.getNumber() != i && - x.rightChild.rightParent.getNumber() != i) - return false; - } - } - - return true; - } - -} diff --git a/src/dr/evomodel/arg/operators/NonContiguousPartitionsException.java b/src/dr/evomodel/arg/operators/NonContiguousPartitionsException.java deleted file mode 100644 index c2a5ea13f7..0000000000 --- a/src/dr/evomodel/arg/operators/NonContiguousPartitionsException.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * NonContiguousPartitionsException.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.arg.operators; - -/** - * Created by IntelliJ IDEA. - * User: msuchard - * Date: Jan 19, 2007 - * Time: 11:04:27 AM - * To change this template use File | Settings | File Templates. - */ -public class NonContiguousPartitionsException extends Exception { - public NonContiguousPartitionsException(String s) { - super(s); - } -} diff --git a/src/dr/evomodel/arg/operators/ObsoleteARGAddRemoveEventOperator.java b/src/dr/evomodel/arg/operators/ObsoleteARGAddRemoveEventOperator.java deleted file mode 100755 index 1f1c81b297..0000000000 --- a/src/dr/evomodel/arg/operators/ObsoleteARGAddRemoveEventOperator.java +++ /dev/null @@ -1,1050 +0,0 @@ -/* - * ObsoleteARGAddRemoveEventOperator.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -/* - * AddRemoveSubtreeOperator.java - * - * (c) 2002-2005 BEAST Development Core Team - * - * This package may be distributed under the - * Lesser Gnu Public Licence (LGPL) - */ -package dr.evomodel.arg.operators; - -import dr.evolution.tree.NodeRef; -import dr.evolution.tree.Tree; -import dr.evolution.tree.TreeUtils; -import dr.evomodel.arg.ARGModel; -import dr.evomodel.arg.ARGModel.Node; -import dr.evomodelxml.tree.TreeModelParser; -import dr.inference.model.CompoundParameter; -import dr.inference.model.Parameter; -import dr.inference.operators.*; -import dr.math.MathUtils; -import dr.math.functionEval.GammaFunction; -import dr.xml.*; - -import java.util.ArrayList; - -/** - * Implements the subtree slide move. - * - * @author Marc Suchard - */ -public class ObsoleteARGAddRemoveEventOperator extends AbstractAdaptableOperator { -// SimpleMCMCOperator implements AdaptableMCMCOperator { - - public static final String SUBTREE_SLIDE = "addremoveARGEvent"; - public static final String SWAP_RATES = "swapRates"; - public static final String SWAP_TRAITS = "swapTraits"; - public static final String MAX_VALUE = "maxTips"; - public static final String SINGLE_PARTITION = "singlePartitionProbability"; - public static final String IS_RECOMBINATION = "isRecombination"; - - public static final String JUST_INTERNAL = "justInternalNodes"; - public static final String INTERNAL_AND_ROOT = "internalAndRootNodes"; - public static final String NODE_RATES = TreeModelParser.NODE_RATES; - - private ARGModel arg = null; - private double size = 1.0; - private boolean gaussian = false; - private double singlePartitionProbability = 0.0; - private boolean isRecombination = false; - // private boolean swapRates; - // private boolean swapTraits; - // private int mode = AdaptableMCMCOperator.DEFAULT; - private CompoundParameter internalNodeParameters; - private CompoundParameter internalAndRootNodeParameters; - private CompoundParameter nodeRates; -// private int maxTips = 1; - - public ObsoleteARGAddRemoveEventOperator(ARGModel arg, int weight, double size, boolean gaussian, - boolean swapRates, boolean swapTraits, AdaptationMode mode, - CompoundParameter param1, - CompoundParameter param2, - CompoundParameter param3, - double singlePartitionProbability, boolean isRecombination) { - super(mode); - this.arg = arg; - setWeight(weight); -// this.maxTips = maxTips; - this.size = size; - this.gaussian = gaussian; -// this.swapRates = swapRates; -// this.swapTraits = swapTraits; - this.internalNodeParameters = param1; - this.internalAndRootNodeParameters = param2; - this.nodeRates = param3; - this.singlePartitionProbability = singlePartitionProbability; - this.isRecombination = isRecombination; - -// this.mode = mode; - } - - - /** - * Do a add/remove reassortment node operation - * - * @return the log-transformed hastings ratio - */ - public double doOperation() { -// System.err.println("Starting AddRemove Operation"); - - double logq = 0; - try { - if (MathUtils.nextDouble() < 0.5) - logq = AddOperation(); - else - logq = RemoveOperation(); - } catch (ARGOperatorFailedException ofe) { - if (ofe.getMessage().compareTo("No reassortment nodes to remove.") != 0) { - System.err.println("Catch: " + ofe.getMessage()); -// System.exit(-1); - } - } - if (arg.isBifurcationDoublyLinked(arg.getRoot())) - throw new RuntimeException("trouble with double-rooted root"); - return logq; - } - -/* - private ArrayList getPotentialSubtreesToMerge() { - ArrayList potentials = new ArrayList(); - int n = arg.getNodeCount(); - for(int i=0; i potentials = new ArrayList(); - int n = arg.getNodeCount(); - for(int i=0; i list) { - int count = 0; - int n = arg.getNodeCount(); - for (int i = 0; i < n; i++) { - Node node = (Node) arg.getNode(i); - if (node.leftParent != null) { // rules out only the root; may subclass for different types of problems - list.add(node); - count++; - if (node.isReassortment()) { - list.add(node); - count++; // reassortment nodes have two parent branches - } - } - } -// int check = arg.getNodeCount() + arg.getReassortmentNodeCount() - 1; -// if( check != count ) { -// System.err.println("What the fuck?"); -// System.exit(-1); -// } - return count; - } - - private int findCurrentReassortmentNodes(ArrayList list) { - int count = 0; - int n = arg.getNodeCount(); - Node root = (Node) arg.getRoot(); - for (int i = 0; i < n; i++) { - Node node = (Node) arg.getNode(i); - if (node.isReassortment() && (node.leftParent != root && node.rightParent != root)) { - if (list != null) - list.add(node); - count++; - } - } - return count; - } - - /*private double RemoveOperation() throws OperatorFailedException { - arg.beginTreeEdit(); - if (arg.getReassortmentNodeCount() > 0) - arg.removeNullCounter(); - try { - arg.endTreeEdit(); - } catch (MutableTree.InvalidTreeException ite) { - throw new RuntimeException(ite.toString() + "\n" + arg.toString() - + "\n" + Tree.Utils.uniqueNewick(arg, arg.getRoot())); - } - arg.pushTreeSizeChangedEvent(); - return 0; - }*/ - - /* private double AddOperation() throws OperatorFailedException { - arg.beginTreeEdit(); - arg.addNullCounter(); - try { - arg.endTreeEdit(); - } catch (MutableTree.InvalidTreeException ite) { - throw new RuntimeException(ite.toString() + "\n" + arg.toString() - + "\n" + Tree.Utils.uniqueNewick(arg, arg.getRoot())); - } - arg.pushTreeSizeChangedEvent(); - return 0; - } - */ - - private double RemoveOperation() throws ARGOperatorFailedException { - double logq = 0; - -// System.err.println("Starting remove ARG operation."); - - // 1. Draw reassortment node uniform randomly - - ArrayList potentialNodes = new ArrayList(); - - int totalPotentials = findCurrentReassortmentNodes(potentialNodes); - if (totalPotentials == 0) - throw new ARGOperatorFailedException("No reassortment nodes to remove."); - Node recNode = (Node) potentialNodes.get(MathUtils.nextInt(totalPotentials)); - logq += Math.log(totalPotentials); - - double reverseReassortmentSpan = 0; - double reverseBifurcationSpan = 0; - - arg.beginTreeEdit(); - boolean doneSomething = false; - Node recParent = recNode.leftParent; - Node recChild = recNode.leftChild; - if (recNode.leftParent == recNode.rightParent) { // Doubly linked. - Node recGrandParent = recParent.leftParent; - - reverseReassortmentSpan = arg.getNodeHeight(recParent) - arg.getNodeHeight(recChild); - reverseBifurcationSpan = arg.getNodeHeight(recGrandParent) - arg.getNodeHeight(recChild); - if (arg.isRoot(recParent)) { // This case should never happen as double links - arg.setRoot(recChild); // to root can not be added or removed. - } else { - //Node recGrandParent = recParent1.leftParent; // And currently recParent must be a bifurcatio -// System.err.println("recGrand ="+recGrandParent.number); - arg.doubleRemoveChild(recGrandParent, recParent); - arg.doubleRemoveChild(recNode, recChild); - if (recGrandParent.bifurcation) - arg.singleAddChild(recGrandParent, recChild); - else - arg.doubleAddChild(recGrandParent, recChild); - } - doneSomething = true; - // There are not left/right choices to be made for doubly linked removals. - // End doubly linked. - } else { // Two different parents. - Node recParent1 = recNode.leftParent; - Node recParent2 = recNode.rightParent; - if ((!recParent1.bifurcation && !recParent2.bifurcation) || - (!recParent1.bifurcation && recParent2.isRoot()) || - (!recParent2.bifurcation && recParent1.isRoot())) { - - arg.endTreeEdit(); - -// try { -// arg.checkTreeIsValid(); -// } catch (MutableTree.InvalidTreeException ite) { -// throw new RuntimeException(ite.toString() + "\n" + arg.toString() -// + "\n" + Tree.Utils.uniqueNewick(arg, arg.getRoot())); -// } - throw new ARGOperatorFailedException("Not reversible deletion."); - } - if (!recParent1.bifurcation || recParent1.isRoot()) { // One orientation is valid - recParent1 = recNode.rightParent; - recParent2 = recNode.leftParent; - } else if (recParent2.bifurcation && !recParent2.isRoot()) { // Both orientations are valid - if (MathUtils.nextDouble() < 0.5) { // choose equally likely - recParent1 = recNode.rightParent; - recParent2 = recNode.leftParent; - } - logq += Math.log(2); - } -// System.err.println("recNode ="+recNode.number); -// System.err.println("recParent1 ="+recParent1.number); -// System.err.println("recParent2 ="+recParent2.number); - - Node recGrandParent = recParent1.leftParent; // And currently recParent must be a bifurcatio -// System.err.println("recGrand ="+recGrandParent.number); - //Node recChild = recNode.leftChild; - Node otherChild = recParent1.leftChild; - if (otherChild == recNode) - otherChild = recParent1.rightChild; -// System.err.println("recChild ="+recChild.number); -// System.err.println("otherChild ="+otherChild.number); - reverseReassortmentSpan = Math.min(arg.getNodeHeight(recParent1), arg.getNodeHeight(recParent2)) - - arg.getNodeHeight(recChild); - reverseBifurcationSpan = arg.getNodeHeight(recGrandParent) - - Math.max(arg.getNodeHeight(recChild), arg.getNodeHeight(otherChild)); - if (recGrandParent.bifurcation) - arg.singleRemoveChild(recGrandParent, recParent1); - else - arg.doubleRemoveChild(recGrandParent, recParent1); - - arg.singleRemoveChild(recParent1, otherChild); - if (recParent2.bifurcation) - arg.singleRemoveChild(recParent2, recNode); - else - arg.doubleRemoveChild(recParent2, recNode); - arg.doubleRemoveChild(recNode, recChild); - if (otherChild != recChild) { - if (recGrandParent.bifurcation) - arg.singleAddChild(recGrandParent, otherChild); - else - arg.doubleAddChild(recGrandParent, otherChild); - if (recParent2.bifurcation) - arg.singleAddChild(recParent2, recChild); - else - arg.doubleAddChild(recParent2, recChild); - } else { - if (recGrandParent.bifurcation) - arg.singleAddChildWithOneParent(recGrandParent, otherChild); - else - arg.doubleAddChildWithOneParent(recGrandParent, otherChild); - if (recParent2.bifurcation) - arg.singleAddChildWithOneParent(recParent2, recChild); - else - arg.doubleAddChildWithOneParent(recParent2, recChild); - } -// System.err.println("Sanity check in Remove Operator"); -// sanityCheck(); -// System.err.println("End Remove Operator in sanity check"); - doneSomething = true; - // Check for node height troubles - - if ((recChild.getHeight() > recParent2.getHeight()) || - (otherChild.getHeight() > recGrandParent.getHeight())) { - arg.endTreeEdit(); - throw new RuntimeException("How did I get here?"); - } - recParent = recParent1; - } - if (doneSomething) { -// System.err.println("Trying to remove "+recNode.number+" and "+recParent.number); -// - arg.contractARGWithRecombinant(recParent, recNode, - internalNodeParameters, internalAndRootNodeParameters, nodeRates); - } -// System.err.println("End ARG\n"+arg.toGraphString()); - - - arg.pushTreeSizeChangedEvent(); - arg.endTreeEdit(); -// try { -// arg.checkTreeIsValid(); -// } catch (MutableTree.InvalidTreeException ite) { -// throw new RuntimeException(ite.toString() + "\n" + arg.toString() -// + "\n" + Tree.Utils.uniqueNewick(arg, arg.getRoot())); -// } - -// System.err.println("Checking remove validity."); - - // todo -- check all ARGTree.Roots -// if (!arg.validRoot()) -// throw new OperatorFailedException("Roots are invalid"); - -// logq -= Math.log(reverseBifurcationSpan) + Math.log(reverseReassortmentSpan); // TODO removed? because of prior ratio - logq -= Math.log(arg.getNodeCount() + arg.getReassortmentNodeCount() - 1); // findPotentialRessortmentNodes() - logq -= Math.log(this.findPotentialAttachmentSisters(recChild, - arg.getNodeHeight(recChild), null)); -// System.err.println(drawRandomPartitioning(null)); - // logq -= drawRandomPartitioning(null); - -// System.err.println("End remove ARG operation."); - - - int nodes = arg.getInternalNodeCount() - 1; - logq += lnGamma(nodes) - lnGamma(nodes + 2); // TODO move into prior - - logq += 3 * Math.log(2); - - logq = 0; - - return logq; // 1 / total potentials * 1 / 2 (if valid) * length1 * length2 * attachmentSisters - } - - private static double lnGamma(double x) { - if (x == 1 || x == 2) - return 0.0; - return GammaFunction.logGamma(x); - } - - private void checkAllHeights() { - int len = arg.getInternalNodeCount(); - System.err.println("# internal nodes = " + len); - int n = internalNodeParameters.getParameterCount(); - System.err.println("VSCP (" + n + ")"); - for (int i = 0; i < n; i++) { - System.err.println(internalNodeParameters.getParameterValue(i)); - } - n = arg.getInternalNodeCount(); - System.err.println("Checking all internal nodes (" + n + ") via tree:"); - for (int i = 0; i < n; i++) { - NodeRef node = arg.getInternalNode(i); - System.err.print(TreeUtils.uniqueNewick(arg, node) + " "); - System.err.println(((Node) node).getHeight()); - } - } - - /*private void checkAllPartitionLabels() { - int len = arg.getExternalNodeCount(); - System.err.println("Tip Partitions:"); - for(int i=0; i=0; j=partSet.nextSetBit(j+1)) { - System.err.print(" "+j); - } - System.err.println(); - } - }*/ - -/* private ArrayList getPotentialTipsToMerge() { - ArrayList potentials = new ArrayList(); - int len = arg.getExternalNodeCount(); - for(int i=0; i getSameTaxonTips(Node asMe) { - ArrayList potentials = new ArrayList(); - int len = arg.getExternalNodeCount(); - Taxon same = asMe.taxon; - for(int i=0; i getPotentialTipsToSplit() { - ArrayList potentials = new ArrayList(); - int len = arg.getExternalNodeCount(); - for(int i=0; i 1 ) // can be split - potentials.add(nr); - } - return potentials; - }*/ - - /*;private int drawOnePartition(BitSet partitionSet) { - int draw = MathUtils.nextInt(partitionSet.cardinality()); - // System.err.println("draw = "+draw); - int result = partitionSet.nextSetBit(0); - for (int i = 0; i < draw; i++) - result = partitionSet.nextSetBit(result + 1); - return result; - }*/ - -// private BitSet bsTransportor = null; - /* - private ArrayList getPotentialSubtreesToSplit() { - ArrayList potentials = new ArrayList(); - // Start with all possible nodes except the root - BitSet bsTmp = null; - int len = arg.getNodeCount(); - for(int i=0; i allTips = arg.getDescendantTipNodes(nr); - int n = allTips.size(); - boolean valid = true; - for(int j=0; valid && j1) ) - potentials.add(nr); - } - } - bsTransportor = bsTmp; - return potentials; - } - */ -/* private int countPotentialSubtreesToSplit() { -// ArrayList potentials = new ArrayList(); - int count = 0; - // Start with all possible nodes except the root - BitSet bsTmp = null; - int len = arg.getNodeCount(); - for(int i=0; i allTips = arg.getDescendantTipNodes(nr); - int n = allTips.size(); - boolean valid = true; - for(int j=0; valid && j1) ) - //potentials.add(nr); - count++; - } - } - bsTransportor = bsTmp; - //return potentials; - return count; - }*/ - -// private ArrayList getPotentialReattachments(double min) { -// ArrayList potentials = new ArrayList(); -// int len = arg.getNodeCount(); -// for(int i=0; i min) ) { -// // Do not reroot and reattach only above current height -// -// potentials.add(nr); -// } -// } -// return potentials; -// } - - private int findPotentialAttachmentSisters(NodeRef rec, double min, ArrayList list) { - int count = 0; - int len = arg.getNodeCount(); - for (int i = 0; i < len; i++) { - Node nr = (Node) arg.getNode(i); - if (!nr.isRoot()) { - if (arg.getNodeHeight(nr.leftParent) > min) { - // can add node somewhere between min and nr.parent - if (list != null) - list.add(nr); - count++; - } - if (nr.isReassortment() && arg.getNodeHeight(nr.rightParent) > min) { - if (list != null) - list.add(nr); - count++; - } - } - } - return count; - } - - private double drawRandomPartitioning(Parameter partitioning) { - double logq = 0; - int len = arg.getNumberOfPartitions(); - if (len == 2) { - boolean first = MathUtils.nextBoolean(); - if (partitioning != null) { - if (first) - partitioning.setParameterValueQuietly(0, 1.0); - else - partitioning.setParameterValueQuietly(1, 1.0); - } - return Math.log(2); - } - if (isRecombination) { - logq += drawRandomRecombination(partitioning); - } else { - logq += drawRandomReassortment(partitioning); - } - return logq; - } - - - private double drawRandomReassortment(Parameter partitioning) { - int len = arg.getNumberOfPartitions(); - double logq = 0; - if (MathUtils.nextDouble() < singlePartitionProbability) { - if (partitioning != null) - partitioning.setParameterValueQuietly(MathUtils.nextInt(len), 1.0); - return Math.log(len); - } - int[] permutation = MathUtils.permuted(len); - int cut = MathUtils.nextInt(len - 1); - for (int i = 0; i < len; i++) { - logq += Math.log(i + 1); - if (i > cut && partitioning != null) - partitioning.setParameterValueQuietly(permutation[i], 1.0); - } - logq += Math.log(len - 1); - return logq; - } - - private double drawRandomRecombination(Parameter partitioning) { - int len = arg.getNumberOfPartitions(); - double logq = 0; - double leftValue = MathUtils.nextInt(2); - double rightValue = 1.0 - leftValue; - logq += Math.log(2); - if (partitioning != null) { - int cut = MathUtils.nextInt(len - 1); - for (int i = 0; i <= cut; i++) - partitioning.setParameterValueQuietly(i, leftValue); - for (int i = cut + 1; i < len; i++) - partitioning.setParameterValueQuietly(i, rightValue); - } - logq += Math.log(len - 1); - return logq; - } - - - private double AddOperation() throws ARGOperatorFailedException { - double logq = 0; - -// System.err.println("Starting add ARG operation. ... "+arg.getReassortmentNodeCount()); - // Draw potential places to add a reassortment node - - ArrayList potentialNodes = new ArrayList(); - int totalPotentials = findPotentialReassortmentNodes(potentialNodes); - if (totalPotentials == 0) { - System.err.println("Should never get here AA"); - System.exit(-1); - throw new ARGOperatorFailedException("No more nodes to recombine."); - } - Node recNode = (Node) potentialNodes.get(MathUtils - .nextInt(totalPotentials)); - Node recParentL = recNode.leftParent; - Node recParentR = recNode.rightParent; - Node recParent = recParentL; - if ((recParentL != recParentR) && MathUtils.nextDouble() > 0.5) - recParent = recParentR; - - logq += Math.log(totalPotentials); - - double minHeight = arg.getNodeHeight(recNode); // Attachment must occur - // previous to this time - - ArrayList attachments = new ArrayList(); - int totalAttachments = findPotentialAttachmentSisters(recNode, - minHeight, attachments); - if (totalAttachments == 0) { -// System.err.println("Should never get here AB"); -// System.exit(-1); - - throw new ARGOperatorFailedException("no more attachment points for this recomb"); - } - Node sisNode = (Node) attachments.get(MathUtils - .nextInt(totalAttachments)); - Node sisParentL = sisNode.leftParent; - Node sisParentR = sisNode.rightParent; - Node sisParent = sisParentL; - if (sisParentL != sisParentR) { - if (arg.getNodeHeight(sisParentL) <= minHeight) - sisParent = sisParentR; - else if (arg.getNodeHeight(sisParentR) > minHeight - && MathUtils.nextDouble() > 0.5) - sisParent = sisParentR; - } - - logq += Math.log(totalAttachments); - - Node newBifurcation = arg.new Node(); - Node newReassortment = arg.new Node(); - newReassortment.bifurcation = false; - double sisHeight = sisNode.getHeight(); - if (sisHeight < minHeight) { - sisHeight = minHeight; - } - double spHeight = arg.getNodeHeight(sisParent); - double totalLength = spHeight - sisHeight; - - double newLength = sisHeight + MathUtils.nextDouble() * totalLength; - - logq -= Math.log(totalLength); // prior ratio - - newBifurcation.heightParameter = new Parameter.Default(newLength); - newBifurcation.setupHeightBounds(); - - logq += Math.log(totalLength); // Uniform[spHeight, sisHeight] - - double topHeight = newLength; - double recParentHeight = arg.getNodeHeight(recParent); - if (topHeight > recParentHeight) - topHeight = recParentHeight; - double recHeight = arg.getNodeHeight(recNode); - totalLength = topHeight - recHeight; - newLength = recHeight + MathUtils.nextDouble() * totalLength; - - logq -= Math.log(totalLength); // prior ratio - - newReassortment.heightParameter = new Parameter.Default(newLength); - newReassortment.setupHeightBounds(); - logq += Math.log(totalLength); // Uniform[bifurcationHeight,recNodeHeight] - - arg.beginTreeEdit(); - if (sisParent.bifurcation) - arg.singleRemoveChild(sisParent, sisNode); - else - arg.doubleRemoveChild(sisParent, sisNode); - if (sisNode != recNode) { - if (recParent.bifurcation) - arg.singleRemoveChild(recParent, recNode); - else - arg.doubleRemoveChild(recParent, recNode); - } - if (sisParent.bifurcation) - arg.singleAddChild(sisParent, newBifurcation); - else - arg.doubleAddChild(sisParent, newBifurcation); - if (sisNode != recNode) - arg.singleAddChild(newBifurcation, sisNode); - arg.doubleAddChild(newReassortment, recNode); - -/* BitSet bitLeft = new BitSet(); - BitSet bitRight = new BitSet(); - if (MathUtils.nextDouble() < 0.5) { - bitLeft.set(0); - bitRight.set(1); - } else { - bitLeft.set(1); - bitRight.set(0); - } - logq += Math.log(2.0);*/ - Parameter partitioning = new Parameter.Default(arg.getNumberOfPartitions()); - -// logq += drawRandomPartitioning(partitioning); // TODO add back in - - /* System.err.print("p: "); - double[] v = partitioning.getParameterValues(); - for (double d : v) - System.err.print(d+" "); - System.err.println("");*/ - - - if (sisNode != recNode) { - arg.addChildAsRecombinant(newBifurcation, recParent, - newReassortment, partitioning); - } else { - arg.addChildAsRecombinant(newBifurcation, newBifurcation, - newReassortment, partitioning); - } - - /* if (sisNode != recNode) { - arg.addChildAsRecombinant(newBifurcation, recParent, - newReassortment, bitLeft, bitRight); - } else { - arg.addChildAsRecombinant(newBifurcation, newBifurcation, - newReassortment, bitLeft, bitRight); - }*/ - arg.expandARGWithRecombinant(newBifurcation, newReassortment, - internalNodeParameters, - internalAndRootNodeParameters, - nodeRates); - // arg.addNewHeightParameter(newReassortment.heightParameter,internalNodeParameters); - // arg.expandNodesWithRecombinant(arg.getRoot(), recNR); - // arg.expandNodesWithSubtree(arg.getRoot(), newSubtree); - // arg.reconstructTrees(); -// -// System.err.println("End ARG\n" + arg.toGraphString()); System.err.println("recNode = " + recNode.number); -// System.err.println("recParent = " + recParent.number); -// System.err.println("sisNode = " + sisNode.number); -// System.err.println("sisParent = " + sisParent.number); - //System.exit(-1); -// ARGTree tree = new ARGTree(arg); - // System.err.println("Reassortment nodes = - // "+arg.getReassortmentNodeCount()); - // //System.exit(-1); - // //System.err.println("ARGTree = "+Tree.Utils.uniqueNewick(tree, - // tree.getRoot())); -// tree = new ARGTree(arg, 0); -// System.err.println("Part 0 = " + tree.toString()); -// tree = new ARGTree(arg, 1); -// System.err.println("Part 1 = " + tree.toString()); - // //if( recNode == sisNode) - //System.exit(-1); -// System.err.println("Sanity check in Add Operation"); -// sanityCheck(); -// System.err.println("End Add Operator sanity check"); - - arg.pushTreeSizeChangedEvent(); - - arg.endTreeEdit(); - -// try { -// arg.checkTreeIsValid(); -// } catch (MutableTree.InvalidTreeException ite) { -// throw new RuntimeException(ite.toString() + "\n" + arg.toString() -// + "\n" + Tree.Utils.uniqueNewick(arg, arg.getRoot())); -// } - -// System.err.println("Checking add validity."); - // todo -- check all ARGTree.Roots -// if (!arg.validRoot()) -// throw new OperatorFailedException("Roots are invalid"); - - // System.err.println("Made it thru once!"); - - // System.exit(-1); - // times++; - // System.err.println("Adds = "+times); - // if( times >= 4 ) - // throw new OperatorFailedException("Do many tries!"); - // System.err.println("Add a recomb node."); -// int cnt = arg.getReassortmentNodeCount(); -// if (cnt > 20) -// throw new OperatorFailedException("No more than X reassortments"); - - logq -= Math.log(findCurrentReassortmentNodes(null)); - if (!(recNode.leftParent.isBifurcation() && recNode.rightParent.isRoot()) && - !(recNode.rightParent.isBifurcation() && recNode.leftParent.isRoot())) - logq -= Math.log(2.0); - -// System.err.println("End add ARG operation."); - - int nodes = arg.getInternalNodeCount() - 1; - logq += lnGamma(nodes) - lnGamma(nodes - 2); // TODO move into prior - - logq = 0; - return logq; - } - -// if( !recParent1.bifurcation || recParent1.isRoot() ) { // One orientation is valid - - - public void sanityCheck() { - int len = arg.getNodeCount(); - for (int i = 0; i < len; i++) { - Node node = (Node) arg.getNode(i); - if (node.bifurcation) { - boolean equalChild = (node.leftChild == node.rightChild); - if ((equalChild && node.leftChild != null)) { - if (!node.leftChild.bifurcation && ((node.leftChild).leftParent == node)) - ; - else { - System.err.println("Node " + (i + 1) + " is insane."); - System.err.println(arg.toGraphString()); - System.exit(-1); - } - } - } else { - if ((node.leftChild != node.rightChild)) { - System.err.println("Node " + (i + 1) + " is insane."); - System.err.println(arg.toGraphString()); - System.exit(-1); - } - } - if (!node.isRoot()) { - double d; - d = node.getHeight(); - } - } - } - - private int times = 0; - - private double getDelta() { - if (!gaussian) { - return (MathUtils.nextDouble() * size) - (size / 2.0); - } else { - return MathUtils.nextGaussian() * size; - } - } - - private int intersectingEdges(Tree tree, NodeRef node, double height, ArrayList directChildren) { - - NodeRef parent = arg.getParent(node); - - if (arg.getNodeHeight(parent) < height) return 0; - - if (arg.getNodeHeight(node) < height) { - if (directChildren != null) directChildren.add(node); - return 1; - } - - int count = 0; - for (int i = 0; i < arg.getChildCount(node); i++) { - count += intersectingEdges(tree, arg.getChild(node, i), height, directChildren); - } - return count; - } - - /** - * @return the other child of the given parent. - */ - private NodeRef getOtherChild(Tree tree, NodeRef parent, NodeRef child) { - - if (arg.getChild(parent, 0) == child) { - return arg.getChild(parent, 1); - } else { - return arg.getChild(parent, 0); - } - } - - public double getSize() { - return size; - } - - public void setSize(double size) { - this.size = size; - } - - @Override - protected double getAdaptableParameterValue() { - return Math.log(getSize()); - } - - public void setAdaptableParameterValue(double value) { - setSize(Math.exp(value)); - } - - public double getRawParameter() { - return getSize(); - } - - public String getAdaptableParameterName() { - return "size"; - } - - public String getOperatorName() { - return SUBTREE_SLIDE; - } - - public static dr.xml.XMLObjectParser PARSER = new dr.xml.AbstractXMLObjectParser() { - - public String getParserName() { - return SUBTREE_SLIDE; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - boolean swapRates = false; - boolean swapTraits = false; - - double singlePartitionProbability = 0.0; - boolean isRecombination = false; - -// int mode = AdaptableMCMCOperator.DEFAULT; -// if (xo.hasAttribute(AUTO_OPTIMIZE)) { -// if (xo.getBooleanAttribute(AUTO_OPTIMIZE)) { -// mode = AdaptableMCMCOperator.ADAPTATION_ON; -// } else { -// mode = AdaptableMCMCOperator.ADAPTATION_OFF; -// } -// } - - AdaptationMode mode = AdaptationMode.parseMode(xo); - - if (xo.hasAttribute(SINGLE_PARTITION)) { - singlePartitionProbability = xo.getDoubleAttribute(SINGLE_PARTITION); - } - - if (xo.hasAttribute(IS_RECOMBINATION)) { - isRecombination = xo.getBooleanAttribute(IS_RECOMBINATION); - - } - - if (xo.hasAttribute(SWAP_RATES)) { - swapRates = xo.getBooleanAttribute(SWAP_RATES); - } - if (xo.hasAttribute(SWAP_TRAITS)) { - swapTraits = xo.getBooleanAttribute(SWAP_TRAITS); - } - Object obj = xo.getChild(ARGModel.class); - //TreeModel tmp = (TreeModel)xo.getChild(TreeModel.class); - ARGModel treeModel = null; - //if( (tmp.TREE_MODEL).compareTo(VariableSizeTreeModel.TREE_MODEL) == 0) { - if (obj instanceof ARGModel) { - //System.err.println("Found VSTM"); - treeModel = (ARGModel) obj; - } else { - System.err.println("Must specify a variable size tree model to use the AddRemoveSubtreeOperators"); - System.exit(-1); - } - - // bug, getChild(String) returns an xmlObject; not in XML rules - CompoundParameter parameter1 = null; //(CompoundParameter) xo.getChild(JUST_INTERNAL); - CompoundParameter parameter2 = null; //CompoundParameter) xo.getChild(INTERNAL_AND_ROOT); - CompoundParameter parameter3 = null; //(CompoundParameter) xo.getChild(NODE_RATES); - - int weight = xo.getIntegerAttribute("weight"); -// int maxTips = xo.getIntegerAttribute(MAX_VALUE); - double size = xo.getDoubleAttribute("size"); - boolean gaussian = xo.getBooleanAttribute("gaussian"); - return new ObsoleteARGAddRemoveEventOperator(treeModel, weight, size, gaussian, swapRates, swapTraits, - mode, parameter1, parameter2, parameter3, singlePartitionProbability, isRecombination); - } - - public String getParserDescription() { - return "An operator that slides a subarg."; - } - - public Class getReturnType() { - return ObsoleteARGAddRemoveEventOperator.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private final XMLSyntaxRule[] rules = { - AttributeRule.newIntegerRule("weight"), -// AttributeRule.newIntegerRule(MAX_VALUE), - AttributeRule.newDoubleRule("size"), - AttributeRule.newBooleanRule("gaussian"), - AttributeRule.newBooleanRule(SWAP_RATES, true), - AttributeRule.newBooleanRule(SWAP_TRAITS, true), - AttributeRule.newBooleanRule(AUTO_OPTIMIZE, true), - new ElementRule(ARGModel.class)//, -// new ElementRule(Parameter.class) - }; - }; - -} diff --git a/src/dr/evomodel/arg/operators/ObsoleteARGNewEventOperator.java b/src/dr/evomodel/arg/operators/ObsoleteARGNewEventOperator.java deleted file mode 100644 index e31ba723de..0000000000 --- a/src/dr/evomodel/arg/operators/ObsoleteARGNewEventOperator.java +++ /dev/null @@ -1,744 +0,0 @@ -/* - * ObsoleteARGNewEventOperator.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -/* - * AddRemoveSubtreeOperator.java - * - * (c) 2002-2005 BEAST Development Core Team - * - * This package may be distributed under the - * Lesser Gnu Public Licence (LGPL) - */ -package dr.evomodel.arg.operators; - -import dr.evolution.tree.NodeRef; -import dr.evolution.tree.TreeUtils; -import dr.evomodel.arg.ARGModel; -import dr.evomodel.arg.ARGModel.Node; -import dr.evomodelxml.tree.TreeModelParser; -import dr.inference.model.CompoundParameter; -import dr.inference.model.Parameter; -import dr.inference.operators.*; -import dr.math.MathUtils; -import dr.math.functionEval.GammaFunction; -import dr.xml.*; - -import java.util.ArrayList; - -/** - * Implements the subtree slide move. - * - * @author Marc Suchard - */ - -public class ObsoleteARGNewEventOperator extends AbstractAdaptableOperator { -// SimpleMCMCOperator implements AdaptableMCMCOperator { - - public static final String SUBTREE_SLIDE = "newARGEvent"; - public static final String SWAP_RATES = "swapRates"; - public static final String SWAP_TRAITS = "swapTraits"; - public static final String MAX_VALUE = "maxTips"; - public static final String SINGLE_PARTITION = "singlePartitionProbability"; - public static final String IS_RECOMBINATION = "isRecombination"; - - public static final String JUST_INTERNAL = "justInternalNodes"; - public static final String INTERNAL_AND_ROOT = "internalAndRootNodes"; - public static final String NODE_RATES = TreeModelParser.NODE_RATES; - - private ARGModel arg = null; - private double size = 1.0; - private boolean gaussian = false; - private double singlePartitionProbability = 0.0; - private boolean isRecombination = false; - // private boolean swapRates; - // private boolean swapTraits; - // private int mode = AdaptableMCMCOperator.DEFAULT; - private CompoundParameter internalNodeParameters; - private CompoundParameter internalAndRootNodeParameters; - private CompoundParameter nodeRates; -// private int maxTips = 1; - - public ObsoleteARGNewEventOperator(ARGModel arg, int weight, double size, boolean gaussian, - boolean swapRates, boolean swapTraits, AdaptationMode mode, - CompoundParameter param1, - CompoundParameter param2, - CompoundParameter param3, - double singlePartitionProbability, boolean isRecombination) { - super(mode); - this.arg = arg; - setWeight(weight); -// this.maxTips = maxTips; - this.size = size; - this.gaussian = gaussian; -// this.swapRates = swapRates; -// this.swapTraits = swapTraits; - this.internalNodeParameters = param1; - this.internalAndRootNodeParameters = param2; - this.nodeRates = param3; - this.singlePartitionProbability = singlePartitionProbability; - this.isRecombination = isRecombination; - -// this.mode = mode; - } - - - /** - * Do a add/remove reassortment node operation - * - * @return the log-transformed hastings ratio - */ - public double doOperation() { -// System.err.println("Starting AddRemove Operation"); - - double logq = 0; - try { - if (MathUtils.nextDouble() < 0.5) - logq = AddOperation(); - else - logq = RemoveOperation(); - } catch (Exception ofe) { -// System.err.println(ofe); - if (ofe.getMessage().compareTo("No reassortment nodes to remove.") != 0) { - System.err.println("Catch: " + ofe.getMessage()); - System.exit(-1); - } - } -// if (arg.isBifurcationDoublyLinked(arg.getRoot())) -// throw new OperatorFailedException("trouble with double-rooted root"); -// System.err.println("logq = "+logq); - return logq; - } - - private int findPotentialNodesToRemove(ArrayList list) { - int count = 0; - int n = arg.getNodeCount(); -// int max = arg.getReassortmentNodeCount(); - Node root = (Node) arg.getRoot(); - for (int i = 0; i < n; i++) { - Node node = (Node) arg.getNode(i); - if (node.isReassortment() - && ((node.leftParent != root && node.leftParent.isBifurcation()) || - (node.rightParent != root && node.rightParent.isBifurcation())) -// && !( -// (node.leftParent == root && node.rightParent.isReassortment()) || -// (node.rightParent== root && node.leftParent.isReassortment())) -// && !(node.leftParent == root && node.rightParent == root) -// && (node.leftParent.isBifurcation() || node.rightParent.isBifurcation()) - ) { - if (list != null) - list.add(node); - count++; - } - } -// System.err.printf("max = %d, available = %d\n",max,count); - return count; - } - - private double RemoveOperation() throws ARGOperatorFailedException { - double logq = 0; - -// System.err.println("Starting remove ARG operation."); -// System.err.println("Before remove:\n"+arg.toGraphString()); - - // 1. Draw reassortment node uniform randomly - - ArrayList potentialNodes = new ArrayList(); - - int totalPotentials = findPotentialNodesToRemove(potentialNodes); - if (totalPotentials == 0) - throw new ARGOperatorFailedException("No reassortment nodes to remove."); -// System.err.println("potentials exist!"); - Node recNode = (Node) potentialNodes.get(MathUtils.nextInt(totalPotentials)); -// logq += Math.log(totalPotentials); - - double reverseReassortmentHeight = 0; - double reverseBifurcationHeight = 0; - - double treeHeight = arg.getNodeHeight(arg.getRoot()); - -// System.err.println("RecNode to remove = "+recNode.number); - reverseReassortmentHeight = arg.getNodeHeight(recNode); - - arg.beginTreeEdit(); - boolean doneSomething = false; - Node recParent = recNode.leftParent; - Node recChild = recNode.leftChild; - if (recNode.leftParent == recNode.rightParent) { // Doubly linked. - Node recGrandParent = recParent.leftParent; -// reverseBifurcationHeight = arg.getNodeHeight(recParent); - -// reverseReassortmentSpan = arg.getNodeHeight(recParent) - arg.getNodeHeight(recChild); -// reverseBifurcationSpan = arg.getNodeHeight(recGrandParent) - arg.getNodeHeight(recChild); -// if (arg.isRoot(recParent)) { // This case should never happen as double links -// arg.setRoot(recChild); // to root can not be added or removed. -// System.err.println("doubled link root?"); -// System.exit(-1); -// } else { - //Node recGrandParent = recParent1.leftParent; // And currently recParent must be a bifurcatio - //System.err.println("recGrand ="+recGrandParent.number); - arg.doubleRemoveChild(recGrandParent, recParent); - arg.doubleRemoveChild(recNode, recChild); - if (recGrandParent.bifurcation) - arg.singleAddChild(recGrandParent, recChild); - else - arg.doubleAddChild(recGrandParent, recChild); -// } - doneSomething = true; - // There are not left/right choices to be made for doubly linked removals. - // End doubly linked. - } else { // Two different parents. - Node recParent1 = recNode.leftParent; - Node recParent2 = recNode.rightParent; - if (!recParent1.bifurcation || recParent1.isRoot()) { // One orientation is valid - recParent1 = recNode.rightParent; - recParent2 = recNode.leftParent; - } else if (recParent2.bifurcation && !recParent2.isRoot()) { // Both orientations are valid - if (MathUtils.nextDouble() < 0.5) { // choose equally likely - recParent1 = recNode.rightParent; - recParent2 = recNode.leftParent; - } - logq += Math.log(2); - } - - Node recGrandParent = recParent1.leftParent; // And currently recParent must be a bifurcatio - - Node otherChild = recParent1.leftChild; - if (otherChild == recNode) - otherChild = recParent1.rightChild; - - if (recGrandParent.bifurcation) - arg.singleRemoveChild(recGrandParent, recParent1); - else - arg.doubleRemoveChild(recGrandParent, recParent1); - - arg.singleRemoveChild(recParent1, otherChild); - if (recParent2.bifurcation) - arg.singleRemoveChild(recParent2, recNode); - else - arg.doubleRemoveChild(recParent2, recNode); - arg.doubleRemoveChild(recNode, recChild); - if (otherChild != recChild) { - if (recGrandParent.bifurcation) - arg.singleAddChild(recGrandParent, otherChild); - else - arg.doubleAddChild(recGrandParent, otherChild); - if (recParent2.bifurcation) - arg.singleAddChild(recParent2, recChild); - else - arg.doubleAddChild(recParent2, recChild); - } else { - if (recGrandParent.bifurcation) - arg.singleAddChildWithOneParent(recGrandParent, otherChild); - else - arg.doubleAddChildWithOneParent(recGrandParent, otherChild); - if (recParent2.bifurcation) - arg.singleAddChildWithOneParent(recParent2, recChild); - else - arg.doubleAddChildWithOneParent(recParent2, recChild); - } -// System.err.println("Sanity check in Remove Operator"); -// sanityCheck(); -// System.err.println("End Remove Operator in sanity check"); - doneSomething = true; - - recParent = recParent1; - } - - reverseBifurcationHeight = arg.getNodeHeight(recParent); - - if (doneSomething) { - try { - arg.contractARGWithRecombinant(recParent, recNode, - internalNodeParameters, internalAndRootNodeParameters, nodeRates); - } catch (Exception e) { - System.err.println("here"); - System.err.println(e); - - } - } - - arg.pushTreeSizeChangedEvent(); - arg.endTreeEdit(); -// try { -// arg.checkTreeIsValid(); -// } catch (MutableTree.InvalidTreeException ite) { -// throw new RuntimeException(ite.toString() + "\n" + arg.toString() -// + "\n" + Tree.Utils.uniqueNewick(arg, arg.getRoot())); -// } - -// double d1 = findPotentialAttachmentPoints(reverseBifurcationHeight,null); -// double d2 = findPotentialAttachmentPoints(reverseReassortmentHeight,null); -// System.err.printf("d1 = %5.4f, d2 = %5.4f\n",d1,d2); - -// logq -= Math.log(findPotentialAttachmentPoints(reverseBifurcationHeight,null)); -// logq -= Math.log(findPotentialAttachmentPoints(reverseReassortmentHeight,null)); - -// int nodes = arg.getInternalNodeCount() - 1; -// -// logq += 3*Math.log(2); -// -// logq = 100; - -// System.err.println("logq remove = "+logq); - logq = 0; -// logq -= 10; -// logq += Math.log(totalPotentials); - return logq; // 1 / total potentials * 1 / 2 (if valid) * length1 * length2 * attachmentSisters - } - - private static double lnGamma(double x) { - if (x == 1 || x == 2) - return 0.0; - return GammaFunction.logGamma(x); - } - - private void checkAllHeights() { - int len = arg.getInternalNodeCount(); - System.err.println("# internal nodes = " + len); - int n = internalNodeParameters.getParameterCount(); - System.err.println("VSCP (" + n + ")"); - for (int i = 0; i < n; i++) { - System.err.println(internalNodeParameters.getParameterValue(i)); - } - n = arg.getInternalNodeCount(); - System.err.println("Checking all internal nodes (" + n + ") via tree:"); - for (int i = 0; i < n; i++) { - NodeRef node = arg.getInternalNode(i); - System.err.print(TreeUtils.uniqueNewick(arg, node) + " "); - System.err.println(((Node) node).getHeight()); - } - } - - private int findPotentialAttachmentPoints(double time, ArrayList list) { - int count = 0; - for (int i = 0, n = arg.getNodeCount(); i < n; i++) { - NodeRef nr = arg.getNode(i); - if (!arg.isRoot(nr) && arg.getNodeHeight(nr) < time) { - if (arg.getNodeHeight(arg.getParent(nr, 0)) > time) { - if (list != null) - list.add(nr); - count++; - } - if (arg.isReassortment(nr) && arg.getNodeHeight(arg.getParent(nr, 1)) > time) { - if (list != null) - list.add(nr); - count++; - } - } - } - return count; - } - - private double drawRandomPartitioning(Parameter partitioning) { - double logq = 0; - int len = arg.getNumberOfPartitions(); - if (len == 2) { -// boolean first = MathUtils.nextBoolean(); - if (partitioning != null) { - if (MathUtils.nextBoolean()) - partitioning.setParameterValueQuietly(0, 1.0); - else - partitioning.setParameterValueQuietly(1, 1.0); - } - return Math.log(2); - } - if (isRecombination) { - logq += drawRandomRecombination(partitioning); - } else { - logq += drawRandomReassortment(partitioning); - } - return logq; - } - - - /* Draws a new partitioning. - * With probability singlePartitionProbability, one bit is set; - * otherwise, all bits are selected via a random permutation - * - */ - private double drawRandomReassortment(Parameter partitioning) { - int len = arg.getNumberOfPartitions(); - double logq = 0; - if (MathUtils.nextDouble() < singlePartitionProbability) { - if (partitioning != null) - partitioning.setParameterValueQuietly(MathUtils.nextInt(len), 1.0); - return Math.log(len); - } - int[] permutation = MathUtils.permuted(len); - int cut = MathUtils.nextInt(len - 1); - for (int i = 0; i < len; i++) { - logq += Math.log(i + 1); - if (i > cut && partitioning != null) - partitioning.setParameterValueQuietly(permutation[i], 1.0); - } - logq += Math.log(len - 1); - return logq; - } - - /* Draws a new partitioning. - * A break-pt is drawn uniformly - * - */ - private double drawRandomRecombination(Parameter partitioning) { - int len = arg.getNumberOfPartitions(); - double logq = 0; - double leftValue = MathUtils.nextInt(2); - double rightValue = 1.0 - leftValue; - logq += Math.log(2); - if (partitioning != null) { - int cut = MathUtils.nextInt(len - 1); - for (int i = 0; i <= cut; i++) - partitioning.setParameterValueQuietly(i, leftValue); - for (int i = cut + 1; i < len; i++) - partitioning.setParameterValueQuietly(i, rightValue); - } - logq += Math.log(len - 1); - return logq; - } - - - private double AddOperation() throws ARGOperatorFailedException { - - double logq = 0; - - // Draw attachment point for new bifurcation - -// System.err.println("Starting add operation."); - - ArrayList potentialBifurcationChildren = new ArrayList(); - ArrayList potentialReassortmentChildren = new ArrayList(); - - double treeHeight = arg.getNodeHeight(arg.getRoot()); - - double newBifurcationHeight = treeHeight * MathUtils.nextDouble(); - double newReassortmentHeight = treeHeight * MathUtils.nextDouble(); - if (newReassortmentHeight > newBifurcationHeight) { - double temp = newReassortmentHeight; - newReassortmentHeight = newBifurcationHeight; - newBifurcationHeight = temp; - } - -// logq += 2.0 * Math.log(treeHeight); // Uniform before sorting - - int totalPotentialBifurcationChildren = findPotentialAttachmentPoints( - newBifurcationHeight, potentialBifurcationChildren); - int totalPotentialReassortmentChildren = findPotentialAttachmentPoints( - newReassortmentHeight, potentialReassortmentChildren); - - if (totalPotentialBifurcationChildren == 0 || totalPotentialReassortmentChildren == 0) { - throw new RuntimeException("Unable to find attachment points."); - } - - Node recNode = (Node) potentialReassortmentChildren.get(MathUtils - .nextInt(totalPotentialReassortmentChildren)); -// logq += Math.log(totalPotentialReassortmentChildren); - - Node recParentL = recNode.leftParent; - Node recParentR = recNode.rightParent; - Node recParent = recParentL; - if (recParentL != recParentR) { - if (arg.getNodeHeight(recParentL) < newReassortmentHeight) - recParent = recParentR; - else if (arg.getNodeHeight(recParentR) > newReassortmentHeight - && MathUtils.nextDouble() > 0.5) - recParent = recParentR; - } - - - Node sisNode = (Node) potentialBifurcationChildren.get(MathUtils - .nextInt(totalPotentialBifurcationChildren)); -// logq += Math.log(totalPotentialBifurcationChildren); - - Node sisParentL = sisNode.leftParent; - Node sisParentR = sisNode.rightParent; - Node sisParent = sisParentL; - if (sisParentL != sisParentR) { - if (arg.getNodeHeight(sisParentL) < newBifurcationHeight) - sisParent = sisParentR; - else if (arg.getNodeHeight(sisParentR) > newBifurcationHeight - && MathUtils.nextDouble() > 0.5) - sisParent = sisParentR; - } - - double newBifurcationRateCategory = 1.0; - double newReassortmentRateCategory = 1.0; - - Node newBifurcation = arg.new Node(); - newBifurcation.heightParameter = new Parameter.Default(newBifurcationHeight); - newBifurcation.rateParameter = new Parameter.Default(newBifurcationRateCategory); - newBifurcation.setupHeightBounds(); - - Node newReassortment = arg.new Node(); - newReassortment.bifurcation = false; - newReassortment.heightParameter = new Parameter.Default(newReassortmentHeight); - newReassortment.rateParameter = new Parameter.Default(newReassortmentRateCategory); - newReassortment.setupHeightBounds(); - - arg.beginTreeEdit(); - if (sisParent.bifurcation) - arg.singleRemoveChild(sisParent, sisNode); - else - arg.doubleRemoveChild(sisParent, sisNode); - if (sisNode != recNode) { - if (recParent.bifurcation) - arg.singleRemoveChild(recParent, recNode); - else - arg.doubleRemoveChild(recParent, recNode); - } - if (sisParent.bifurcation) - arg.singleAddChild(sisParent, newBifurcation); - else - arg.doubleAddChild(sisParent, newBifurcation); - if (sisNode != recNode) - arg.singleAddChild(newBifurcation, sisNode); - arg.doubleAddChild(newReassortment, recNode); - - Parameter partitioning = new Parameter.Default(arg.getNumberOfPartitions()); - -// logq += - drawRandomPartitioning(partitioning); -// System.err.println("point 1"); - - if (sisNode != recNode) { - arg.addChildAsRecombinant(newBifurcation, recParent, - newReassortment, partitioning); - } else { - arg.addChildAsRecombinant(newBifurcation, newBifurcation, - newReassortment, partitioning); - } - - arg.expandARGWithRecombinant(newBifurcation, newReassortment, - internalNodeParameters, - internalAndRootNodeParameters, - nodeRates); - -// System.err.println("point 2"); - - arg.pushTreeSizeChangedEvent(); - - arg.endTreeEdit(); -// try { -// arg.checkTreeIsValid(); -// } catch (MutableTree.InvalidTreeException ite) { -// throw new RuntimeException(ite.toString() + "\n" + arg.toString() -// + "\n" + Tree.Utils.uniqueNewick(arg, arg.getRoot())); -// } - -// double d1 = findPotentialNodesToRemove(null); -// System.err.printf("d1 = %5.4f\n",d1); - -// logq -= Math.log(findPotentialNodesToRemove(null)); -// if (!(recNode.leftParent.isBifurcation() && recNode.rightParent.isRoot()) && -// !(recNode.rightParent.isBifurcation() && recNode.leftParent.isRoot())) -// logq -= Math.log(2.0); - -// System.err.println("End add ARG operation."); - -// int nodes = arg.getInternalNodeCount() - 1; - -// -/* int i = findPotentialNodesToRemove(null); - if (i==0) { - System.err.println("why can't i remove this one?"); - System.err.println("graph:"+arg.toGraphString()); - System.exit(1); - return Double.NEGATIVE_INFINITY ; - }*/ - logq = 0; -// logq -= Math.log(findPotentialNodesToRemove(null)); -// System.err.println("logq add = "+logq); -// System.err.println("After add:\n"+arg.toGraphString()); - return logq; - } - -// if( !recParent1.bifurcation || recParent1.isRoot() ) { // One orientation is valid - - - public void sanityCheck() { - int len = arg.getNodeCount(); - for (int i = 0; i < len; i++) { - Node node = (Node) arg.getNode(i); - if (node.bifurcation) { - boolean equalChild = (node.leftChild == node.rightChild); - if ((equalChild && node.leftChild != null)) { - if (!node.leftChild.bifurcation && ((node.leftChild).leftParent == node)) - ; - else { - System.err.println("Node " + (i + 1) + " is insane."); - System.err.println(arg.toGraphString()); - System.exit(-1); - } - } - } else { - if ((node.leftChild != node.rightChild)) { - System.err.println("Node " + (i + 1) + " is insane."); - System.err.println(arg.toGraphString()); - System.exit(-1); - } - } - if (!node.isRoot()) { - double d; - d = node.getHeight(); - } - } - } - - private int times = 0; - - private double getDelta() { - if (!gaussian) { - return (MathUtils.nextDouble() * size) - (size / 2.0); - } else { - return MathUtils.nextGaussian() * size; - } - } - - - public double getSize() { - return size; - } - - public void setSize(double size) { - this.size = size; - } - - @Override - protected double getAdaptableParameterValue() { - return Math.log(getSize()); - } - - public void setAdaptableParameterValue(double value) { - setSize(Math.exp(value)); - } - - public double getRawParameter() { - return getSize(); - } - -// public int getMode() { -// return mode; -// } - - public String getAdaptableParameterName() { - return "size"; - } - - public String getOperatorName() { - return SUBTREE_SLIDE; - } - - public static dr.xml.XMLObjectParser PARSER = new dr.xml.AbstractXMLObjectParser() { - - public String getParserName() { - return SUBTREE_SLIDE; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - boolean swapRates = false; - boolean swapTraits = false; - - double singlePartitionProbability = 0.0; - boolean isRecombination = false; - - AdaptationMode mode = AdaptationMode.parseMode(xo); - -// int mode = AdaptableMCMCOperator.DEFAULT; -// if (xo.hasAttribute(AUTO_OPTIMIZE)) { -// if (xo.getBooleanAttribute(AUTO_OPTIMIZE)) { -// mode = AdaptableMCMCOperator.ADAPTATION_ON; -// } else { -// mode = AdaptableMCMCOperator.ADAPTATION_OFF; -// } -// } - - if (xo.hasAttribute(SINGLE_PARTITION)) { - singlePartitionProbability = xo.getDoubleAttribute(SINGLE_PARTITION); - } - - if (xo.hasAttribute(IS_RECOMBINATION)) { - isRecombination = xo.getBooleanAttribute(IS_RECOMBINATION); - - } - - if (xo.hasAttribute(SWAP_RATES)) { - swapRates = xo.getBooleanAttribute(SWAP_RATES); - } - if (xo.hasAttribute(SWAP_TRAITS)) { - swapTraits = xo.getBooleanAttribute(SWAP_TRAITS); - } - Object obj = xo.getChild(ARGModel.class); - //TreeModel tmp = (TreeModel)xo.getChild(TreeModel.class); - ARGModel treeModel = null; - //if( (tmp.TREE_MODEL).compareTo(VariableSizeTreeModel.TREE_MODEL) == 0) { - if (obj instanceof ARGModel) { - //System.err.println("Found VSTM"); - treeModel = (ARGModel) obj; - } else { - System.err.println("Must specify a variable size tree model to use the AddRemoveSubtreeOperators"); - System.exit(-1); - } - - // bug, getChild(String) returns an xmlObject; not in XML rules - CompoundParameter parameter1 = null; //(CompoundParameter) xo.getChild(JUST_INTERNAL); - CompoundParameter parameter2 = null; //CompoundParameter) xo.getChild(INTERNAL_AND_ROOT); - CompoundParameter parameter3 = null; //(CompoundParameter) xo.getChild(NODE_RATES); - - int weight = xo.getIntegerAttribute("weight"); -// int maxTips = xo.getIntegerAttribute(MAX_VALUE); - double size = xo.getDoubleAttribute("size"); - boolean gaussian = xo.getBooleanAttribute("gaussian"); - return new ObsoleteARGNewEventOperator(treeModel, weight, size, gaussian, swapRates, swapTraits, - mode, parameter1, parameter2, parameter3, singlePartitionProbability, isRecombination); - } - - public String getParserDescription() { - return "An operator that slides a subarg."; - } - - public Class getReturnType() { - return ObsoleteARGAddRemoveEventOperator.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private final XMLSyntaxRule[] rules = { - AttributeRule.newIntegerRule("weight"), -// AttributeRule.newIntegerRule(MAX_VALUE), - AttributeRule.newDoubleRule("size"), - AttributeRule.newBooleanRule("gaussian"), - AttributeRule.newBooleanRule(SWAP_RATES, true), - AttributeRule.newBooleanRule(SWAP_TRAITS, true), - AttributeRule.newBooleanRule(AUTO_OPTIMIZE, true), - new ElementRule(ARGModel.class)//, -// new ElementRule(Parameter.class) - }; - }; - -} diff --git a/src/dr/evomodel/arg/operators/SlidingPatternsOperator.java b/src/dr/evomodel/arg/operators/SlidingPatternsOperator.java deleted file mode 100644 index 9a52118884..0000000000 --- a/src/dr/evomodel/arg/operators/SlidingPatternsOperator.java +++ /dev/null @@ -1,256 +0,0 @@ -/* - * SlidingPatternsOperator.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.arg.operators; - -import dr.evolution.alignment.SitePatterns; -import dr.inference.model.Parameter; -import dr.inference.model.ParameterParser; -import dr.inference.operators.*; -import dr.math.MathUtils; -import dr.xml.*; - -import java.util.ArrayList; -import java.util.List; - -/** - * Created by IntelliJ IDEA. - * User: msuchard - * Date: Jan 18, 2007 - * Time: 8:01:56 PM - * To change this template use File | Settings | File Templates. - */ -@Deprecated -public class SlidingPatternsOperator extends AbstractAdaptableOperator { -// -// SimpleMCMCOperator implements AdaptableMCMCOperator { - - public static final String WINDOW_SIZE = "windowSize"; - public static final String OPERATOR_NAME = "slidingPatternsOperator"; - public static final String BREAK_POINTS = "breakPoints"; - - public SlidingPatternsOperator(List list, Parameter breakPoints, int windowSize, int weight, AdaptationMode mode) { - super(mode); - this.partitions = list; - this.windowSize = windowSize; -// this.weight = weight; -// this.mode = mode; - this.breakPoints = breakPoints; -// System.err.println("Starting values: "+currentBreakPointsString() ); -// System.exit(-1) ; - } - - - public String currentBreakPointsString() { - StringBuilder sb = new StringBuilder(); - sb.append("["); - boolean first = true; - for (double value : breakPoints.getParameterValues()) { - int pt = (int) value; - if (!first) { - sb.append(","); - first = false; - } - sb.append(pt); - } - sb.append("]"); - return sb.toString(); - - } - - // http://www.google.com/search?client=safari&rls=en&q=The+week+renewal+add+a+friend&ie=UTF-8&oe=UTF-8 - public void addNewSitePatterns(SitePatterns addPatterns) { - // todo need to implement for a variable number of partitions - } - - public String getOperatorName() { - return OPERATOR_NAME; - } - - public double doOperation() { - - // Select boundary to update, 0 => btw partition 0 and 1, 1 => btw partition 1 and 2, etc. - int whichBoundary = MathUtils.nextInt(breakPoints.getDimension()); - - int cBreakPt = (int) breakPoints.getParameterValue(whichBoundary); - SitePatterns left = partitions.get(whichBoundary); - SitePatterns right = partitions.get(whichBoundary + 1); - - - // this is no longer compatible with SitePatterns. It should implement its own instance - throw new UnsupportedOperationException("this function is no longer functioning"); - -// int min = left.getFrom(); -// int max = right.getTo(); -// -// int pBreakPt = min; -// while (pBreakPt <= min || pBreakPt >= max) { // cBreakPt + [windowSize-1, windowSize+1] (and not 0) -// if (MathUtils.nextBoolean()) -// pBreakPt = cBreakPt + MathUtils.nextInt(windowSize) + 1; -// else -// pBreakPt = cBreakPt - MathUtils.nextInt(windowSize) - 1; -// } -// -// return 0; - } - - @Override - protected double getAdaptableParameterValue() { - return Math.log(windowSize); - } - - public void setAdaptableParameterValue(double value) { - windowSize = (int) Math.exp(value); - } - - public double getRawParameter() { - return windowSize; - } - - public String getAdaptableParameterName() { - return "windowSize"; - } - -// public int getMode() { -// return mode; -// } - - public static boolean arePartitionsContiguous(List list) { - // this is no longer compatible with SitePatterns. It should implement its own instance - throw new UnsupportedOperationException("this function is no longer functioning"); - -// int current = -1; -// int index = 0; -// for (SitePatterns patterns : list) { -// int start = patterns.getFrom(); -// int end = patterns.getTo(); -// /* System.err.println(start+" -> "+end+" : "+patterns.getSiteCount()+" "+patterns.getPatternCount()); -// int[] data = patterns.getSitePattern(0); -// System.err.print("Data 0:"); -// for (int i : data) -// System.err.print(" "+i); -// System.err.println("");*/ -//// if (current == -1) -//// current = end; -// if (current != -1 && start != (current + 1)) -//// throw new NonContiguousPartitionsException("Partition #"+0+" does not start contiguously"); -// return false; -// current = end; -// } -// -// return true; - } - - public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { - - public String getParserName() { - return OPERATOR_NAME; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - -// int mode = AdaptableMCMCOperator.DEFAULT; -// if (xo.hasAttribute(AUTO_OPTIMIZE)) { -// if (xo.getBooleanAttribute(AUTO_OPTIMIZE)) { -// mode = AdaptableMCMCOperator.ADAPTATION_ON; -// } else { -// mode = AdaptableMCMCOperator.ADAPTATION_OFF; -// } -// } - - AdaptationMode mode = AdaptationMode.parseMode(xo); - - int weight = xo.getIntegerAttribute(WEIGHT); - int windowSize = xo.getIntegerAttribute(WINDOW_SIZE); - - List list = new ArrayList(); - - final int numChild = xo.getChildCount(); - for (int i = 0; i < numChild; i++) { - Object obj = xo.getChild(i); - if (obj instanceof SitePatterns) { -// System.err.println("Found: "+((SitePatterns)obj).getId()) ; - list.add((SitePatterns) obj); - } - } - if (!arePartitionsContiguous(list)) - throw new XMLParseException("Only contiguous partitions are allowed"); - - // Set current breakpoints - int dim = list.size() - 1; - XMLObject cxo = xo.getChild(BREAK_POINTS); - Parameter breakPoints = new Parameter.Default(dim); - - ParameterParser.replaceParameter(cxo, breakPoints); - - // this is no longer compatible with SitePatterns. It should implement its own instance - throw new UnsupportedOperationException("this function is no longer functioning"); - -// breakPoints.setDimension(dim); -// for (int index = 0; index < dim; index++) -// breakPoints.setParameterValueQuietly(index, -// list.get(index + 1).getFrom()); -// -//// Parameter parameter = (Parameter)xo.getChild(Parameter.class); -// -// return new SlidingPatternsOperator(list, breakPoints, windowSize, weight, mode); - } - - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - - public String getParserDescription() { - return "This element returns a sliding window operator on alignment sites."; - } - - public Class getReturnType() { - return MCMCOperator.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private final XMLSyntaxRule[] rules = { - AttributeRule.newIntegerRule(WINDOW_SIZE), - AttributeRule.newIntegerRule(WEIGHT), - AttributeRule.newBooleanRule(AUTO_OPTIMIZE, true), - new ElementRule(BREAK_POINTS, Parameter.class), - new ElementRule(SitePatterns.class, 2, 100) // todo fix hard-coded 100 - }; - - }; - - - private int totalAlignmentLength; - private final List partitions; - private int windowSize = 10; - // private int mode = AdaptableMCMCOperator.DEFAULT; - // private int weight = 1; - private final Parameter breakPoints; -} diff --git a/src/dr/evomodel/arg/parsers.txt b/src/dr/evomodel/arg/parsers.txt deleted file mode 100644 index a4bb45d3d9..0000000000 --- a/src/dr/evomodel/arg/parsers.txt +++ /dev/null @@ -1,24 +0,0 @@ -# A list of additional parsers to be loaded at runtime -# They can be references to an actual XMLObjectParser class or a class which -# has one or more static instances of XMLObjectParser - -# ANCESTRAL RECOMBINATION GRAPHS -dr.evomodel.arg.coalescent.ARGCoalescentLikelihood -dr.evomodel.arg.coalescent.ARGUniformPrior -dr.evomodel.arg.likelihood.ARGLikelihood -dr.evomodel.arg.operators.SlidingPatternsOperator -dr.evomodel.arg.branchratemodel.ARGDiscretizedBranchRates -dr.evomodel.arg.ARGModel -dr.evomodel.arg.UniformPartitionLikelihood -dr.evomodel.arg.operators.ARGSubtreeSlideOperator -dr.evomodel.arg.operators.ARGExchangeOperator -dr.evomodel.arg.operators.ObsoleteARGAddRemoveEventOperator -dr.evomodel.arg.operators.ARGPartitioningOperator -dr.evomodel.arg.operators.ObsoleteARGNewEventOperator -dr.evomodel.arg.operators.ARGAddRemoveEventOperator -dr.evomodel.arg.operators.ARGSwapOperator -dr.evomodel.arg.ARGTreeLogger -dr.evomodel.arg.ARGLogger -dr.evomodel.arg.ARGReassortmentNodeCountStatistic -dr.evomodel.arg.ARGTraceAnalysisParser -dr.evomodel.arg.ARGReassortmentTimingStatistic diff --git a/src/dr/evomodel/epidemiology/casetocase/CaseToCaseTreeLikelihood.java b/src/dr/evomodel/epidemiology/casetocase/CaseToCaseTreeLikelihood.java index b10feb2bab..04d6a1463b 100644 --- a/src/dr/evomodel/epidemiology/casetocase/CaseToCaseTreeLikelihood.java +++ b/src/dr/evomodel/epidemiology/casetocase/CaseToCaseTreeLikelihood.java @@ -41,7 +41,7 @@ import dr.evolution.util.TaxonList; import dr.evomodel.epidemiology.casetocase.periodpriors.AbstractPeriodPriorDistribution; import dr.evomodel.tree.TreeModel; -import dr.oldevomodel.treelikelihood.AbstractTreeLikelihood; +import dr.evomodel.treelikelihood.AbstractTreeLikelihood; import dr.inference.loggers.LogColumn; import dr.inference.loggers.Loggable; import dr.inference.model.Model; @@ -130,10 +130,10 @@ public CaseToCaseTreeLikelihood(String name, PartitionedTreeModel tree, Abstract Parameter maxFirstInfToRoot) { - super(name, caseData, tree); + super(name, tree); - if(stateCount!=treeModel.getExternalNodeCount()){ + if(caseData.getStateCount() != treeModel.getExternalNodeCount()){ throw new RuntimeException("There are duplicate tip outbreak."); } diff --git a/src/dr/evomodel/operators/CategoryOperator.java b/src/dr/evomodel/operators/CategoryOperator.java deleted file mode 100644 index 3d046975cc..0000000000 --- a/src/dr/evomodel/operators/CategoryOperator.java +++ /dev/null @@ -1,166 +0,0 @@ -/* - * CategoryOperator.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.operators; - -import dr.evolution.alignment.Alignment; -import dr.math.MathUtils; -import dr.oldevomodel.sitemodel.CategorySampleModel; -import dr.inference.model.Parameter; -import dr.inference.operators.SimpleMCMCOperator; -import dr.xml.*; -import org.w3c.dom.Document; -import org.w3c.dom.Element; - - -/** - * An operator on categories of sites - * - * @author Roald Forsberg - */ -public class CategoryOperator extends SimpleMCMCOperator { - - public static final String CATEGORY_OPERATOR = "categoryOperator"; - - // dimension of categoryParameter should be set beforehand - public CategoryOperator(CategorySampleModel siteModel, int siteCount, - Parameter categoryParameter, double weight) { - this.categoryParameter = categoryParameter; - setWeight(weight); - this.siteModel = siteModel; - this.categoryCount = siteModel.getCategoryCount(); - this.siteCount = siteCount; - } - - - /** - * Alter the category of one site - */ - public final double doOperation() { - - int randomSite = (int) (MathUtils.nextDouble() * siteCount); - - int currentCategory = (int) categoryParameter.getParameterValue(randomSite); - - siteModel.subtractSitesInCategoryCount(currentCategory); - - int[] temp = new int[categoryCount - 1]; - - int count = 0; - - for (int i = 0; i < categoryCount; i++) { - if (i != currentCategory) { - temp[count] = i; - count++; - } - } - - int newCategory = temp[(int) (MathUtils.nextDouble() * temp.length)]; - - categoryParameter.setParameterValue(randomSite, newCategory); - siteModel.addSitesInCategoryCount(newCategory); - - return 0.0; - - } - - - // Interface MCMCOperator - public final String getOperatorName() { - return CATEGORY_OPERATOR; - } - - - /** - * Create the Operator part of this model parameter! - */ - public Element createOperatorElement(Document d) { - throw new RuntimeException("Not implemented!"); - } - - public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { - - public String getParserName() { - return CATEGORY_OPERATOR; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - Parameter catParam = (Parameter) xo.getChild(Parameter.class); - CategorySampleModel siteModel = (CategorySampleModel) xo.getChild(CategorySampleModel.class); - Alignment alignment = (Alignment) xo.getChild(Alignment.class); - - double weight = xo.getDoubleAttribute(WEIGHT); - - return new CategoryOperator(siteModel, alignment.getSiteCount(), - catParam, weight); - } - - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - - public String getParserDescription() { - return "An operator on categories of sites."; - } - - public Class getReturnType() { - return CategoryOperator.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{ - AttributeRule.newDoubleRule("weight"), - new ElementRule(Parameter.class), - new ElementRule(CategorySampleModel.class), - new ElementRule(Alignment.class) - }; - - }; - - public String toString() { - return getOperatorName(); - } - - public String getPerformanceSuggestion() { - return ""; - } - - // Private instance variables - private Parameter categoryParameter; - - private CategorySampleModel siteModel; - - private int categoryCount; - - private int siteCount; - -} - diff --git a/src/dr/evomodel/operators/LinkageGroupSwap.java b/src/dr/evomodel/operators/LinkageGroupSwap.java deleted file mode 100644 index 8a91b860c5..0000000000 --- a/src/dr/evomodel/operators/LinkageGroupSwap.java +++ /dev/null @@ -1,162 +0,0 @@ -/* - * LinkageGroupSwap.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.operators; - -import dr.evolution.alignment.Alignment; -import dr.evolution.util.Taxon; -import dr.evomodel.tree.HiddenLinkageModel; -import dr.inference.operators.SimpleMCMCOperator; -import dr.math.MathUtils; -import dr.xml.*; - -import java.util.ArrayList; -import java.util.HashSet; - -/** - * @author Aaron Darling - */ -public class LinkageGroupSwap extends SimpleMCMCOperator { - - HiddenLinkageModel hlm; - int groupCount; - int columnCount; - - public LinkageGroupSwap(HiddenLinkageModel hlm, double weight){ - this.hlm = hlm; - groupCount = hlm.getLinkageGroupCount(); - columnCount = hlm.getData().getAlignment().getSiteCount(); - setWeight(weight); - } - - @Override - public double doOperation() { - if(MathUtils.nextBoolean()){ - // swap all taxa in one group to a new group - int A = MathUtils.nextInt(groupCount); - int B = MathUtils.nextInt(groupCount); - HashSet aTaxa = new HashSet(hlm.getGroup(A)); - HashSet bTaxa = new HashSet(hlm.getGroup(B)); - for(Taxon taxon : aTaxa){ - hlm.moveReadGroup(taxon, A, B); - } - for(Taxon taxon : bTaxa){ - hlm.moveReadGroup(taxon, B, A); - } - }else{ - // pick two linkage groups uniformly A, B - // pick an alignment column uniformly X - // move all reads in group A that are defined in column X to group B, and - // vice versa from B to A. - // pick a read uniformly at random, add it to a linkage group uniformly at random - ArrayList aTaxa = new ArrayList(); - ArrayList bTaxa = new ArrayList(); - int A=0, B=0; - - // iterate until we actually find something to move - // this could be done more efficiently, e.g. by limiting - // choice of X and Y to groups that have something in col X. - while(aTaxa.size()==0&&bTaxa.size()==0) - { - int X = MathUtils.nextInt(columnCount); - - A = MathUtils.nextInt(groupCount); - B = MathUtils.nextInt(groupCount); - if(A==B) - continue; // nothing to do. - - // find all reads intersecting column X - Alignment aln = hlm.getData().getAlignment(); - for(int i=0; i NO_DEPENDENCY){ - if(bitVec[dependentInd] == ABSENT && bitVec[i]==PRESENT){ - //throw new OperatorFailedException(""); - return Double.NEGATIVE_INFINITY; - } - } - - } - parameter.setParameterValue(index, newVal); - - return logq; - } - - public final String getPerformanceSuggestion() { - return "no suggestions available"; - } - - public static dr.xml.XMLObjectParser PARSER = new AbstractXMLObjectParser() { - - public String getParserName() { - return "msatModelSwitchOperator"; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - double weight = xo.getDoubleAttribute(WEIGHT); - Parameter modelChoose = (Parameter) xo.getElementFirstChild(MODEL_CHOOSE); - Parameter dependencies = (Parameter)xo.getElementFirstChild(DEPENDENCIES); - int[] variableIndices; - if(xo.hasChildNamed(VARIABLE_INDICES)){ - - double[] temp = ((Parameter)xo.getElementFirstChild(VARIABLE_INDICES)).getParameterValues(); - variableIndices = new int[temp.length]; - for(int i = 0; i < temp.length;i++){ - variableIndices[i] = (int)temp[i]; - } - - }else{ - variableIndices = new int[]{0, 1, 2, 3, 4, 5}; - } - - return new MicrosatelliteBitFlipOperator(modelChoose, dependencies, weight, variableIndices); - } - - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - - public String getParserDescription() { - return "This element returns a microsatellite averaging operator on a given parameter."; - } - - public Class getReturnType() { - return MCMCOperator.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{ - AttributeRule.newDoubleRule(WEIGHT), - new ElementRule(MODEL_CHOOSE, new XMLSyntaxRule[]{new ElementRule(Parameter.class)}), - new ElementRule(DEPENDENCIES, new XMLSyntaxRule[]{new ElementRule(Parameter.class)}), - new ElementRule(VARIABLE_INDICES, new XMLSyntaxRule[]{new ElementRule(Parameter.class)},true) - - }; - - }; - -} diff --git a/src/dr/evomodel/operators/MicrosatelliteFullAncestryImportanceSamplingOperator.java b/src/dr/evomodel/operators/MicrosatelliteFullAncestryImportanceSamplingOperator.java deleted file mode 100644 index 02b819b467..0000000000 --- a/src/dr/evomodel/operators/MicrosatelliteFullAncestryImportanceSamplingOperator.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * MicrosatelliteFullAncestryImportanceSamplingOperator.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.operators; - -import dr.evolution.tree.TreeUtils; -import dr.evomodel.tree.MicrosatelliteSamplerTreeModel; -import dr.evomodel.tree.TreeModel; -import dr.oldevomodel.substmodel.MicrosatelliteModel; -import dr.evomodel.branchratemodel.BranchRateModel; -import dr.inference.model.Parameter; -import dr.evolution.tree.NodeRef; -import dr.inference.operators.SimpleMCMCOperator; -import dr.math.MathUtils; - -/** - * @author Chieh-Hsi Wu - * - * Produce an importance sample of the ancestry given a msat pattern and a tree. - */ -public class MicrosatelliteFullAncestryImportanceSamplingOperator extends SimpleMCMCOperator { - - public static final String MSAT_FULL_ANCESTRY_IMPORTANCE_SAMPLING_OPERATOR = "MsatFullAncestryImportanceSamplingOperator"; - private Parameter parameter; - private MicrosatelliteSamplerTreeModel msatSamplerTreeModel; - private MicrosatelliteModel msatModel; - private BranchRateModel branchRateModel; - - - public MicrosatelliteFullAncestryImportanceSamplingOperator( - Parameter parameter, - MicrosatelliteSamplerTreeModel msatSamplerTreeModel, - MicrosatelliteModel msatModel, - BranchRateModel branchRateModel, - double weight){ - - super(); - this.parameter = parameter; - this.msatSamplerTreeModel = msatSamplerTreeModel; - this.msatModel = msatModel; - this.branchRateModel = branchRateModel; - setWeight(weight); - } - - public double doOperation() { - TreeModel tree = msatSamplerTreeModel.getTreeModel(); - - //get postOrder - int[] postOrder = new int[tree.getNodeCount()]; - TreeUtils.postOrderTraversalList(tree,postOrder); - - int extNodeCount = tree.getExternalNodeCount(); - double logq=0.0; - for(int i = 0; i < postOrder.length; i ++){ - - //if it's an internal node - if(postOrder[i] >= extNodeCount){ - - //getLikelihoodGiven the children - NodeRef node = tree.getNode(postOrder[i]); - NodeRef lc = tree.getChild(node,0); - NodeRef rc = tree.getChild(node,1); - int lcState = msatSamplerTreeModel.getNodeValue(lc); - int rcState = msatSamplerTreeModel.getNodeValue(rc); - double branchLeftLength = tree.getBranchLength(lc)*branchRateModel.getBranchRate(tree,lc); - double branchRightLength = tree.getBranchLength(rc)*branchRateModel.getBranchRate(tree,rc); - double[] probLbranch = msatModel.getColTransitionProbabilities(branchLeftLength, lcState); - double[] probRbranch = msatModel.getColTransitionProbabilities(branchRightLength, rcState); - double[] lik = new double[msatModel.getDataType().getStateCount()]; - int currState = (int)parameter.getParameterValue(msatSamplerTreeModel.getParameterIndexFromNodeNumber(postOrder[i])); - //if node = root node - if(i == postOrder.length -1){ - //likelihood of root state also depends on the stationary distribution - double[] statDist = msatModel.getStationaryDistribution(); - for(int j = 0; j < lik.length; j++){ - lik[j] = probLbranch[j]*probRbranch[j]*statDist[j]; - } - - }else{ - - for(int j = 0; j < lik.length; j++){ - lik[j] = probLbranch[j]*probRbranch[j]; - } - - } - - int sampledState = MathUtils.randomChoicePDF(lik); - logq = logq + Math.log(lik[currState]) - Math.log(lik[sampledState]); - parameter.setParameterValue(msatSamplerTreeModel.getParameterIndexFromNodeNumber(postOrder[i]),sampledState); - } - } - - return logq; - } - - public String getPerformanceSuggestion(){ - return "None"; - } - public String getOperatorName(){ - return MSAT_FULL_ANCESTRY_IMPORTANCE_SAMPLING_OPERATOR; - } - public int getStepCount(){ - return 1; - } -} diff --git a/src/dr/evomodel/operators/MicrosatelliteModelSelectOperator.java b/src/dr/evomodel/operators/MicrosatelliteModelSelectOperator.java deleted file mode 100644 index f45a4d35ec..0000000000 --- a/src/dr/evomodel/operators/MicrosatelliteModelSelectOperator.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * MicrosatelliteModelSelectOperator.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.operators; - -import dr.inference.model.Parameter; -import dr.inference.operators.SimpleMCMCOperator; -import dr.math.MathUtils; - -/** - * @author Chieh-Hsi Wu - * - * Operator that selects a microsatellite model from a group provided by the user. - */ -public class MicrosatelliteModelSelectOperator extends SimpleMCMCOperator { - private Parameter parameter; - private Parameter[] indicators; - public MicrosatelliteModelSelectOperator(Parameter parameter, Parameter[] indicators, double weight){ - this.parameter = parameter; - this.indicators = indicators; - setWeight(weight); - } - - public String getOperatorName(){ - return "msatModelSelectOperator("+parameter.getParameterName()+")"; - } - - public final String getPerformanceSuggestion() { - return "no suggestions available"; - } - - public double doOperation() { - int index = MathUtils.nextInt(indicators.length); - //System.out.println(index); - Parameter newModel = indicators[index]; - for(int i = 0; i < parameter.getDimension() -1 ; i++){ - parameter.setParameterValueQuietly(i,newModel.getParameterValue(i)); - } - parameter.setParameterValueNotifyChangedAll( - parameter.getDimension()-1, - newModel.getParameterValue(parameter.getDimension()-1) - ); - //System.out.println(parameter+"; "+indicators[index]); - return 0.0; - } - - - -} diff --git a/src/dr/evomodel/operators/MicrosatelliteSingleAncestralStateGibbsOperator.java b/src/dr/evomodel/operators/MicrosatelliteSingleAncestralStateGibbsOperator.java deleted file mode 100644 index 5a356ff296..0000000000 --- a/src/dr/evomodel/operators/MicrosatelliteSingleAncestralStateGibbsOperator.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * MicrosatelliteSingleAncestralStateGibbsOperator.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.operators; - -import dr.inference.model.Parameter; -import dr.evomodel.tree.MicrosatelliteSamplerTreeModel; -import dr.evomodel.tree.TreeModel; -import dr.oldevomodel.substmodel.MicrosatelliteModel; -import dr.evomodel.branchratemodel.BranchRateModel; -import dr.evolution.tree.NodeRef; -import dr.inference.operators.GibbsOperator; -import dr.inference.operators.SimpleMCMCOperator; -import dr.math.MathUtils; - -/** - * @author Chieh-Hsi Wu - * - * - */ -public class MicrosatelliteSingleAncestralStateGibbsOperator extends SimpleMCMCOperator implements GibbsOperator { - public static final String MSAT_SINGLE_ANCESTAL_STATE_GIBBS_OPERATOR = "MsatSingleAncestralStateGibbsOperator"; - private Parameter parameter; - private MicrosatelliteSamplerTreeModel msatSamplerTreeModel; - private MicrosatelliteModel msatModel; - private BranchRateModel branchRateModel; - - public MicrosatelliteSingleAncestralStateGibbsOperator( - Parameter parameter, - MicrosatelliteSamplerTreeModel msatSamplerTreeModel, - MicrosatelliteModel msatModel, - BranchRateModel branchRateModel, - double weight){ - - super(); - this.parameter = parameter; - this.msatSamplerTreeModel = msatSamplerTreeModel; - this.msatModel = msatModel; - this.branchRateModel = branchRateModel; - setWeight(weight); - } - - public double doOperation() { - TreeModel tree = msatSamplerTreeModel.getTreeModel(); - - - int index = MathUtils.nextInt(parameter.getDimension()); - - //double logq=0.0; - - - //getLikelihoodGiven the children - NodeRef node = tree.getNode(msatSamplerTreeModel.getNodeNumberFromParameterIndex(index)); - NodeRef lc = tree.getChild(node,0); - NodeRef rc = tree.getChild(node,1); - - - int lcState = msatSamplerTreeModel.getNodeValue(lc); - int rcState = msatSamplerTreeModel.getNodeValue(rc); - - - double branchLeftLength = tree.getBranchLength(lc)*branchRateModel.getBranchRate(tree,lc); - double branchRightLength = tree.getBranchLength(rc)*branchRateModel.getBranchRate(tree,rc); - - - double[] probLbranch = msatModel.getColTransitionProbabilities(branchLeftLength, lcState); - double[] probRbranch = msatModel.getColTransitionProbabilities(branchRightLength, rcState); - - double[] lik = new double[msatModel.getDataType().getStateCount()]; - //int currState = (int)parameter.getParameterValue(index); - //if node = root node - - if(tree.isRoot(node)){ - //likelihood of root state also depends on the stationary distribution - double[] statDist = msatModel.getStationaryDistribution(); - for(int j = 0; j < lik.length; j++){ - lik[j] = probLbranch[j]*probRbranch[j]*statDist[j]; - } - }else{ - NodeRef parent = tree.getParent(node); - int pState = msatSamplerTreeModel.getNodeValue(parent); - double branchParentLength = tree.getBranchLength(node)*branchRateModel.getBranchRate(tree,node); - double[] probPbranch = msatModel.getRowTransitionProbabilities(branchParentLength,pState); - for(int j = 0; j < lik.length; j++){ - lik[j] = probLbranch[j]*probRbranch[j]*probPbranch[j]; - } - } - - int sampledState = MathUtils.randomChoicePDF(lik); - //logq = logq + Math.log(lik[currState]) - Math.log(lik[sampledState]); - parameter.setParameterValue(index,sampledState); - return 0.0; - } - - public String getPerformanceSuggestion(){ - return "None"; - } - public String getOperatorName(){ - return MSAT_SINGLE_ANCESTAL_STATE_GIBBS_OPERATOR; - } - public int getStepCount(){ - return 1; - } - -} \ No newline at end of file diff --git a/src/dr/evomodel/operators/MicrosatelliteUpDownOperator.java b/src/dr/evomodel/operators/MicrosatelliteUpDownOperator.java deleted file mode 100644 index 32a580d69d..0000000000 --- a/src/dr/evomodel/operators/MicrosatelliteUpDownOperator.java +++ /dev/null @@ -1,154 +0,0 @@ -/* - * MicrosatelliteUpDownOperator.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.operators; - -import dr.inference.operators.*; -import dr.math.MathUtils; - -/** - * - * @author Chieh-Hsi - * - * Implements MicrosatUpDownOperator - * - * This is almost the same as UpDownOperator, except it uses scaleAllAndNotify method instead of scale. - * - */ -public class MicrosatelliteUpDownOperator extends AbstractAdaptableOperator { - - private Scalable.Default[] upParameter = null; - private Scalable.Default[] downParameter = null; - private double scaleFactor; - - public MicrosatelliteUpDownOperator(Scalable.Default[] upParameter, - Scalable.Default[] downParameter, - double scale, - double weight, - AdaptationMode mode) { - - super(mode); - setWeight(weight); - - this.upParameter = upParameter; - this.downParameter = downParameter; - this.scaleFactor = scale; - } - - public final double getScaleFactor() { - return scaleFactor; - } - - public final void setScaleFactor(double sf) { - if( (sf > 0.0) && (sf < 1.0) ) { - scaleFactor = sf; - } else { - throw new IllegalArgumentException("scale must be between 0 and 1"); - } - } - - /** - * change the parameter and return the hastings ratio. - */ - public final double doOperation() { - - - final double scale = (scaleFactor + (MathUtils.nextDouble() * ((1.0 / scaleFactor) - scaleFactor))); - int goingUp = 0, goingDown = 0; - - if( upParameter != null ) { - for( Scalable.Default up : upParameter ) { - goingUp += up.scaleAllAndNotify(scale, -1, false); - } - } - - if( downParameter != null ) { - for(Scalable.Default dn : downParameter ) { - goingDown += dn.scaleAllAndNotify(1.0 / scale, -1, false); - } - } - - return (goingUp - goingDown - 2) * Math.log(scale); - } - - public String getAdaptableParameterName() { - return "scaleFactor"; - } - - public final String getOperatorName() { - String name = ""; - if( upParameter != null ) { - name = "up:"; - for( Scalable up : upParameter ) { - name = name + up.getName() + " "; - } - } - - if( downParameter != null ) { - name += "down:"; - for( Scalable dn : downParameter ) { - name = name + dn.getName() + " "; - } - } - return name; - } - - @Override - protected double getAdaptableParameterValue() { - return Math.log(1.0 / scaleFactor - 1.0) / Math.log(10); - } - - public void setAdaptableParameterValue(double value) { - scaleFactor = 1.0 / (Math.pow(10.0, value) + 1.0); - } - - public double getRawParameter() { - return scaleFactor; - } - - // Since this operator invariably modifies at least 2 parameters it - // should allow lower acceptance probabilities - // as it is known that optimal acceptance levels are inversely - // proportional to the number of dimensions operated on - // AD 16/3/2004 - public double getMinimumAcceptanceLevel() { - return 0.05; - } - - public double getMaximumAcceptanceLevel() { - return 0.3; - } - - public double getMinimumGoodAcceptanceLevel() { - return 0.10; - } - - public double getMaximumGoodAcceptanceLevel() { - return 0.20; - } - -} \ No newline at end of file diff --git a/src/dr/evomodel/operators/MoveLinkageGroup.java b/src/dr/evomodel/operators/MoveLinkageGroup.java deleted file mode 100644 index 7ad0fca9c8..0000000000 --- a/src/dr/evomodel/operators/MoveLinkageGroup.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * MoveLinkageGroup.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.operators; - -import dr.evolution.util.Taxon; -import dr.evomodel.tree.HiddenLinkageModel; -import dr.evomodelxml.operators.MoveLinkageGroupParser; -import dr.inference.operators.SimpleMCMCOperator; -import dr.math.MathUtils; - -/** - * @author Aaron Darling - */ -public class MoveLinkageGroup extends SimpleMCMCOperator { - - HiddenLinkageModel hlm; - int readCount; - int groupCount; - - public MoveLinkageGroup(HiddenLinkageModel hlm, double weight){ - this.hlm = hlm; - readCount = hlm.getData().getReadsTaxa().getTaxonCount(); - groupCount = hlm.getLinkageGroupCount(); - setWeight(weight); - } - - public double doOperation() { - // pick a read uniformly at random, add it to a linkage group uniformly at random - int r = MathUtils.nextInt(readCount); - Taxon read = hlm.getData().getReadsTaxa().getTaxon(r); - int g=hlm.getLinkageGroupId(read); - - int newGroup = MathUtils.nextInt(groupCount); - hlm.moveReadGroup(read, g, newGroup); - - // moves are symmetric -- same forward and backward proposal probabilities - double logHastings = 0.0; - return logHastings; - } - - public String getOperatorName() { - return MoveLinkageGroupParser.MOVE_LINKAGE_GROUP + "(" + hlm.getId() + ")"; - } - - public String getPerformanceSuggestion() { - return "Ask Aaron Darling to write a better operator"; - } - -} diff --git a/src/dr/evomodel/operators/RateSampleOperator.java b/src/dr/evomodel/operators/RateSampleOperator.java deleted file mode 100644 index f704685751..0000000000 --- a/src/dr/evomodel/operators/RateSampleOperator.java +++ /dev/null @@ -1,179 +0,0 @@ -/* - * RateSampleOperator.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.operators; - -import dr.evolution.tree.NodeRef; -import dr.oldevomodel.clock.RateEvolutionLikelihood; -import dr.evomodel.tree.TreeModel; -import dr.evomodelxml.operators.RateSampleOperatorParser; -import dr.inference.operators.SimpleMCMCOperator; -import dr.math.MathUtils; - -/** - * A special operator for sampling rates in a subtree - * according to a RateEvolutionLikelihood such as the autocorrelated clock model - * - * @author Michael Defoin Platel - */ -public class RateSampleOperator extends SimpleMCMCOperator { - - private TreeModel tree; - - private boolean sampleAll; - - RateEvolutionLikelihood rateEvolution; - - public RateSampleOperator(TreeModel tree, boolean sampleAll, RateEvolutionLikelihood rateEvolution) { - - this.tree = tree; - this.sampleAll = sampleAll; - this.rateEvolution = rateEvolution; - } - - /** - * sample the rates of a subtree and return the hastings ratio. - */ - public final double doOperation() { - - int index; - if (sampleAll) { - index = tree.getRoot().getNumber(); - } else { - do { - index = MathUtils.nextInt(tree.getNodeCount()); - } while (tree.isExternal(tree.getNode(index))); - } - - - double logBackward = rateEvolution.getLogLikelihood(); - - //sampleOne(tree.getNode(index)); - - //sampleSubtree(tree.getNode(index)); - sampleNode(tree.getNode(index)); - - //sampleSister(tree.getNode(index)); - - double logForward = rateEvolution.getLogLikelihood(); - - return logBackward - logForward; - } - - void sampleSubtree(NodeRef parent) { - - int nbChildren = tree.getChildCount(parent); - for (int c = 0; c < nbChildren; c++) { - final NodeRef node = tree.getChild(parent, c); - rateEvolution.sampleRate(node); - sampleSubtree(node); - } - } - - void sampleSister(NodeRef parent) { - - int nbChildren = tree.getChildCount(parent); - for (int c = 0; c < nbChildren; c++) { - final NodeRef node = tree.getChild(parent, c); - rateEvolution.sampleRate(node); - } - - } - - void sampleNode(NodeRef parent) { - - int nbChildren = tree.getChildCount(parent); - - if (nbChildren > 0) { - final int c = MathUtils.nextInt(nbChildren); - - final NodeRef node = tree.getChild(parent, c); - rateEvolution.sampleRate(node); - } - - } - - void sampleOne(NodeRef parent) { - - int nbChildren = tree.getChildCount(parent); - - if (nbChildren > 0) { - - final NodeRef node = tree.getChild(parent, 0); - rateEvolution.sampleRate(node); - } - - } - - /** - * This method should be overridden by operators that need to do something just before the return of doOperation. - * - * @param newValue the proposed parameter value - * @param oldValue the old parameter value - */ - void cleanupOperation(double newValue, double oldValue) { - // DO NOTHING - } - - //MCMCOperator INTERFACE - public final String getOperatorName() { - return "rateSample"; - } - - - public double getTargetAcceptanceProbability() { - return 0.234; - } - - public double getMinimumAcceptanceLevel() { - return 0.1; - } - - public double getMaximumAcceptanceLevel() { - return 0.4; - } - - public double getMinimumGoodAcceptanceLevel() { - return 0.20; - } - - public double getMaximumGoodAcceptanceLevel() { - return 0.30; - } - - public final String getPerformanceSuggestion() { - - return "No suggestions"; - } - - public String toString() { - return RateSampleOperatorParser.SAMPLE_OPERATOR + "("; - } - - //PRIVATE STUFF - -} \ No newline at end of file diff --git a/src/dr/evomodel/operators/TreeNodeSlide.java b/src/dr/evomodel/operators/TreeNodeSlide.java deleted file mode 100644 index 1f947516eb..0000000000 --- a/src/dr/evomodel/operators/TreeNodeSlide.java +++ /dev/null @@ -1,482 +0,0 @@ -/* - * TreeNodeSlide.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.operators; - -import dr.evolution.tree.NodeRef; -import dr.evolution.tree.Tree; -import dr.evolution.tree.TreeUtils; -import dr.evomodel.speciation.SpeciesBindings; -import dr.evomodel.speciation.SpeciesTreeModel; -import dr.evomodelxml.operators.TreeNodeSlideParser; -import dr.inference.model.Parameter; -import dr.inference.operators.SimpleMCMCOperator; -import dr.math.MathUtils; -import jebl.util.FixedBitSet; - -import java.util.Arrays; - -/** - * An operator on a species tree based on the ideas of Mau et all. - * - * - * Bayesian Phylogenetic Inference via Markov Chain Monte Carlo Methods - * - * @author Joseph Heled - * Date: 29/05/2008 - */ -// Cleaning out untouched stuff. Can be resurrected if needed -@Deprecated -public class TreeNodeSlide extends SimpleMCMCOperator { - - private final SpeciesTreeModel tree; - private final SpeciesBindings species; - - private final int[] preOrderIndexBefore; - private final int[] preOrderIndexAfter; - - private final boolean verbose = false; - - // private double range = 1.0; - // private boolean outgroupOnly = false; - - //private boolean verbose = false; - - public TreeNodeSlide(SpeciesTreeModel tree, SpeciesBindings species /*, boolean outgroupOnly*/, double weight) { - this.tree = tree; - this.species = species; - // this.outgroupOnly = outgroupOnly; - - preOrderIndexBefore = new int[tree.getNodeCount()]; - Arrays.fill(preOrderIndexBefore, -1); - - preOrderIndexAfter= new int[tree.getNodeCount()]; - Arrays.fill(preOrderIndexAfter, -1); - - setWeight(weight); - } - - public String getPerformanceSuggestion() { - return "none"; - } - - public String getOperatorName() { - return TreeNodeSlideParser.TREE_NODE_REHEIGHT + "(" + tree.getId() + "," + species.getId() + ")"; - } - - public double doOperation() { - operateOneNode(0.0); - return 0; - } - - private void ptree(SpeciesTreeModel tree, NodeRef[] order, int[] preOrderIndex) { - System.err.println(TreeUtils.uniqueNewick(tree, tree.getRoot())); - System.err.println(TreeUtils.newick(tree)); - ptreenode(tree, tree.getRoot(), preOrderIndex, ""); - for(NodeRef anOrder : order) { - System.err.print(anOrder.getNumber() + " "); - } - System.err.println(); - } - - private void ptreenode(SpeciesTreeModel tree, NodeRef node, int[] preOrderIndex, String indent) { - System.err.print(indent + node.getNumber() + " " + tree.getNodeHeight(node) + - " " + ((node != tree.getRoot()) ? tree.getParent(node).getNumber() : -1) + " "); - - if( ! tree.isExternal(node) ) { - System.err.print("(" + tree.getChild(node, 0).getNumber() + " " + tree.getChild(node, 1).getNumber() - + ")"); - int k = tree.getExternalNodeCount() + 2*preOrderIndex[node.getNumber()]; - System.err.println(" [" + tree.sppSplitPopulations.getParameterValue(k) + "," + - tree.sppSplitPopulations.getParameterValue(k+1) + "] "); - ptreenode(tree, tree.getChild(node, 0), preOrderIndex, indent + " "); - ptreenode(tree, tree.getChild(node, 1), preOrderIndex, indent + " "); - } else { - System.err.println( tree.getNodeTaxon(node).toString() ); - } - } - - public void operateOneNode(final double factor) { - -// #print "operate: tree", ut.treerep(t) - // if( verbose) System.out.println(" Mau at start: " + tree.getSimpleTree()); - - final int count = tree.getExternalNodeCount(); assert count == species.nSpecies(); - - NodeRef[] order = new NodeRef[2 * count - 1]; - boolean[] swapped = new boolean[count-1]; - mauCanonical(tree, order, swapped); - - // internal node to change - // count-1 - number of internal nodes - int which = MathUtils.nextInt(count - 1); -// if( outgroupOnly ) { -// if( order[1] == tree.getRoot() ) { -// which = 0; -// } else if( order[2*count - 3] == tree.getRoot() ) { -// which = count - 2; -// } -// } -// if( verbose) { -// System.out.print("order:"); -// for(int k = 0 ; k < 2*count; k += 2) { -// System.out.print(tree.getNodeTaxon(order[k]).getId() + ((k == 2*which) ? "*" : " ")); -// } -// System.out.println(); -// } - - FixedBitSet left = new FixedBitSet(count); - FixedBitSet right = new FixedBitSet(count); - - for(int k = 0; k < 2*which+1; k += 2) { - left.set(tree.speciesIndex(order[k])); - } - - for(int k = 2*(which+1); k < 2*count; k += 2) { - right.set(tree.speciesIndex(order[k])); - } - - double newHeight; - - if( factor > 0 ) { - newHeight = tree.getNodeHeight(order[2*which+1]) * factor; - } else { - final double limit = species.speciationUpperBound(left, right); - newHeight = MathUtils.nextDouble() * limit; - } - - if( false ) { - double totChange = 0; - double tot = 0; - double totChangeUp = 0.0; - int topChange = 0; - - for(int which1 = 0; which1 < count - 1; which1++) { - FixedBitSet left1 = new FixedBitSet(count); - FixedBitSet right1 = new FixedBitSet(count); - - final NodeRef node = order[2 * which1 + 1]; - final double h = tree.getNodeHeight(node); - - for(int k = 0; k < 2 * which1 + 1; k += 2) { - final NodeRef ref = order[k]; - left1.set(tree.speciesIndex(ref)); - } - - for(int k = 2 * (which1 + 1); k < 2 * count; k += 2) { - right1.set(tree.speciesIndex(order[k])); - } - - final double limit = species.speciationUpperBound(left1, right1); - - final NodeRef parent = tree.getParent(node); - final double ph = parent != null ? tree.getNodeHeight(parent) : limit; - final double h1 = tree.getNodeHeight(tree.getChild(node, 0)); - final double h2 = tree.getNodeHeight(tree.getChild(node, 1)); - final double chDown = Math.max(h1, h2); - - final double chup = Math.max(limit - ph, 0); - totChangeUp += chup; - double change = chDown + chup; - totChange += change; - if( change > limit ) { - assert change <= limit; - } - - tot += limit; - - if( which == which1 && (newHeight < chDown || newHeight > limit - chup) ) { - topChange = 1; - } -// final double h1 = tree.getNodeHeight(order[2 * which1]); -// final double h2 = tree.getNodeHeight(order[2 * which1 + 2]); -// double lowerLimit = 0; -// double upperLimit = limit; -// if( h > h1 ) { -// assert tree.getParent(order[2 * which]) == node; -// lowerLimit = h1; -// } else { -// assert tree.getParent() == node; -// upperLimit = Math.min(upperLimit, h1); -// } -// if( h > h2 && h2 > lowerLimit ) { -// assert tree.getParent(order[2 * which+2]) == node; -// lowerLimit = h2; -// } -// - } - final double p = totChange / tot; - System.err.println("top% " + p + " " + totChangeUp / tot + (topChange > 0 ? "++" : "")); - } - - tree.beginTreeEdit(); - - tree.setPreorderIndices(preOrderIndexBefore); - - final NodeRef node = order[2 * which + 1]; - - if( false ) { - System.err.println("Before " + node.getNumber() + " " + newHeight); - ptree(tree, order, preOrderIndexBefore); - - if( newHeight > tree.getNodeHeight(node) ) { - NodeRef parent = tree.getParent(node); - while( parent != null && tree.getNodeHeight(parent) < newHeight) { - // swap - final int pi = getIndexOf(parent, order); - final int side = pi < which ? 0 : 1; - // 0 for right, 1 for left - //final int side = (1+getSide(which, parent, order, swapped))/2; - - swapPops(node, swapped[which] ? 1-side : side, - parent, swapped[pi] ? side : 1-side, preOrderIndexBefore); - parent = tree.getParent(parent); - } - } else { - // NodeRef child = tree.getChild(node, 0); - if( which > 0 ) { - NodeRef nb = order[2*which - 1]; - if( tree.getNodeHeight(node) > tree.getNodeHeight(nb) ) { - while( nb != node && tree.getNodeHeight(nb) < newHeight ) { - nb = tree.getParent(nb); - } - - if( nb != node ) { - final int side = swapped[which] ? 1 : 0; - swapPops(node, side, nb, 1-side, preOrderIndexBefore); - - NodeRef pnb = tree.getParent(nb); - while( pnb != node ) { - swapPops(nb, 1-side, pnb, 1-side, preOrderIndexBefore); - nb = pnb; - pnb = tree.getParent(nb); - } - } - } - } - if( which < count - 2 ) { - NodeRef nb = order[2*which + 3]; - if( tree.getNodeHeight(node) > tree.getNodeHeight(nb) ) { - while( nb != node && tree.getNodeHeight(nb) < newHeight ) { - nb = tree.getParent(nb); - } - if( nb != node ) { - final int side = swapped[which] ? 0 : 1; - swapPops(node, side, nb, 1-side, preOrderIndexBefore); - - NodeRef pnb = tree.getParent(nb); - while( pnb != node ) { - swapPops(nb, 1-side, pnb, 1-side, preOrderIndexBefore); - nb = pnb; - pnb = tree.getParent(nb); - } - } - } - } - } - } - tree.setNodeHeight(node, newHeight); - - mauReconstruct(tree, order, swapped); - - // restore pre-order of pops - - { - tree.setPreorderIndices(preOrderIndexAfter); - - double[] splitPopValues = null; - - for(int k = 0; k < preOrderIndexBefore.length; ++k) { - final int b = preOrderIndexBefore[k]; - if( b >= 0 ) { - final int a = preOrderIndexAfter[k]; - if( a != b ) { - //if( verbose) System.out.println("pops: " + a + " <- " + b); - - final Parameter p1 = tree.sppSplitPopulations; - if( splitPopValues == null ) { - splitPopValues = p1.getParameterValues(); - } - - if( tree.constPopulation() ) { - p1.setParameterValue(count + a, splitPopValues[count + b]); - } else { - for(int i = 0; i < 2; ++i) { - p1.setParameterValue(count + 2*a + i, splitPopValues[count + 2*b + i]); - } - } - } - } - } - } - - // System.err.println("After"); - //ptree(tree, order, preOrderIndexAfter); - - // if( verbose) System.out.println(" Mau after: " + tree.getSimpleTree()); - // } - - tree.endTreeEdit(); - } - - private int getSide(int which, NodeRef parent, NodeRef[] order, boolean[] swapped) { - for(int k = 1; k < order.length; k+=2) { - if( order[k] == parent ) { - //if( swapped[(k-1)/2] ) s = -s; - return k < 2*which+1 ? -1 : +1; - } - } - assert false; - return 0; - } - - private int getIndexOf(NodeRef parent, NodeRef[] order) { - for(int k = 1; k < order.length; k+=2) { - if( order[k] == parent ) { - return (k-1)/2; - } - } - assert false; - return -1; - } - - private void swapPops(NodeRef node, int i, NodeRef parent, int i1, int[] preOrderIndexBefore) { - int count = tree.getExternalNodeCount(); - int l1 = count + 2*preOrderIndexBefore[node.getNumber()] + i; - int l2 = count + 2*preOrderIndexBefore[parent.getNumber()] + i1; - final double p1 = tree.sppSplitPopulations.getParameterValue(l1); - final double p2 = tree.sppSplitPopulations.getParameterValue(l2); - tree.sppSplitPopulations.setParameterValue(l1, p2); - tree.sppSplitPopulations.setParameterValue(l2, p1); - } - -// static private void treeMixup(Tree tree, NodeRef node) { -// final double h = tree.getNodeHeight(node); -// if( ! tree.isRoot(node) ) { -// assert tree.getBranchLength(node) == (tree.getNodeHeight(tree.getParent(node)) - h); -// } -// if( ! tree.isExternal(node) ) { -// for(int k = 0; k < tree.getChildCount(node); ++k) { -// assert h > tree.getNodeHeight(tree.getChild(node, k)); -// final NodeRef child = tree.getChild(node, k); -// treeMixup(tree, child); -// } -// } -// } - -// static private void setPreorderIndices(SpeciesTreeModel tree, int[] indices) { -// setPreorderIndices(tree, tree.getRoot(), 0, indices); -// } -// -// static private int setPreorderIndices(SpeciesTreeModel tree, NodeRef node, int loc, int[] indices) { -// if( ! tree.isExternal(node) ) { -// int l = setPreorderIndices(tree, tree.getChild(node, 0), loc, indices); -// indices[node.getNumber()] = l; -// loc = setPreorderIndices(tree, tree.getChild(node, 1), l+1, indices); -// } -// return loc; -// } - - /** - * Obtain an ordering of tree tips from randomly swaping the children order in internal nodes. - * - * @param tree tree to create order from - * @param order Nodes in their random order (only odd indices are filled) - * @param wasSwapped true if internal node was swapped - */ - static private void mauCanonical(Tree tree, NodeRef[] order, boolean[] wasSwapped) { - mauCanonicalSub(tree, tree.getRoot(), 0, order, wasSwapped); - } - - static private 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; - } - - static private void mauReconstruct(SpeciesTreeModel tree, NodeRef[] order, boolean[] swapped) { - final NodeRef root = mauReconstructSub(tree, 0, swapped.length, order, swapped); - if( tree.getRoot() != root ) { - tree.setRoot(root); - } - } - - static private NodeRef mauReconstructSub(SpeciesTreeModel tree, int from, int to, NodeRef[] order, boolean[] wasSwaped) { - if( from == to ) { - return order[2*from]; - } - - int rootIndex = -1; - { - double h = -1; - - for(int i = from; i < to; ++i) { - final double v = tree.getNodeHeight(order[2 * i + 1]); - if( h < v ) { - h = v; - rootIndex = i; - } - } - } - - final NodeRef root = order[2 * rootIndex + 1]; - - final NodeRef lchild = tree.getChild(root, 0); - final NodeRef rchild = tree.getChild(root, 1); - - NodeRef lTargetChild = mauReconstructSub(tree, from, rootIndex, order, wasSwaped); - NodeRef rTargetChild = mauReconstructSub(tree, rootIndex+1, to, order, wasSwaped); - - if( wasSwaped[rootIndex] ) { - NodeRef z = lTargetChild; - lTargetChild = rTargetChild; - rTargetChild = z; - } - - if( lchild != lTargetChild ) { - tree.replaceChild(root, lchild, lTargetChild); - } - - if( rchild != rTargetChild ) { - tree.replaceChild(root, rchild, rTargetChild); - } - - return root; - } - -} diff --git a/src/dr/evomodel/speciation/MultiSpeciesCoalescent.java b/src/dr/evomodel/speciation/MultiSpeciesCoalescent.java index 269b49e9cc..f87aa014cf 100644 --- a/src/dr/evomodel/speciation/MultiSpeciesCoalescent.java +++ b/src/dr/evomodel/speciation/MultiSpeciesCoalescent.java @@ -43,6 +43,7 @@ * * @author Joseph Heled, Graham Jones * Date: 26/05/2008 + * @deprecated - StarBEAST is in BEAST2 */ public class MultiSpeciesCoalescent extends Likelihood.Abstract implements Units { private final SpeciesTreeModel spTree; diff --git a/src/dr/evomodel/speciation/SpeciesBindings.java b/src/dr/evomodel/speciation/SpeciesBindings.java index 777ad6a462..9e4b9a1338 100644 --- a/src/dr/evomodel/speciation/SpeciesBindings.java +++ b/src/dr/evomodel/speciation/SpeciesBindings.java @@ -45,6 +45,7 @@ * * @author Joseph Heled * Date: 25/05/2008 + * @deprecated - StarBEAST is in BEAST2 */ public class SpeciesBindings extends AbstractModel { // all gene trees diff --git a/src/dr/evomodel/speciation/SpeciesTreeBMPrior.java b/src/dr/evomodel/speciation/SpeciesTreeBMPrior.java index a9bf4dcdef..05b66aa53b 100644 --- a/src/dr/evomodel/speciation/SpeciesTreeBMPrior.java +++ b/src/dr/evomodel/speciation/SpeciesTreeBMPrior.java @@ -36,6 +36,7 @@ /** * @author Joseph Heled * Date: 8/12/2008 + * @deprecated - StarBEAST is in BEAST2 */ public class SpeciesTreeBMPrior extends Likelihood.Abstract { diff --git a/src/dr/evomodel/speciation/SpeciesTreeModel.java b/src/dr/evomodel/speciation/SpeciesTreeModel.java index 03482a1d8b..515dbfc3c3 100644 --- a/src/dr/evomodel/speciation/SpeciesTreeModel.java +++ b/src/dr/evomodel/speciation/SpeciesTreeModel.java @@ -33,7 +33,6 @@ import dr.evolution.util.MutableTaxonListListener; import dr.evolution.util.Taxon; import dr.evomodel.coalescent.VDdemographicFunction; -import dr.evomodel.operators.TreeNodeSlide; import dr.evomodel.tree.TreeLogger; import dr.evomodelxml.speciation.SpeciesTreeModelParser; import dr.inference.model.AbstractModel; @@ -54,6 +53,8 @@ * * @author Joseph Heled * Date: 24/05/2008 + * + * @deprecated - StarBEAST is in BEAST2 */ public class SpeciesTreeModel extends AbstractModel implements MutableTree, TreeTraitProvider, TreeLogger.LogUpon, Scalable, Citable { @@ -931,7 +932,7 @@ private SimpleTree compatibleUninformedSpeciesTree(Tree startTree) { } if (treeHeight > 0) { - sTree.setAttribute("check", new Double(rootHeight)); + sTree.setAttribute("check", rootHeight); } { @@ -989,7 +990,7 @@ public String getName() { return getModelName(); } - static private TreeNodeSlide internalTreeOP = null; +// static private TreeNodeSlide internalTreeOP = null; public int scale(double scaleFactor, int nDims, boolean testBounds) { assert scaleFactor > 0; @@ -1010,11 +1011,11 @@ public int scale(double scaleFactor, int nDims, boolean testBounds) { if (nDims != 1) { throw new UnsupportedOperationException("not implemented for count != 1"); } - if (internalTreeOP == null) { - internalTreeOP = new TreeNodeSlide(this, species, 1); - } - - internalTreeOP.operateOneNode(scaleFactor); +// if (internalTreeOP == null) { +// internalTreeOP = new TreeNodeSlide(this, species, 1); +// } +// +// internalTreeOP.operateOneNode(scaleFactor); fireModelChanged(this, 1); return nDims; } diff --git a/src/dr/evomodel/speciation/SpeciesTreeSimplePrior.java b/src/dr/evomodel/speciation/SpeciesTreeSimplePrior.java index 70289520c7..6aab5e2e17 100644 --- a/src/dr/evomodel/speciation/SpeciesTreeSimplePrior.java +++ b/src/dr/evomodel/speciation/SpeciesTreeSimplePrior.java @@ -38,6 +38,7 @@ /** * @author Joseph Heled * Date: 8/12/2008 + * @deprecated - StarBEAST is in BEAST2 */ public class SpeciesTreeSimplePrior extends Likelihood.Abstract { diff --git a/src/dr/evomodel/substmodel/BinaryCovarionModel.java b/src/dr/evomodel/substmodel/BinaryCovarionModel.java index bceebfee3b..7a3d754ff5 100644 --- a/src/dr/evomodel/substmodel/BinaryCovarionModel.java +++ b/src/dr/evomodel/substmodel/BinaryCovarionModel.java @@ -29,7 +29,6 @@ import dr.evomodelxml.substmodel.BinaryCovarionModelParser; import dr.evolution.datatype.TwoStateCovarion; -import dr.oldevomodel.substmodel.SubstitutionModelUtils; import dr.inference.model.Parameter; /** @@ -65,7 +64,7 @@ public BinaryCovarionModel(TwoStateCovarion dataType, Parameter hiddenFrequencies, Parameter alphaParameter, Parameter switchingParameter, - dr.oldevomodel.substmodel.BinaryCovarionModel.Version version) { + BinaryCovarionModel.Version version) { super(BinaryCovarionModelParser.COVARION_MODEL, dataType, frequencies, hiddenFrequencies); @@ -171,10 +170,95 @@ protected double getNormalizationValue(double[][] matrix, double[] pi) { return 1.0; // Already normalized } + /** + * Normalize rate matrix to one expected substitution per unit time + * + * @param matrix the matrix to normalize to one expected substitution + * @param pi the equilibrium distribution of states + */ + void normalize(double[][] matrix, double[] pi) { + + double subst = 0.0; + int dimension = pi.length; + + for (int i = 0; i < dimension; i++) { + subst += -matrix[i][i] * pi[i]; + } + + // normalize, including switches + for (int i = 0; i < dimension; i++) { + for (int j = 0; j < dimension; j++) { + matrix[i][j] = matrix[i][j] / subst; + } + } + + double switchingProportion = 0.0; + switchingProportion += matrix[0][2] * pi[2]; + switchingProportion += matrix[2][0] * pi[0]; + switchingProportion += matrix[1][3] * pi[3]; + switchingProportion += matrix[3][1] * pi[1]; + + //System.out.println("switchingProportion=" + switchingProportion); + + // normalize, removing switches + for (int i = 0; i < dimension; i++) { + for (int j = 0; j < dimension; j++) { + matrix[i][j] = matrix[i][j] / (1.0 - switchingProportion); + } + } + } + + public enum Version { + VERSION1("1") { + public double getF0(double iF0) { + return 1.0; + } + + public double getF1(double iF1) { + return 1.0; + } + }, + VERSION2("2") { + public double getF0(double iF0) { + return iF0; + } + + public double getF1(double iF1) { + return iF1; + } + }; + + Version(String text) { + this.text = text; + } + + public String getText() { + return text; + } + + private final String text; + + public static Version parseFromString(String text) { + for (Version version : Version.values()) { + if (version.getText().compareToIgnoreCase(text) == 0) + return version; + } + throw new IllegalArgumentException("Unknown version type: " + text); + } + + public String toString() { + return getText(); + } + + abstract public double getF0(double iF0); + + abstract public double getF1(double iF1); + } + private Parameter alpha; private Parameter switchRate; private Parameter frequencies; private Parameter hiddenFrequencies; - final private dr.oldevomodel.substmodel.BinaryCovarionModel.Version version; + final private Version version; } \ No newline at end of file diff --git a/src/dr/evomodel/substmodel/MutationDeathModel.java b/src/dr/evomodel/substmodel/MutationDeathModel.java index 62d62dc353..6bf59bc788 100644 --- a/src/dr/evomodel/substmodel/MutationDeathModel.java +++ b/src/dr/evomodel/substmodel/MutationDeathModel.java @@ -39,12 +39,13 @@ package dr.evomodel.substmodel; import dr.evolution.datatype.DataType; -import dr.oldevomodelxml.substmodel.MutationDeathModelParser; import dr.inference.model.Model; import dr.inference.model.Parameter; import java.util.Arrays; +import static dr.evomodelxml.substmodel.MutationDeathModelParser.MD_MODEL; + public class MutationDeathModel extends ComplexSubstitutionModel { //BaseSubstitutionModel { private SubstitutionModel CTMCModel; private Parameter delParameter = null; @@ -58,7 +59,7 @@ public class MutationDeathModel extends ComplexSubstitutionModel { //BaseSubstit public MutationDeathModel(Parameter delParameter, DataType dT, SubstitutionModel evoModel, FrequencyModel freqModel, Parameter mutationRate) { - super(MutationDeathModelParser.MD_MODEL, dT, freqModel, null); + super(MD_MODEL, dT, freqModel, null); CTMCModel = evoModel; stateCount = freqModel.getFrequencyCount(); diff --git a/src/dr/oldevomodel/substmodel/SubstitutionModelUtils.java b/src/dr/evomodel/substmodel/SubstitutionModelUtils.java similarity index 99% rename from src/dr/oldevomodel/substmodel/SubstitutionModelUtils.java rename to src/dr/evomodel/substmodel/SubstitutionModelUtils.java index ab63a6ac27..c84a37e700 100644 --- a/src/dr/oldevomodel/substmodel/SubstitutionModelUtils.java +++ b/src/dr/evomodel/substmodel/SubstitutionModelUtils.java @@ -25,7 +25,7 @@ * */ -package dr.oldevomodel.substmodel; +package dr.evomodel.substmodel; import dr.evolution.datatype.DataType; @@ -144,4 +144,4 @@ private static String header(DataType dataType, int indent, int columnWidth) { } return builder.toString(); } -} +} \ No newline at end of file diff --git a/src/dr/evomodel/substmodel/nucleotide/HKY.java b/src/dr/evomodel/substmodel/nucleotide/HKY.java index 87cc5abac2..9aca67b0fb 100644 --- a/src/dr/evomodel/substmodel/nucleotide/HKY.java +++ b/src/dr/evomodel/substmodel/nucleotide/HKY.java @@ -286,15 +286,7 @@ public static void main(String[] args) { double[] probs = new double[16]; hky.getTransitionProbabilities(time,probs); System.out.println("new probs = "+new Vector(probs)); - - // check against old implementation - dr.oldevomodel.substmodel.FrequencyModel oldFreq = new dr.oldevomodel.substmodel.FrequencyModel(Nucleotides.INSTANCE,pi); - dr.oldevomodel.substmodel.HKY oldHKY = new dr.oldevomodel.substmodel.HKY(kappa,oldFreq); - oldHKY.setKappa(kappa); - - oldHKY.getTransitionProbabilities(time,probs); - System.out.println("old probs = "+new Vector(probs)); - + } /** diff --git a/src/dr/evomodel/tree/HiddenLinkageLogger.java b/src/dr/evomodel/tree/HiddenLinkageLogger.java deleted file mode 100644 index ccc5ad0441..0000000000 --- a/src/dr/evomodel/tree/HiddenLinkageLogger.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * HiddenLinkageLogger.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.evomodel.tree; - -import dr.inference.loggers.LogFormatter; -import dr.inference.loggers.MCLogger; - -/** - * @author Aaron Darling - */ -public class HiddenLinkageLogger extends MCLogger { - - HiddenLinkageModel hlm; - public HiddenLinkageLogger(HiddenLinkageModel hlm, LogFormatter formatter, int logEvery) - { - super(formatter, logEvery, false); - this.hlm = hlm; - } - - public void startLogging() { - String[] labels = new String[1 + hlm.getData().getReadsTaxa().getTaxonCount()]; - labels[0] = "iter"; - for(int i=1; i

- *

- * Created by - * Alexander V. Alekseyenko (alexander.alekseyenko@gmail.com) - * Date: Feb 13, 2008 - * Time: 10:13:07 AM - */ -public class ALSTreeLikelihood extends TreeLikelihood { - - protected AbstractObservationProcess observationProcess; - - public ALSTreeLikelihood(AbstractObservationProcess observationProcess, PatternList patternList, TreeModel treeModel, - SiteModel siteModel, BranchRateModel branchRateModel, boolean useAmbiguities, - boolean storePartials, boolean forceRescaling) { - super(patternList, treeModel, siteModel, branchRateModel, null, useAmbiguities, false, storePartials, false, forceRescaling); - - this.observationProcess = observationProcess; - addModel(observationProcess); - - // TreeLikelihood does not initialize the partials for tips, we'll do it ourselves - int extNodeCount = treeModel.getExternalNodeCount(); - for (int i = 0; i < extNodeCount; i++) { - String id = treeModel.getTaxonId(i); - int index = patternList.getTaxonIndex(id); - setPartials(likelihoodCore, patternList, categoryCount, index, i); - } - -/* //Examine the tree - double totalTime=0.0; - double realTime = 0.0; - for(int i=0; i - *

- * Created by - * Alexander V. Alekseyenko (alexander.alekseyenko@gmail.com) - * Date: Feb 19, 2008 - * Time: 12:41:01 PM - */ -abstract public class AbstractObservationProcess extends AbstractModel { - protected boolean[] nodePatternInclusion; - protected boolean[] storedNodePatternInclusion; - protected double[] cumLike; - protected double[] nodePartials; - protected double[] nodeLikelihoods; - protected int nodeCount; - protected int patternCount; - protected int stateCount; - protected TreeModel treeModel; - protected PatternList patterns; - protected double[] patternWeights; - protected Parameter mu; - protected Parameter lam; - - // update control variables - protected boolean weightKnown; - protected double logTreeWeight; - protected double storedLogTreeWeight; - private double gammaNorm; - private double totalPatterns; - protected MutationDeathType dataType; - protected int deathState; - protected SiteRateModel siteModel; - private double logN; - protected boolean nodePatternInclusionKnown = false; - BranchRateModel branchRateModel; - - public AbstractObservationProcess(String Name, TreeModel treeModel, PatternList patterns, SiteRateModel siteModel, - BranchRateModel branchRateModel, Parameter mu, Parameter lam) { - super(Name); - this.treeModel = treeModel; - this.patterns = patterns; - this.mu = mu; - this.lam = lam; - this.siteModel = siteModel; - if (branchRateModel != null) { - this.branchRateModel = branchRateModel; - } else { - this.branchRateModel = new DefaultBranchRateModel(); - } - addModel(treeModel); - addModel(siteModel); - addModel(this.branchRateModel); - addVariable(mu); - addVariable(lam); - - nodeCount = treeModel.getNodeCount(); - stateCount = patterns.getDataType().getStateCount(); - this.patterns = patterns; - patternCount = patterns.getPatternCount(); - patternWeights = patterns.getPatternWeights(); - totalPatterns = 0; - for (int i = 0; i < patternCount; ++i) { - totalPatterns += patternWeights[i]; - } - logN = Math.log(totalPatterns); - - gammaNorm = -GammaFunction.lnGamma(totalPatterns + 1); - - dataType = (MutationDeathType) patterns.getDataType(); - this.deathState = dataType.DEATHSTATE; - setNodePatternInclusion(); - cumLike = new double[patternCount]; - nodeLikelihoods = new double[patternCount]; - weightKnown = false; - } - -// public Parameter getMuParameter() { -// return mu; -// } -// -// public Parameter getLamParameter() { -// return lam; -// } - - private double calculateSiteLogLikelihood(int site, double[] partials, double[] frequencies) { - int v = site * stateCount; - double sum = 0.0; - for (int i = 0; i < stateCount; i++) { - sum += frequencies[i] * partials[v + i]; - } - return Math.log(sum); - } - - - private void calculateNodePatternLikelihood(int nodeIndex, - double[] freqs, - LikelihoodCore likelihoodCore, - double averageRate, - double[] cumLike) { - // get partials for node nodeIndex - likelihoodCore.getPartials(nodeIndex, nodePartials); // MAS - /* - multiply the partials by equilibrium probs - this part could be optimized by first summing - and then multiplying by equilibrium probs - */ - double prob = Math.log(getNodeSurvivalProbability(nodeIndex, averageRate)); - - for (int j = 0; j < patternCount; ++j) { - if (nodePatternInclusion[nodeIndex * patternCount + j]) { - cumLike[j] += Math.exp(calculateSiteLogLikelihood(j, nodePartials, freqs) + prob); - } - } - } - - private double accumulateCorrectedLikelihoods(double[] cumLike, double ascertainmentCorrection, - double[] patterWeights) { - double logL = 0; - for (int j = 0; j < patternCount; ++j) { - logL += Math.log(cumLike[j] / ascertainmentCorrection) * patternWeights[j]; - } - return logL; - } - - public final double nodePatternLikelihood(double[] freqs, LikelihoodPartialsProvider likelihoodCore, - ScaleFactorsHelper scaleFactorsHelper) { - int i, j; - double logL = gammaNorm; - - double birthRate = lam.getParameterValue(0); - double logProb; - if (!nodePatternInclusionKnown) - setNodePatternInclusion(); - if (nodePartials == null) { - nodePartials = new double[patternCount * stateCount]; - } - - double averageRate = getAverageRate(); - - for (j = 0; j < patternCount; ++j) cumLike[j] = 0; - - for (i = 0; i < nodeCount; ++i) { - // get partials for node i - likelihoodCore.getPartials(i, nodePartials); - scaleFactorsHelper.rescalePartials(i, nodePartials); - /* - multiply the partials by equilibrium probs - this part could be optimized by first summing - and then multiplying by equilibrium probs - */ -// likelihoodCore.calculateLogLikelihoods(nodePartials, freqs, nodeLikelihoods); // MAS Removed - logProb = Math.log(getNodeSurvivalProbability(i, averageRate)); - - for (j = 0; j < patternCount; ++j) { - if (nodePatternInclusion[i * patternCount + j]) { -// cumLike[j] += Math.exp(nodeLikelihoods[j] + logProb); // MAS Replaced with line below - cumLike[j] += Math.exp(calculateSiteLogLikelihood(j, nodePartials, freqs) - + logProb); - } - } - } - - double ascertainmentCorrection = getAscertainmentCorrection(cumLike); -// System.err.println("AscertainmentCorrection: "+ascertainmentCorrection); - - for (j = 0; j < patternCount; ++j) { - logL += Math.log(cumLike[j] / ascertainmentCorrection) * patternWeights[j]; - } - - double deathRate = mu.getParameterValue(0); - - double logTreeWeight = getLogTreeWeight(); - - if (integrateGainRate) { - logL -= gammaNorm + logN + Math.log(-logTreeWeight * deathRate / birthRate) * totalPatterns; - } else { - logL += logTreeWeight + Math.log(birthRate / deathRate) * totalPatterns; - } - return logL; - } - - protected double getAscertainmentCorrection(double[] patternProbs) { - // This function probably belongs better to the AscertainedSitePatterns - double excludeProb = 0, includeProb = 0, returnProb = 1.0; - if (this.patterns instanceof AscertainedSitePatterns) { - int[] includeIndices = ((AscertainedSitePatterns) patterns).getIncludePatternIndices(); - int[] excludeIndices = ((AscertainedSitePatterns) patterns).getExcludePatternIndices(); - for (int i = 0; i < ((AscertainedSitePatterns) patterns).getIncludePatternCount(); i++) { - int index = includeIndices[i]; - includeProb += patternProbs[index]; - } - for (int j = 0; j < ((AscertainedSitePatterns) patterns).getExcludePatternCount(); j++) { - int index = excludeIndices[j]; - excludeProb += patternProbs[index]; - } - if (includeProb == 0.0) { - returnProb -= excludeProb; - } else if (excludeProb == 0.0) { - returnProb = includeProb; - } else { - returnProb = includeProb - excludeProb; - } - } - - return returnProb; - } - - final public double getLogTreeWeight() { - if (!weightKnown) { - logTreeWeight = calculateLogTreeWeight(); - weightKnown = true; - } - - return logTreeWeight; - } - - abstract public double calculateLogTreeWeight(); - - abstract void setNodePatternInclusion(); - - final public double getAverageRate() { - if (!averageRateKnown) { - double avgRate = 0.0; - double proportions[] = siteModel.getCategoryProportions(); - for (int i = 0; i < siteModel.getCategoryCount(); ++i) { - avgRate += proportions[i] * siteModel.getRateForCategory(i); - } - averageRate = avgRate; - averageRateKnown = true; - } - return averageRate; - } - - public double getNodeSurvivalProbability(int index, double averageRate) { - NodeRef node = treeModel.getNode(index); - NodeRef parent = treeModel.getParent(node); - - if (parent == null) return 1.0; - - final double deathRate = mu.getParameterValue(0) * averageRate; //getAverageRate(); - final double branchRate = branchRateModel.getBranchRate(treeModel, node); - // Get the operational time of the branch - final double branchTime = branchRate * treeModel.getBranchLength(node); - return 1.0 - Math.exp(-deathRate * branchTime); - } - - protected void handleModelChangedEvent(Model model, Object object, int index) { - if (model == siteModel) { - averageRateKnown = false; - } - if (model == treeModel || model == siteModel || model == branchRateModel) { - weightKnown = false; - } - if (model == treeModel) { - if (object instanceof TreeChangedEvent) { - if (((TreeChangedEvent) object).isTreeChanged()) { - nodePatternInclusionKnown = false; - } - } - } - } - - protected final void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) { - if (variable == mu || variable == lam) { - weightKnown = false; - } else { - System.err.println("AbstractObservationProcess: Got unexpected parameter changed event. (Parameter = " + variable + ")"); - } - } - - protected void storeState() { -// storedAverageRate = averageRate; - storedLogTreeWeight = logTreeWeight; - System.arraycopy(nodePatternInclusion, 0, storedNodePatternInclusion, 0, storedNodePatternInclusion.length); - } - - protected void restoreState() { -// averageRate = storedAverageRate; - averageRateKnown = false; - logTreeWeight = storedLogTreeWeight; - boolean[] tmp = storedNodePatternInclusion; - storedNodePatternInclusion = nodePatternInclusion; - nodePatternInclusion = tmp; - } - - protected void acceptState() { - } - - public void setIntegrateGainRate(boolean integrateGainRate) { - this.integrateGainRate = integrateGainRate; - } - - private boolean integrateGainRate = false; - - private double storedAverageRate; - private double averageRate; - private boolean averageRateKnown = false; -} diff --git a/src/dr/oldevomodel/MSSD/AnyTipObservationProcess.java b/src/dr/oldevomodel/MSSD/AnyTipObservationProcess.java deleted file mode 100644 index 758e048dac..0000000000 --- a/src/dr/oldevomodel/MSSD/AnyTipObservationProcess.java +++ /dev/null @@ -1,175 +0,0 @@ -/* - * AnyTipObservationProcess.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.MSSD; - -import dr.evolution.alignment.PatternList; -import dr.evolution.tree.NodeRef; -import dr.evolution.tree.TreeUtils; -import dr.evomodel.branchratemodel.BranchRateModel; -import dr.oldevomodel.sitemodel.SiteRateModel; -import dr.evomodel.tree.TreeModel; -import dr.inference.model.Parameter; - -/** - * Package: AnyTipObservationProcess - * Description: - *

- *

- * Created by - * Alexander V. Alekseyenko (alexander.alekseyenko@gmail.com) - * Date: Mar 18, 2008 - * Time: 6:45:00 PM - */ -public class AnyTipObservationProcess extends AbstractObservationProcess { - protected double[] u0; - protected double[] p; - - public AnyTipObservationProcess(String modelName, TreeModel treeModel, PatternList patterns, SiteRateModel siteModel, - BranchRateModel branchRateModel, Parameter mu, Parameter lam) { - super(modelName, treeModel, patterns, siteModel, branchRateModel, mu, lam); - } - - public double calculateLogTreeWeight() { - int L = treeModel.getNodeCount(); - if (u0 == null || p == null) { - u0 = new double[L]; // probability that the trait at node i survives to no leaf - p = new double[L]; // probability of survival on the branch ancestral to i - } - int i, j, childNumber; - NodeRef node; - double logWeight = 0.0; - - double averageRate = getAverageRate(); - - for (i = 0; i < L; ++i) { - p[i] = 1.0 - getNodeSurvivalProbability(i, averageRate); - } - - TreeUtils.postOrderTraversalList(treeModel, postOrderNodeList); - - for (int postOrderIndex = 0; postOrderIndex < nodeCount; postOrderIndex++) { - - i = postOrderNodeList[postOrderIndex]; - - if (i < treeModel.getExternalNodeCount()) { // Is tip - u0[i] = 0.0; - logWeight += 1.0 - p[i]; - } else { // Is internal node or root - u0[i] = 1.0; - node = treeModel.getNode(i); - for (j = 0; j < treeModel.getChildCount(node); ++j) { - childNumber = treeModel.getChild(node, j).getNumber(); - u0[i] *= 1.0 - p[childNumber] * (1.0 - u0[childNumber]); - } - logWeight += (1.0 - u0[i]) * (1.0 - p[i]); - } - } - - return -logWeight * lam.getParameterValue(0) / (getAverageRate() * mu.getParameterValue(0)); - } - - - private void setTipNodePatternInclusion() { // These values never change - for (int i = 0; i < treeModel.getExternalNodeCount(); i++) { - NodeRef node = treeModel.getNode(i); - - for (int patternIndex = 0; patternIndex < patternCount; patternIndex++) { - extantInTipsBelow[i * patternCount + patternIndex] = 1; - int taxonIndex = patterns.getTaxonIndex(treeModel.getNodeTaxon(node)); - int[] states = dataType.getStates(patterns.getPatternState(taxonIndex, patternIndex)); - for (int state : states) { - if (state == deathState) { - extantInTipsBelow[i * patternCount + patternIndex] = 0; - } - } - extantInTips[patternIndex] += extantInTipsBelow[i * patternCount + patternIndex]; - - } - } - - for (int i = 0; i < treeModel.getExternalNodeCount(); i++) { - for (int patternIndex = 0; patternIndex < patternCount; patternIndex++) { - nodePatternInclusion[i * patternCount + patternIndex] = - (extantInTipsBelow[i * patternCount + patternIndex] >= extantInTips[patternIndex]); - } - } - } - - void setNodePatternInclusion() { - - if (postOrderNodeList == null) { - postOrderNodeList = new int[nodeCount]; - } - - if (nodePatternInclusion == null) { - nodePatternInclusion = new boolean[nodeCount * patternCount]; - storedNodePatternInclusion = new boolean[nodeCount * patternCount]; - } - - if (extantInTips == null) { - extantInTips = new int[patternCount]; - extantInTipsBelow = new int[nodeCount * patternCount]; - setTipNodePatternInclusion(); - } - - // Determine post-order traversal - TreeUtils.postOrderTraversalList(treeModel, postOrderNodeList); - - // Do post-order traversal - for (int postOrderIndex = 0; postOrderIndex < nodeCount; postOrderIndex++) { - NodeRef node = treeModel.getNode(postOrderNodeList[postOrderIndex]); - final int nChildren = treeModel.getChildCount(node); - if (nChildren > 0) { - final int nodeNumber = node.getNumber(); - for (int patternIndex = 0; patternIndex < patternCount; patternIndex++) { - extantInTipsBelow[nodeNumber * patternCount + patternIndex] = 0; - for (int j = 0; j < nChildren; j++) { - final int childIndex = treeModel.getChild(node, j).getNumber(); - extantInTipsBelow[nodeNumber * patternCount + patternIndex] += - extantInTipsBelow[childIndex * patternCount + patternIndex]; - } - } - } - } - - for (int i = treeModel.getExternalNodeCount(); i < treeModel.getNodeCount(); ++i) { - for (int patternIndex = 0; patternIndex < patternCount; patternIndex++) { - nodePatternInclusion[i * patternCount + patternIndex] = - (extantInTipsBelow[i * patternCount + patternIndex] >= extantInTips[patternIndex]); - } - } - - nodePatternInclusionKnown = true; - } - - private int[] extantInTips; - private int[] extantInTipsBelow; // Easier to store/restore (later) if 1D array - - private int[] postOrderNodeList; - -} diff --git a/src/dr/oldevomodel/MSSD/ExponentialBranchLengthTreePrior.java b/src/dr/oldevomodel/MSSD/ExponentialBranchLengthTreePrior.java deleted file mode 100644 index bc4ade5e69..0000000000 --- a/src/dr/oldevomodel/MSSD/ExponentialBranchLengthTreePrior.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * ExponentialBranchLengthTreePrior.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.MSSD; - -import dr.evolution.tree.TreeUtils; -import dr.evomodel.tree.TreeModel; -import dr.inference.model.AbstractModelLikelihood; -import dr.inference.model.Model; -import dr.inference.model.Parameter; -import dr.inference.model.Variable; -import dr.math.GammaFunction; - -/** - * Package: alsDefaultPrior - * Description: - *

- *

- * Created by - * Alexander V. Alekseyenko (alexander.alekseyenko@gmail.com) - * Date: Mar 14, 2008 - * Time: 12:47:07 PM - */ -public class ExponentialBranchLengthTreePrior extends AbstractModelLikelihood { - - TreeModel treeModel; - - public ExponentialBranchLengthTreePrior(TreeModel treeModel) { - super(null); - this.treeModel = treeModel; - } - - protected void handleModelChangedEvent(Model model, Object object, int index) { -//AUTOGENERATED METHOD IMPLEMENTATION - } - - /** - * This method is called whenever a parameter is changed. - *

- * It is strongly recommended that the model component sets a "dirty" flag and does no - * further calculations. Recalculation is typically done when the model component is asked for - * some information that requires them. This mechanism is 'lazy' so that this method - * can be safely called multiple times with minimal computational cost. - */ - protected final void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) { -//AUTOGENERATED METHOD IMPLEMENTATION - } - - /** - * Additional state information, outside of the sub-model is stored by this call. - */ - protected void storeState() { -//AUTOGENERATED METHOD IMPLEMENTATION - } - - /** - * After this call the model is guaranteed to have returned its extra state information to - * the values coinciding with the last storeState call. - * Sub-models are handled automatically and do not need to be considered in this method. - */ - protected void restoreState() { -//AUTOGENERATED METHOD IMPLEMENTATION - } - - /** - * This call specifies that the current state is accept. Most models will not need to do anything. - * Sub-models are handled automatically and do not need to be considered in this method. - */ - protected void acceptState() { -//AUTOGENERATED METHOD IMPLEMENTATION - } - - /** - * Get the model. - * - * @return the model. - */ - public Model getModel() { - return this; //AUTOGENERATED METHOD IMPLEMENTATION - } - - /** - * Get the log likelihood. - * - * @return the log likelihood. - */ - public double getLogLikelihood() { - return calculateLogLikelihood(); - } - - public double calculateLogLikelihood() { - int L = treeModel.getNodeCount(); - - double totalTreeTime = TreeUtils.getTreeLength(treeModel, treeModel.getRoot()); - -// if(ctmcScale != null){ // -// double ab=ctmcScale.getParameterValue(0); -// return GammaFunction.lnGamma(L)-Math.log(mu*lam)-(L-1)*Math.log(totalTreeTime)-0.5*Math.log(ab)-ab*totalTreeTime; -// }else{ // No Markov Chain for this model - return GammaFunction.lnGamma(L) - (L - 1) * Math.log(totalTreeTime); - } - - /** - * Forces a complete recalculation of the likelihood next time getLikelihood is called - */ - public void makeDirty() { -//AUTOGENERATED METHOD IMPLEMENTATION - } -} diff --git a/src/dr/oldevomodel/MSSD/SingleTipObservationProcess.java b/src/dr/oldevomodel/MSSD/SingleTipObservationProcess.java deleted file mode 100644 index cf4dc5a290..0000000000 --- a/src/dr/oldevomodel/MSSD/SingleTipObservationProcess.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * SingleTipObservationProcess.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.MSSD; - -import dr.evolution.alignment.PatternList; -import dr.evolution.util.Taxon; -import dr.evomodel.branchratemodel.BranchRateModel; -import dr.oldevomodel.sitemodel.SiteRateModel; -import dr.evomodel.tree.TreeModel; -import dr.oldevomodelxml.MSSD.SingleTipObservationProcessParser; -import dr.inference.model.Parameter; - -/** - * Package: SingleTipObservationProcess - * Description: - *

- *

- * Created by - * Alexander V. Alekseyenko (alexander.alekseyenko@gmail.com) - * Date: Feb 19, 2008 - * Time: 2:57:14 PM - */ -public class SingleTipObservationProcess extends AnyTipObservationProcess { - protected Taxon sourceTaxon; - - public SingleTipObservationProcess(TreeModel treeModel, PatternList patterns, SiteRateModel siteModel, - BranchRateModel branchRateModel, Parameter mu, Parameter lam, Taxon sourceTaxon) { - super(SingleTipObservationProcessParser.MODEL_NAME, treeModel, patterns, siteModel, branchRateModel, mu, lam); - this.sourceTaxon = sourceTaxon; - } - - public double calculateLogTreeWeight() { - return -lam.getParameterValue(0) / (getAverageRate() * mu.getParameterValue(0)); - } - -} diff --git a/src/dr/oldevomodel/approxPopTree/AbstractPopulationMRCAModel.java b/src/dr/oldevomodel/approxPopTree/AbstractPopulationMRCAModel.java deleted file mode 100644 index e7e6efc3ea..0000000000 --- a/src/dr/oldevomodel/approxPopTree/AbstractPopulationMRCAModel.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * AbstractPopulationMRCAModel.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.approxPopTree; - -import dr.evolution.alignment.Patterns; -import dr.evolution.tree.NodeRef; -import dr.inference.model.AbstractModel; - -import java.util.LinkedList; - -/** - * Package: AbstractPopulationMRCAModel - * Description: - *

- *

- * Created by - * - * @author Alexander V. Alekseyenko (alexander.alekseyenko@gmail.com) - * Date: Feb 1, 2010 - * Time: 5:30:01 PM - */ -abstract public class AbstractPopulationMRCAModel extends AbstractModel { - protected double time; // time of the population node above - protected double tMRCA; - - public AbstractPopulationMRCAModel(String name, double populationTime) { - super(name); - time = populationTime; - } - - public double getMRCATime(LinkedList nodes) { // get time of actual MRCA for the sequence nodes below - return tMRCA; - } - - abstract public double drawMRCATime(LinkedList nodes); // re-draw from the distribution of t(MRCA) - - abstract public double[][] getMRCAPartials(LinkedList nodes, Patterns patterns); // get partials at Population node - - abstract public double[][] drawMRCAPartials(LinkedList nodes, Patterns patterns); // re-draw partial at Population node - - protected double[][] computeProfilePartials(LinkedList nodes, Patterns patterns) { // compute profile partials for the sequence nodes, useful for the above methods - - int patternCount = patterns.getPatternCount(); - int stateCount = patterns.getStateCount(); - double partials[][] = new double[patternCount][stateCount]; - // Do the profile computation here - // - return partials; - } -} diff --git a/src/dr/oldevomodel/approxPopTree/CoalescentPopulationMRCAModel.java b/src/dr/oldevomodel/approxPopTree/CoalescentPopulationMRCAModel.java deleted file mode 100644 index 8366dfab68..0000000000 --- a/src/dr/oldevomodel/approxPopTree/CoalescentPopulationMRCAModel.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * CoalescentPopulationMRCAModel.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.approxPopTree; - -import dr.evolution.alignment.Patterns; -import dr.evolution.tree.NodeRef; -import dr.inference.model.Model; -import dr.inference.model.Parameter; -import dr.inference.model.Variable; - -import java.util.LinkedList; - -/** - * Package: CoalescentPopulationMRCAModel - * Description: - *

- *

- * Created by - * - * @author Alexander V. Alekseyenko (alexander.alekseyenko@gmail.com) - * Date: Feb 1, 2010 - * Time: 6:06:24 PM - */ -public class CoalescentPopulationMRCAModel extends AbstractPopulationMRCAModel { - public CoalescentPopulationMRCAModel(String name, double populationTime) { - super(name, populationTime); - } - - public double getMRCATime(LinkedList nodes) { - return 0; //AUTOGENERATED METHOD IMPLEMENTATION - } - - public double drawMRCATime(LinkedList nodes) { - return 0; //AUTOGENERATED METHOD IMPLEMENTATION - } - - public double[][] getMRCAPartials(LinkedList nodes, Patterns patterns) { - return new double[0][]; //AUTOGENERATED METHOD IMPLEMENTATION - } - - public double[][] drawMRCAPartials(LinkedList nodes, Patterns patterns) { - return new double[0][]; //AUTOGENERATED METHOD IMPLEMENTATION - } - - protected void handleModelChangedEvent(Model model, Object object, int index) { - //AUTOGENERATED METHOD IMPLEMENTATION - } - - protected void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) { - //AUTOGENERATED METHOD IMPLEMENTATION - } - - protected void storeState() { - //AUTOGENERATED METHOD IMPLEMENTATION - } - - protected void restoreState() { - //AUTOGENERATED METHOD IMPLEMENTATION - } - - protected void acceptState() { - //AUTOGENERATED METHOD IMPLEMENTATION - } -} diff --git a/src/dr/oldevomodel/approxPopTree/ConstantPopulationMRCAModel.java b/src/dr/oldevomodel/approxPopTree/ConstantPopulationMRCAModel.java deleted file mode 100644 index 0b328d198f..0000000000 --- a/src/dr/oldevomodel/approxPopTree/ConstantPopulationMRCAModel.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * ConstantPopulationMRCAModel.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.approxPopTree; - -import dr.evolution.alignment.Patterns; -import dr.evolution.tree.NodeRef; -import dr.inference.model.Model; -import dr.inference.model.Parameter; -import dr.inference.model.Variable; - -import java.util.LinkedList; - -/** - * Package: ConstantPopulationMRCAModel - * Description: - *

- *

- * Created by - * - * @author Alexander V. Alekseyenko (alexander.alekseyenko@gmail.com) - * Date: Feb 1, 2010 - * Time: 5:43:52 PM - */ -public class ConstantPopulationMRCAModel extends AbstractPopulationMRCAModel { - public ConstantPopulationMRCAModel(String name, double populationTime) { - super(name, populationTime); - } - - public double getMRCATime(LinkedList nodes) { - return time; - } - - public double drawMRCATime(LinkedList nodes) { - return time; - } - - public double[][] getMRCAPartials(LinkedList nodes, Patterns patterns) { - return computeProfilePartials(nodes, patterns); - } - - public double[][] drawMRCAPartials(LinkedList nodes, Patterns patterns) { - return computeProfilePartials(nodes, patterns); - } - - protected void handleModelChangedEvent(Model model, Object object, int index) { - //AUTOGENERATED METHOD IMPLEMENTATION - } - - protected void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) { - //AUTOGENERATED METHOD IMPLEMENTATION - } - - protected void storeState() { - //AUTOGENERATED METHOD IMPLEMENTATION - } - - protected void restoreState() { - //AUTOGENERATED METHOD IMPLEMENTATION - } - - protected void acceptState() { - //AUTOGENERATED METHOD IMPLEMENTATION - } -} diff --git a/src/dr/oldevomodel/approxPopTree/PopTreeModel.java b/src/dr/oldevomodel/approxPopTree/PopTreeModel.java deleted file mode 100644 index 5259f28fb9..0000000000 --- a/src/dr/oldevomodel/approxPopTree/PopTreeModel.java +++ /dev/null @@ -1,197 +0,0 @@ -/* - * PopTreeModel.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.approxPopTree; - -import dr.evolution.tree.FlexibleTree; -import dr.evolution.tree.NodeRef; -import dr.evolution.util.Taxon; -import dr.evomodel.tree.TreeModel; -import dr.xml.*; - -import java.util.HashMap; -import java.util.LinkedList; -import java.util.Map; - -/** - * Package: PopTree - * Description: - *

- *

- * Created by - * - * @author Alexander V. Alekseyenko (alexander.alekseyenko@gmail.com) - * Date: Feb 1, 2010 - * Time: 11:39:59 AM - */ -public class PopTreeModel extends FlexibleTree { - protected Map> populations; - protected double time; - - public PopTreeModel(TreeModel treeModel, double time) throws InvalidTreeException { - super(treeModel); - this.time = time; - this.populations = new HashMap>(); - enforcePopulations(time); - } - - public void enforcePopulations(double time) { - enforcePopulations(time, this.getRoot()); - } - - public void enforcePopulations(double time, NodeRef node) { - beginTreeEdit(); - reducePopulations(time, node); - endTreeEdit(); - this.adoptTreeModelOrdering(); - } - - protected void reducePopulations(double time, NodeRef node) { - if (this.getNodeHeight(node) <= time) { - if (!this.isExternal(node)) - this.setNodeHeight(node, time); - mergeSubtreePopulation(node); - - } else { - for (int i = 0; i < this.getChildCount(node); ++i) { - NodeRef child = this.getChild(node, i); - reducePopulations(time, child); - } - } - } - - public void splitPopulation(NodeRef node) { - splitPopulation(node, .5); - } - - public void splitPopulation(NodeRef node, double frac) { - if (populations.containsKey(node) && populations.get(node).size() >= 1) { - // - } - } - - public void mergePopulations(NodeRef parent) { - // assumes parent is an internal node which will become a new population node with all the crap below merged into this population - setNodeHeight(parent, time); - enforcePopulations(time, parent); - } - - protected void mergeSubtreePopulation(NodeRef parent) { - /* - merge the subtree below node into a new population - */ - LinkedList sequenceNodes; - sequenceNodes = new LinkedList(); - if (this.getNodeTaxon(parent) == null) { - this.setNodeTaxon(parent, new Taxon("popNode" + populations.size())); - } - - if (this.isExternal(parent)) { - - } - - sequenceNodes.addFirst(parent); //push(parent); - while (true) { - NodeRef currentNode = sequenceNodes.removeFirst(); - if (this.isExternal(currentNode)) { - sequenceNodes.addFirst(currentNode); //push(currentNode); - //this.setNodeAttribute(parent,"sequenceNodes",sequenceNodes); - populations.put(parent, sequenceNodes); - return; - } - int numChildren = this.getChildCount(currentNode); - for (int i = 0; getChildCount(currentNode) > 0;) { - NodeRef child = this.getChild(currentNode, i); - sequenceNodes.addFirst(child); //push(child); - this.removeChild(currentNode, child); - } - } - } - - public int getPopulationNodeCount() { - return populations.size(); - } - - public String toString() { - return super.toString() + formatPopulationNodes(); - } - - public String formatPopulationNodes() { - String retval = "\n"; - retval += getExternalNodeCount() + "\n"; - for (NodeRef node : populations.keySet()) { - retval += this.getNodeTaxon(node).getId() + "(" + this.isExternal(node) + ")::"; - for (NodeRef seqNode : populations.get(node)) { - retval += this.getNodeTaxon(seqNode).getId() + ","; - } - retval += "\n"; - } - return retval; - } - - public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - TreeModel treeModel = (TreeModel) xo.getChild(TreeModel.class); - double timeCutoff = xo.getDoubleAttribute(POP_HEIGHT_CUTOFF); - PopTreeModel popTreeModel = null; - try { - popTreeModel = new PopTreeModel(treeModel, timeCutoff); - } catch (InvalidTreeException e) { - e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. - } - return popTreeModel; - } - - public XMLSyntaxRule[] getSyntaxRules() { - - return rules; //AUTOGENERATED METHOD IMPLEMENTATION - } - - private final XMLSyntaxRule[] rules = { - new ElementRule(TreeModel.class), - AttributeRule.newDoubleRule(POP_HEIGHT_CUTOFF, false), - }; - - public String getParserDescription() { - return "Creates a Population Tree Model with specified divergence cut-off for population nodes"; - } - - public Class getReturnType() { - return PopTreeModel.class; - } - - public String getParserName() { - return POP_TREE_MODEL; - } - - }; - - public static final String POP_TREE_MODEL = "popTreeModel"; - public static final String POP_HEIGHT_CUTOFF = "populationNodeHeight"; - public static final String TREE_MODEL = "treeModel"; -} diff --git a/src/dr/oldevomodel/approxPopTree/UniformPopulationMRCAModel.java b/src/dr/oldevomodel/approxPopTree/UniformPopulationMRCAModel.java deleted file mode 100644 index b301cd47e4..0000000000 --- a/src/dr/oldevomodel/approxPopTree/UniformPopulationMRCAModel.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * UniformPopulationMRCAModel.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.approxPopTree; - -import dr.evolution.alignment.Patterns; -import dr.evolution.tree.NodeRef; -import dr.inference.model.Model; -import dr.inference.model.Parameter; -import dr.inference.model.Variable; - -import java.util.LinkedList; - -/** - * Package: UniformPopulationMRCAModel - * Description: - *

- *

- * Created by - * - * @author Alexander V. Alekseyenko (alexander.alekseyenko@gmail.com) - * Date: Feb 1, 2010 - * Time: 5:38:45 PM - */ -public class UniformPopulationMRCAModel extends AbstractPopulationMRCAModel { - UniformPopulationMRCAModel(String name, double populationTime) { - super(name, populationTime); - } - - public double getMRCATime(LinkedList nodes) { - return tMRCA; - } - - public double drawMRCATime(LinkedList nodes) { - tMRCA = Math.random(); - return tMRCA; - } - - public double[][] getMRCAPartials(LinkedList nodes, Patterns patterns) { - return new double[0][]; //AUTOGENERATED METHOD IMPLEMENTATION - } - - public double[][] drawMRCAPartials(LinkedList nodes, Patterns patterns) { - return new double[0][]; //AUTOGENERATED METHOD IMPLEMENTATION - } - - protected void handleModelChangedEvent(Model model, Object object, int index) { - //AUTOGENERATED METHOD IMPLEMENTATION - } - - protected void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) { - //AUTOGENERATED METHOD IMPLEMENTATION - } - - protected void storeState() { - //AUTOGENERATED METHOD IMPLEMENTATION - } - - protected void restoreState() { - //AUTOGENERATED METHOD IMPLEMENTATION - } - - protected void acceptState() { - //AUTOGENERATED METHOD IMPLEMENTATION - } -} diff --git a/src/dr/oldevomodel/clock/ACLikelihood.java b/src/dr/oldevomodel/clock/ACLikelihood.java deleted file mode 100644 index f0b6532309..0000000000 --- a/src/dr/oldevomodel/clock/ACLikelihood.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * ACLikelihood.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.clock; - -import dr.evomodel.tree.TreeModel; -import dr.inference.model.Parameter; -import dr.math.MathUtils; -import dr.math.distributions.InverseGaussianDistribution; -import dr.math.distributions.LogNormalDistribution; -import dr.math.distributions.NormalDistribution; - -/** - * Calculates the likelihood of a set of rate changes in a tree, assuming a (log)normal or inverse gaussian distributed - * change in rate at each node, with a mean of the previous (log) rate and a variance proportional to branch length. - * cf Yang and Rannala 2006 - * - * @author Michael Defoin Platel - * @author Wai Lok Sibon Li - */ -public class ACLikelihood extends RateEvolutionLikelihood { - public static final String LOGNORMAL = "logNormal"; - public static final String NORMAL = "normal"; - public static final String INVERSEGAUSSIAN = "inverseGaussian"; - - public ACLikelihood(TreeModel tree, Parameter ratesParameter, Parameter variance, Parameter rootRate, - boolean isEpisodic, String distribution) { - - //super((isLogSpace) ? "LogNormally Distributed" : "Normally Distributed", tree, ratesParameter, rootRate, isEpisodic); - super(distribution, tree, ratesParameter, rootRate, isEpisodic); - - //this.isLogSpace = isLogSpace; - this.variance = variance; - this.distribution = distribution; - - addVariable(variance); - } - - /** - * @return the log likelihood of the rate change from the parent to the child. - */ - double branchRateChangeLogLikelihood(double parentRate, double childRate, double time) { - double var = variance.getParameterValue(0); - - if (!isEpisodic()) - var *= time; - - //if (isLogSpace) { - // double logParentRate = Math.log(parentRate); - // double logChildRate = Math.log(childRate); - - // return NormalDistribution.logPdf(logChildRate, logParentRate - (var / 2.), Math.sqrt(var)) - logChildRate; - - //} else { - // return NormalDistribution.logPdf(childRate, parentRate, Math.sqrt(var)); - //} - if(distribution.equals(LOGNORMAL)) { - return LogNormalDistribution.logPdf(childRate, Math.log(parentRate) - (var / 2.), Math.sqrt(var)); - } - else if(distribution.equals(NORMAL)) { - return NormalDistribution.logPdf(childRate, parentRate, Math.sqrt(var)); - } - else if(distribution.equals(INVERSEGAUSSIAN)) { /* Inverse Gaussian */ - double shape = (parentRate * parentRate * parentRate) / var; - return InverseGaussianDistribution.logPdf(childRate, parentRate, shape); - } - else { - throw new RuntimeException ("Parameter for distribution is not recognised"); - } - } - - double branchRateSample(double parentRate, double time) { - - double var = variance.getParameterValue(0); - - if (!isEpisodic()) - var *= time; - - //if (isLogSpace) { - // final double logParentRate = Math.log(parentRate); - - // return Math.exp(MathUtils.nextGaussian() * Math.sqrt(var) + logParentRate - (var / 2.)); - //} else { - // return MathUtils.nextGaussian() * Math.sqrt(var) + parentRate; - //} - - if(distribution.equals(LOGNORMAL)) { - final double logParentRate = Math.log(parentRate); - - return Math.exp(MathUtils.nextGaussian() * Math.sqrt(var) + logParentRate - (var / 2.)); - } - else if(distribution.equals(NORMAL)) { - return MathUtils.nextGaussian() * Math.sqrt(var) + parentRate; - } - else { /* Inverse Gaussian */ - //return Math.random() - //Random rand = new Random(); - double lambda = (parentRate * parentRate * parentRate) / var; - return MathUtils.nextInverseGaussian(parentRate, lambda); - } - } - - private Parameter variance; - //boolean isLogSpace = false; - String distribution; -} diff --git a/src/dr/oldevomodel/clock/RateEvolutionLikelihood.java b/src/dr/oldevomodel/clock/RateEvolutionLikelihood.java deleted file mode 100644 index 6ee8ce8a8b..0000000000 --- a/src/dr/oldevomodel/clock/RateEvolutionLikelihood.java +++ /dev/null @@ -1,221 +0,0 @@ -/* - * RateEvolutionLikelihood.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.clock; - -import dr.evolution.tree.NodeRef; -import dr.evolution.tree.Tree; -import dr.evomodel.branchratemodel.AbstractBranchRateModel; -import dr.evomodel.tree.TreeModel; -import dr.evomodel.tree.TreeParameterModel; -import dr.inference.model.Model; -import dr.inference.model.Parameter; -import dr.inference.model.Variable; - -import java.util.logging.Logger; - -/** - * Abstract superclass of likelihoods of rate evolution through time. - * - * @author Alexei Drummond - * @author Andrew Rambaut - * @author Michael Defoin Platel - */ -public abstract class RateEvolutionLikelihood extends AbstractBranchRateModel { - - public static final String RATES = "rates"; - public static final String EPISODIC = "episodic"; - public static final String LOGSPACE = "logspace"; - - public static final String ROOTRATE = "rootRate"; - - public RateEvolutionLikelihood(String name, TreeModel treeModel, Parameter ratesParameter, Parameter rootRateParameter, boolean isEpisodic) { - - super(name); - - this.treeModel = treeModel; - addModel(treeModel); - - this.ratesParameter = new TreeParameterModel(treeModel, ratesParameter, false); - Parameter.DefaultBounds bound = new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, 0, ratesParameter.getDimension()); - ratesParameter.addBounds(bound); - - addModel(this.ratesParameter); - - this.rootRateParameter = rootRateParameter; - rootRateParameter.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, 0, 1)); - addVariable(rootRateParameter); - - if (rootRateParameter.getDimension() != 1) { - throw new IllegalArgumentException("The root rate parameter must be of dimension 1"); - } - - this.isEpisodic = isEpisodic; - - Logger.getLogger("dr.evomodel").info("AutoCorrelated Relaxed Clock: " + name + (isEpisodic ? " (episodic)." : ".")); - - } - - // ************************************************************** - // Model IMPLEMENTATION - // ************************************************************** - - public final void handleModelChangedEvent(Model model, Object object, int index) { - likelihoodKnown = false; - if (model == ratesParameter) { - fireModelChanged(this, index); - } - } - - protected final void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) { - likelihoodKnown = false; - } - - protected void storeState() { - } - - protected void restoreState() { - likelihoodKnown = false; - } - - protected void acceptState() { - } - - // ************************************************************** - // Likelihood IMPLEMENTATION - // ************************************************************** - - /** - * Get the model. - * - * @return the model. - */ - public Model getModel() { - return this; - } - - public final double getLogLikelihood() { - if (!getLikelihoodKnown()) { - logLikelihood = calculateLogLikelihood(); - likelihoodKnown = true; - } - return logLikelihood; - } - - public void makeDirty() { - likelihoodKnown = false; - } - - /** - * Called to decide if the likelihood must be calculated. Can be overridden - * (for example, to always return false). - * - * @return the likelihood. - */ - protected boolean getLikelihoodKnown() { - return likelihoodKnown; - } - - /** - * Get the log likelihood of the rate changes in this tree. - * - * @return the log likelihood. - */ - private double calculateLogLikelihood() { - NodeRef root = treeModel.getRoot(); - NodeRef node1 = treeModel.getChild(root, 0); - NodeRef node2 = treeModel.getChild(root, 1); - - return calculateLogLikelihood(root, node1) + calculateLogLikelihood(root, node2); - } - - /** - * Recursively calculate the log likelihood of the rate changes in the given tree. - * - * @return the partial log likelihood of the rate changes below the given node plus the - * branch directly above. - */ - private double calculateLogLikelihood(NodeRef parent, NodeRef node) { - - double logL, length; - length = treeModel.getBranchLength(node); - - logL = branchRateChangeLogLikelihood(getBranchRate(treeModel, parent), getBranchRate(treeModel, node), - length); - - //System.out.print(parent.getNumber() + " " + getBranchRate(treeModel, parent)+ " " + node.getNumber() + " " + getBranchRate(treeModel, node) + " " + treeModel.getBranchLength(node) + " " + logL + ", "); - - for (int i = 0; i < treeModel.getChildCount(node); i++) { - logL += calculateLogLikelihood(node, treeModel.getChild(node, i)); - } - return logL; - } - - public String toString() { - return Double.toString(getLogLikelihood()); - } - - abstract double branchRateSample(double parentRate, double time); - - public void sampleRate(NodeRef node) { - - final NodeRef parent = treeModel.getParent(node); - final double length = treeModel.getBranchLength(node); - final double rate = branchRateSample(getBranchRate(treeModel, parent), length); - - treeModel.setNodeRate(node, rate); - - } - - public double getBranchRate(Tree tree, NodeRef node) { - - if (tree.isRoot(node)) return rootRateParameter.getParameterValue(0); - return ratesParameter.getNodeValue(tree, node); - } - - public boolean isEpisodic() { - return isEpisodic; - } - - /** - * @return the log likelihood of the rate change from the parent to the given node. - */ - abstract double branchRateChangeLogLikelihood(double parentRate, double childRate, double time); - - // ************************************************************** - // Private members - // ************************************************************** - - private double logLikelihood; - private boolean likelihoodKnown = false; - - private final TreeModel treeModel; - private final TreeParameterModel ratesParameter; - protected final Parameter rootRateParameter; - private final boolean isEpisodic; - -} diff --git a/src/dr/oldevomodel/clock/UCLikelihood.java b/src/dr/oldevomodel/clock/UCLikelihood.java deleted file mode 100644 index 70295635fe..0000000000 --- a/src/dr/oldevomodel/clock/UCLikelihood.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * UCLikelihood.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.clock; - -import dr.evomodel.tree.TreeModel; -import dr.inference.model.Parameter; -import dr.math.MathUtils; -import dr.math.distributions.NormalDistribution; - -/** - * Calculates the likelihood of a set of rate changes in a tree, assuming that rates are lognormally distributed - * cf Yang and Rannala 2006 - * - * @author Michael Defoin Platel - */ -public class UCLikelihood extends RateEvolutionLikelihood { - - public UCLikelihood(TreeModel tree, Parameter ratesParameter, Parameter variance, Parameter rootRate, boolean isLogSpace) { - - super((isLogSpace) ? "LogNormally Distributed" : "Normally Distributed", tree, ratesParameter, rootRate, false); - - this.isLogSpace = isLogSpace; - this.variance = variance; - - addVariable(variance); - } - - /** - * @return the log likelihood of the rate. - */ - double branchRateChangeLogLikelihood(double foo1, double rate, double foo2) { - double var = variance.getParameterValue(0); - double meanRate = rootRateParameter.getParameterValue(0); - - - if (isLogSpace) { - final double logmeanRate = Math.log(meanRate); - final double logRate = Math.log(rate); - - return NormalDistribution.logPdf(logRate, logmeanRate - (var / 2.), Math.sqrt(var)) - logRate; - - } else { - return NormalDistribution.logPdf(rate, meanRate, Math.sqrt(var)); - } - } - - double branchRateSample(double foo1, double foo2) { - double meanRate = rootRateParameter.getParameterValue(0); - - double var = variance.getParameterValue(0); - - if (isLogSpace) { - final double logMeanRate = Math.log(meanRate); - - return Math.exp(MathUtils.nextGaussian() * Math.sqrt(var) + logMeanRate - (var / 2.)); - } else { - return MathUtils.nextGaussian() * Math.sqrt(var) + meanRate; - } - } - - private final Parameter variance; - - boolean isLogSpace = false; -} diff --git a/src/dr/oldevomodel/clock/UniversalClock.java b/src/dr/oldevomodel/clock/UniversalClock.java deleted file mode 100644 index 4504f0e485..0000000000 --- a/src/dr/oldevomodel/clock/UniversalClock.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * UniversalClock.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.clock; - -import dr.evolution.tree.NodeRef; -import dr.evolution.tree.Tree; -import dr.evomodel.branchratemodel.AbstractBranchRateModel; -import dr.inference.model.Model; -import dr.inference.model.Parameter; -import dr.inference.model.Variable; - -/** - * A class that calculates the rate of evolution based on of the mass and temperature - * - * @author Alexei Drummond - */ - -public class UniversalClock extends AbstractBranchRateModel { - - public static final String UNIVERSAL_CLOCK = "universalClock"; - - /** - * creates a universal clock model - * - * @param rateParameter the rate vector of *all* nodes - * @param massParameter the mass vector of *all* nodes - * @param temperatureParameter the temperature vector of *all* nodes - * @param scaleParameter a single-dimensional scale parameter - */ - public UniversalClock( - Parameter rateParameter, - Parameter massParameter, - Parameter temperatureParameter, - Parameter scaleParameter - ) { - - super(UNIVERSAL_CLOCK); - - this.rateParameter = rateParameter; - this.massParameter = massParameter; - this.temperatureParameter = temperatureParameter; - this.scaleParameter = scaleParameter; - - // don't add rate parameter, cause that is what you are changing! - // you don't care if it changes - addVariable(massParameter); - addVariable(temperatureParameter); - addVariable(scaleParameter); - - } - - // ***************************************************************** - // Interface Model - // ***************************************************************** - - protected void handleModelChangedEvent(Model model, Object object, int index) { - // no submodels so nothing to do - } - - protected final void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) { - - if ((variable == massParameter) || (variable == temperatureParameter)) { - if (index == -1) { - calculateAllRates(); - } else calculateRate(index); - } else if (variable == scaleParameter) { - calculateAllRates(); - } else { - throw new RuntimeException("unknown parameter changed in " + UNIVERSAL_CLOCK); - } - } - - protected void storeState() { - } // no additional state needs storing - - protected void restoreState() { - } // no additional state needs restoring - - protected void acceptState() { - } // no additional state needs accepting - - // ************************************************************** - // Private methods - // ************************************************************** - - private void calculateAllRates() { - int numNodes = massParameter.getDimension(); - for (int i = 0; i < numNodes; i++) { - calculateRate(i); - } - } - - private void calculateRate(int index) { - - double mass = massParameter.getParameterValue(index); - double temperature = temperatureParameter.getParameterValue(index); - - double scale = scaleParameter.getParameterValue(0); - - // replace this with the real equation!! - double substitutionRate = scale * Math.pow(mass, -0.25) * Math.exp(temperature); - - rateParameter.setParameterValue(index, substitutionRate); - } - - public double getBranchRate(Tree tree, NodeRef node) { - throw new RuntimeException("Look at code before running this class!"); - } - - Parameter rateParameter = null; - Parameter massParameter = null; - Parameter temperatureParameter = null; - Parameter scaleParameter = null; - -} - diff --git a/src/dr/oldevomodel/ibd/AvgPosteriorIBDReporter.java b/src/dr/oldevomodel/ibd/AvgPosteriorIBDReporter.java deleted file mode 100644 index e67332e391..0000000000 --- a/src/dr/oldevomodel/ibd/AvgPosteriorIBDReporter.java +++ /dev/null @@ -1,318 +0,0 @@ -/* - * AvgPosteriorIBDReporter.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.ibd; - -import dr.evolution.tree.NodeRef; -import dr.evolution.tree.Tree; -import dr.evolution.tree.TreeTrait; -import dr.evolution.tree.TreeTraitProvider; -import dr.evomodel.branchratemodel.BranchRateModel; -import dr.evomodel.branchratemodel.DefaultBranchRateModel; -import dr.oldevomodel.substmodel.AbstractSubstitutionModel; -import dr.oldevomodel.substmodel.HKY; -import dr.evomodel.tree.TreeModel; -import dr.oldevomodel.treelikelihood.NodePosteriorTreeLikelihood; -import dr.inference.model.*; -import dr.xml.*; - -/** - * Package: dr.evomodel.ibd - * Description: Computes for each tip the expected number of other tips IBD to it given the tip labels, - * averaged over the full length of the alignment - *

- *

- * Created by - * avaleks (alexander.alekseyenko@gmail.com) - * Date: 04-Aug-2008 - * Time: 13:46:33 - */ -public class AvgPosteriorIBDReporter extends AbstractModel implements TreeTraitProvider { - - protected double[] ibdweights; - protected double[][] ibdForward; - protected double[][] ibdBackward; - protected double[] diag; - protected boolean weightsKnown; - protected HKY substitutionModel; - protected TreeModel treeModel; - protected BranchRateModel branchRateModel; - protected Parameter mutationParameter; - protected NodePosteriorTreeLikelihood likelihoodReporter; - protected double[] probabilities; - - AvgPosteriorIBDReporter(NodePosteriorTreeLikelihood likelihoodReporter, Parameter mutationParameter, TreeModel treeModel, BranchRateModel branchRateModel, AbstractSubstitutionModel substitutionModel) { - super("AvgPosteriorIBDReporter"); - this.substitutionModel = (HKY) substitutionModel; - addModel(this.substitutionModel); - this.treeModel = treeModel; - addModel(this.treeModel); - this.branchRateModel = branchRateModel; - addModel(this.branchRateModel); - this.mutationParameter = mutationParameter; - addVariable(this.mutationParameter); - this.likelihoodReporter = likelihoodReporter; - this.probabilities = new double[substitutionModel.getStateCount() * substitutionModel.getStateCount()]; - } - - public void forwardIBD() { - int numNodes = treeModel.getNodeCount(); - int stateCount = substitutionModel.getStateCount(); - getDiagonalRates(diag); - int patternCount = likelihoodReporter.getPatternCount(); - for (int nodeId = 0; nodeId < numNodes; ++nodeId) { - NodeRef node = treeModel.getNode(nodeId); - NodeRef parent = treeModel.getParent(node); - likelihoodReporter.getNodeMatrix(nodeId, probabilities); - double[] posteriors = likelihoodReporter.getPosteriors(nodeId); - if (parent == null) { // handle the root - - } else if (treeModel.isExternal(node)) { // Handle the tip - double branchTime = branchRateModel.getBranchRate(treeModel, node) * (treeModel.getNodeHeight(parent) - treeModel.getNodeHeight(node)); - - for (int state = 0; state < stateCount; ++state) { - double enorm = Math.exp(-diag[state] * branchTime) / probabilities[state + state * stateCount]; - for (int pattern = 0; pattern < patternCount; ++pattern) { - ibdForward[nodeId][pattern * stateCount + state] = posteriors[pattern * stateCount + state] * enorm; - } - } - } else { // Handle internal node - double branchTime = branchRateModel.getBranchRate(treeModel, node) * (treeModel.getNodeHeight(parent) - treeModel.getNodeHeight(node)); - - int childCount = treeModel.getChildCount(node); - for (int state = 0; state < stateCount; ++state) { - double enorm = Math.exp(-diag[state] * branchTime) / probabilities[state + state * stateCount]; - for (int pattern = 0; pattern < patternCount; ++pattern) { - ibdForward[nodeId][pattern * stateCount + state] = 0; - - for (int child = 0; child < childCount; ++child) { - int childNodeId = treeModel.getChild(node, child).getNumber(); - - ibdForward[nodeId][pattern * stateCount + state] += ibdForward[childNodeId][pattern * stateCount + state]; - } - ibdForward[nodeId][pattern * stateCount + state] *= posteriors[pattern * stateCount + state] * enorm; - } - } - } - } - } - - public void backwardIBD(NodeRef node) { - int stateCount = substitutionModel.getStateCount(); - int patternCount = likelihoodReporter.getPatternCount(); - if (node == null) { - node = treeModel.getRoot(); - int nodeId = node.getNumber(); - for (int i = 0; i < patternCount * stateCount; ++i) { - ibdBackward[nodeId][i] = 0; - } - } - getDiagonalRates(diag); - int childCount = treeModel.getChildCount(node); - int nodeId = node.getNumber(); - - double[] posteriors = likelihoodReporter.getPosteriors(nodeId); - for (int child = 0; child < childCount; ++child) { - NodeRef childNode = treeModel.getChild(node, child); - int childNodeId = childNode.getNumber(); - likelihoodReporter.getNodeMatrix(childNodeId, probabilities); - double branchTime = branchRateModel.getBranchRate(treeModel, childNode) * (treeModel.getNodeHeight(node) - treeModel.getNodeHeight(childNode)); - for (int pattern = 0; pattern < patternCount; ++pattern) { - for (int state = 0; state < stateCount; ++state) { - ibdBackward[childNodeId][pattern * stateCount + state] = ibdBackward[nodeId][pattern * stateCount + state]; - for (int sibling = 0; sibling < childCount; ++sibling) { - if (sibling != child) { - int siblingId = treeModel.getChild(node, sibling).getNumber(); - ibdBackward[childNodeId][pattern * stateCount + state] += ibdForward[siblingId][pattern * stateCount + state]; - } - } - ibdBackward[childNodeId][pattern * stateCount + state] *= posteriors[pattern * stateCount + state] * Math.exp(-diag[state] * branchTime) / probabilities[state + state * stateCount]; - } - } - } - for (int child = 0; child < childCount; ++child) { - NodeRef childNode = treeModel.getChild(node, child); - backwardIBD(childNode); - } - - } - - public void expectedIBD() { - int stateCount = substitutionModel.getStateCount(); - int nodeCount = treeModel.getNodeCount(); - int patternCount = likelihoodReporter.getPatternCount(); - if (ibdweights == null) { - ibdweights = new double[treeModel.getExternalNodeCount()]; - ibdForward = new double[nodeCount][stateCount * patternCount]; - ibdBackward = new double[nodeCount][stateCount * patternCount]; - diag = new double[stateCount]; - } - - - forwardIBD(); - backwardIBD(null); - int numTips = treeModel.getExternalNodeCount(); - double[] patternWeights = likelihoodReporter.getPatternWeights(); - double total = 0.0; - for (int i = 0; i < patternCount; ++i) { - total += patternWeights[i]; - } - - for (int i = 0; i < numTips; ++i) { - double[] posteriors = likelihoodReporter.getPosteriors(i); - - ibdweights[i] = 0; - for (int pattern = 0; pattern < patternCount; ++pattern) { - for (int j = 0; j < stateCount; ++j) { - ibdweights[i] += ibdBackward[i][pattern * stateCount + j] * posteriors[pattern * stateCount + j] * patternWeights[pattern] / total; - } - } - } - } - - protected void getDiagonalRates(double[] diagonalRates) { - double kappa = substitutionModel.getKappa(); - double[] freq = substitutionModel.getFrequencyModel().getFrequencies(); - double mutationRate = mutationParameter.getParameterValue(0); - double beta = 0.5 / ((freq[0] + freq[2]) * (freq[1] + freq[3]) + kappa * (freq[0] * freq[2] + freq[1] * freq[3])); - - diagonalRates[0] = ((freq[1] + freq[3]) + freq[2] * kappa) * mutationRate * beta; - diagonalRates[1] = ((freq[0] + freq[2]) + freq[3] * kappa) * mutationRate * beta; - diagonalRates[2] = ((freq[1] + freq[3]) + freq[0] * kappa) * mutationRate * beta; - diagonalRates[3] = ((freq[0] + freq[2]) + freq[1] * kappa) * mutationRate * beta; - } - - TreeTrait avgPosteriorIBDWeight = new TreeTrait.D() { - public String getTraitName() { - return "AvgPosteriorIBDWeight"; - } - - public Intent getIntent() { - return Intent.NODE; - } - - public Double getTrait(Tree tree, NodeRef node) { - if (!weightsKnown) { - expectedIBD(); - weightsKnown = true; - } - if (tree.isExternal(node)) { - int nodeNum = node.getNumber(); - return ibdweights[nodeNum] + 1; - } - return null; - } - }; - - public TreeTrait[] getTreeTraits() { - return new TreeTrait[] { avgPosteriorIBDWeight }; - } - - public TreeTrait getTreeTrait(String key) { - // ignore the key - it must be the one they wanted, no? - return avgPosteriorIBDWeight; - } - - /** - * The XML parser - */ - - public static final String IBD_REPORTER_LIKELIHOOD = "avgPosteriorIBDReporter"; - public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { - - public String getParserName() { - return IBD_REPORTER_LIKELIHOOD; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - - TreeModel treeModel = (TreeModel) xo.getChild(TreeModel.class); - Parameter mutationParameter = (Parameter) xo.getChild(Parameter.class); - AbstractSubstitutionModel substitutionModel = - (AbstractSubstitutionModel) xo.getChild(AbstractSubstitutionModel.class); - - BranchRateModel branchRateModel = (BranchRateModel) xo.getChild(BranchRateModel.class); - if (branchRateModel == null) { - branchRateModel = new DefaultBranchRateModel(); - } - - NodePosteriorTreeLikelihood likelihoodReporter = (NodePosteriorTreeLikelihood) xo.getChild(NodePosteriorTreeLikelihood.class); - - return new AvgPosteriorIBDReporter(likelihoodReporter, mutationParameter, treeModel, branchRateModel, substitutionModel); - } - - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - - public String getParserDescription() { - return "This element represents a reporter for average expected number of tips ibd conditional on observed patterns."; - } - - public Class getReturnType() { - return Likelihood.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{ - new ElementRule(TreeModel.class), - new ElementRule(BranchRateModel.class, true), - new ElementRule(AbstractSubstitutionModel.class), - new ElementRule(Parameter.class), - new ElementRule(NodePosteriorTreeLikelihood.class) - }; - }; - - protected void handleModelChangedEvent(Model model, Object object, int index) { - if (model == branchRateModel || model == treeModel || model == substitutionModel || model == likelihoodReporter) { - weightsKnown = false; - } else { - System.err.println("Weird call back to IBDReporter from " + model.getModelName()); - } - } - - protected final void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) { - if (variable == mutationParameter) { - weightsKnown = false; - } else { - System.err.println("Weird call back to IBDReporter from " + variable.getVariableName()); - } - } - - protected void storeState() { - } - - protected void restoreState() { - } - - protected void acceptState() { - } -} \ No newline at end of file diff --git a/src/dr/oldevomodel/ibd/HKYRates.java b/src/dr/oldevomodel/ibd/HKYRates.java deleted file mode 100644 index f16c77d746..0000000000 --- a/src/dr/oldevomodel/ibd/HKYRates.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * HKYRates.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.ibd; - -import dr.oldevomodel.substmodel.FrequencyModel; -import dr.oldevomodel.substmodel.HKY; -import dr.inference.model.Parameter; - -/** - * Package: dr.evomodel.ibd - * Description: - *

- *

- * Created by - * avaleks (alexander.alekseyenko@gmail.com) - * Date: 05-Aug-2008 - * Time: 09:32:35 - */ -public class HKYRates extends HKY { - /** - * Constructor - */ - public HKYRates(Parameter kappaParameter, FrequencyModel freqModel) { - super(kappaParameter, freqModel); - } - - public double[] getRelativeRates(double[] rateMatrix) { - double kappa = getKappa(); - double[] freq = getFrequencyModel().getFrequencies(); - // A - C - G - T - rateMatrix[0] = -(freq[1] + freq[3]) - freq[2] * kappa; - rateMatrix[1] = freq[1]; - rateMatrix[2] = freq[2] * kappa; - rateMatrix[3] = freq[3]; - - rateMatrix[4] = freq[0]; - rateMatrix[5] = -(freq[0] + freq[2]) - freq[3] * kappa; - rateMatrix[6] = freq[2]; - rateMatrix[7] = freq[3] * kappa; - - rateMatrix[8] = freq[0] * kappa; - rateMatrix[9] = freq[1]; - rateMatrix[10] = -(freq[1] + freq[3]) - freq[0] * kappa; - rateMatrix[11] = freq[3]; - - rateMatrix[12] = freq[0]; - rateMatrix[13] = freq[1] * kappa; - rateMatrix[14] = freq[2]; - rateMatrix[15] = -(freq[0] + freq[1]) - freq[1] * kappa; - - - return rateMatrix; - } -} diff --git a/src/dr/oldevomodel/ibd/IBDReporter.java b/src/dr/oldevomodel/ibd/IBDReporter.java deleted file mode 100644 index 264c860427..0000000000 --- a/src/dr/oldevomodel/ibd/IBDReporter.java +++ /dev/null @@ -1,293 +0,0 @@ -/* - * IBDReporter.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.ibd; - -import dr.evolution.tree.NodeRef; -import dr.evolution.tree.Tree; -import dr.evolution.tree.TreeTrait; -import dr.evolution.tree.TreeTraitProvider; -import dr.evomodel.branchratemodel.BranchRateModel; -import dr.evomodel.branchratemodel.DefaultBranchRateModel; -import dr.oldevomodel.substmodel.AbstractSubstitutionModel; -import dr.oldevomodel.substmodel.HKY; -import dr.evomodel.tree.TreeModel; -import dr.inference.model.*; -import dr.xml.*; - -/** - * Package: dr.evomodel.ibd - * Description: - *

- *

- * Created by - * avaleks (alexander.alekseyenko@gmail.com) - * Date: 04-Aug-2008 - * Time: 13:46:33 - */ -public class IBDReporter extends AbstractModel implements TreeTraitProvider { - - protected double[] ibdweights; - protected double[][] ibdForward; - protected double[][] ibdBackward; - protected double[] diag; - protected boolean weightsKnown; - protected HKY substitutionModel; - protected TreeModel treeModel; - protected BranchRateModel branchRateModel; - protected Parameter mutationParameter; - - IBDReporter(Parameter mutationParameter, TreeModel treeModel, BranchRateModel branchRateModel, AbstractSubstitutionModel substitutionModel) { - super("IBDReporter"); - this.substitutionModel = (HKY) substitutionModel; - addModel(this.substitutionModel); - this.treeModel = treeModel; - addModel(this.treeModel); - this.branchRateModel = branchRateModel; - addModel(this.branchRateModel); - this.mutationParameter = mutationParameter; - addVariable(this.mutationParameter); - } - - public void forwardIBD() { - int numNodes = treeModel.getNodeCount(); - int stateCount = substitutionModel.getStateCount(); - getDiagonalRates(diag); - for (int nodeId = 0; nodeId < numNodes; ++nodeId) { - NodeRef node = treeModel.getNode(nodeId); - NodeRef parent = treeModel.getParent(node); - if (parent == null) { // handle the root - - } else if (treeModel.isExternal(node)) { // Handle the tip - double branchTime = branchRateModel.getBranchRate(treeModel, node) * (treeModel.getNodeHeight(parent) - treeModel.getNodeHeight(node)); - - for (int state = 0; state < stateCount; ++state) { - ibdForward[nodeId][state] = Math.exp(-diag[state] * branchTime); - } - } else { // Handle internal node - double branchTime = branchRateModel.getBranchRate(treeModel, node) * (treeModel.getNodeHeight(parent) - treeModel.getNodeHeight(node)); - - int childCount = treeModel.getChildCount(node); - for (int state = 0; state < stateCount; ++state) { - ibdForward[nodeId][state] = 0; - for (int child = 0; child < childCount; ++child) { - int childNodeId = treeModel.getChild(node, child).getNumber(); - ibdForward[nodeId][state] += ibdForward[childNodeId][state]; - } - ibdForward[nodeId][state] *= Math.exp(-diag[state] * branchTime); - } - } - } - } - - public void backwardIBD(NodeRef node) { - int stateCount = substitutionModel.getStateCount(); - if (node == null) { - node = treeModel.getRoot(); - int nodeId = node.getNumber(); - for (int state = 0; state < stateCount; ++state) { - ibdBackward[nodeId][state] = 0; - } - } - getDiagonalRates(diag); - int childCount = treeModel.getChildCount(node); - int nodeId = node.getNumber(); - for (int child = 0; child < childCount; ++child) { - NodeRef childNode = treeModel.getChild(node, child); - int childNodeId = childNode.getNumber(); - double branchTime = branchRateModel.getBranchRate(treeModel, childNode) * (treeModel.getNodeHeight(node) - treeModel.getNodeHeight(childNode)); - for (int state = 0; state < stateCount; ++state) { - ibdBackward[childNodeId][state] = ibdBackward[nodeId][state]; - for (int sibling = 0; sibling < childCount; ++sibling) { - if (sibling != child) { - int siblingId = treeModel.getChild(node, sibling).getNumber(); - ibdBackward[childNodeId][state] += ibdForward[siblingId][state]; - } - } - ibdBackward[childNodeId][state] *= Math.exp(-diag[state] * branchTime); - } - } - for (int child = 0; child < childCount; ++child) { - NodeRef childNode = treeModel.getChild(node, child); - backwardIBD(childNode); - } - - } - - public void expectedIBD() { - int stateCount = substitutionModel.getStateCount(); - int nodeCount = treeModel.getNodeCount(); - if (ibdweights == null) { - ibdweights = new double[treeModel.getExternalNodeCount()]; - ibdForward = new double[nodeCount][stateCount]; - ibdBackward = new double[nodeCount][stateCount]; - diag = new double[stateCount]; - } - - double[] freq = substitutionModel.getFrequencyModel().getFrequencies(); - forwardIBD(); - backwardIBD(null); - int numTips = treeModel.getExternalNodeCount(); - for (int i = 0; i < numTips; ++i) { - ibdweights[i] = 0; - for (int j = 0; j < stateCount; ++j) { - ibdweights[i] += ibdBackward[i][j] * freq[j]; - } - } - } - - protected void getDiagonalRates(double[] diagonalRates) { - double kappa = substitutionModel.getKappa(); - double[] freq = substitutionModel.getFrequencyModel().getFrequencies(); - double mutationRate = mutationParameter.getParameterValue(0); - double beta = 0.5 / ((freq[0] + freq[2]) * (freq[1] + freq[3]) + kappa * (freq[0] * freq[2] + freq[1] * freq[3])); - - diagonalRates[0] = ((freq[1] + freq[3]) + freq[2] * kappa) * mutationRate * beta; - diagonalRates[1] = ((freq[0] + freq[2]) + freq[3] * kappa) * mutationRate * beta; - diagonalRates[2] = ((freq[1] + freq[3]) + freq[0] * kappa) * mutationRate * beta; - diagonalRates[3] = ((freq[0] + freq[2]) + freq[1] * kappa) * mutationRate * beta; - } - - TreeTrait ibdWeight = new TreeTrait.D() { - public String getTraitName() { - return "IBDWeight"; - } - - public Intent getIntent() { - return Intent.NODE; - } - - public Double getTrait(Tree tree, NodeRef node) { - if (!weightsKnown) { - expectedIBD(); - weightsKnown = true; - } - if (tree.isExternal(node)) { - return getIBDWeight(tree, node); - } - return null; - } - }; - - public TreeTrait[] getTreeTraits() { - return new TreeTrait[] { ibdWeight }; - } - - public TreeTrait getTreeTrait(String key) { - // ignore the key - it must be the one they wanted, no? - return ibdWeight; - } - - 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; - } - - /** - * The XML parser - */ - - public static final String IBD_REPORTER_LIKELIHOOD = "ibdReporter"; - public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { - - public String getParserName() { - return IBD_REPORTER_LIKELIHOOD; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - - TreeModel treeModel = (TreeModel) xo.getChild(TreeModel.class); - Parameter mutationParameter = (Parameter) xo.getChild(Parameter.class); - AbstractSubstitutionModel substitutionModel = - (AbstractSubstitutionModel) xo.getChild(AbstractSubstitutionModel.class); - - BranchRateModel branchRateModel = (BranchRateModel) xo.getChild(BranchRateModel.class); - if (branchRateModel == null) { - branchRateModel = new DefaultBranchRateModel(); - } - - return new IBDReporter(mutationParameter, treeModel, branchRateModel, substitutionModel); - } - - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - - public String getParserDescription() { - return "This element represents a reporter for expected number of tips ibd."; - } - - public Class getReturnType() { - return Likelihood.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{ - new ElementRule(TreeModel.class), - new ElementRule(BranchRateModel.class, true), - new ElementRule(AbstractSubstitutionModel.class), - new ElementRule(Parameter.class) - }; - }; - - protected void handleModelChangedEvent(Model model, Object object, int index) { - if (model == branchRateModel || model == treeModel || model == substitutionModel) { - weightsKnown = false; - } else { - System.err.println("Weird call back to IBDReporter from " + model.getModelName()); - } - } - - protected final void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) { - if (variable == mutationParameter) { - weightsKnown = false; - } else { - System.err.println("Weird call back to IBDReporter from " + variable.getVariableName()); - } - } - - protected void storeState() { - } - - protected void restoreState() { - } - - protected void acceptState() { - } - -} diff --git a/src/dr/oldevomodel/indel/HomologyRecursion.java b/src/dr/oldevomodel/indel/HomologyRecursion.java deleted file mode 100644 index b50fe4b9ca..0000000000 --- a/src/dr/oldevomodel/indel/HomologyRecursion.java +++ /dev/null @@ -1,680 +0,0 @@ -/* - * HomologyRecursion.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.indel; - - -import dr.evolution.alignment.Alignment; -import dr.evolution.datatype.DataType; -import dr.evolution.tree.NodeRef; -import dr.evolution.tree.Tree; -import dr.oldevomodel.substmodel.SubstitutionModel; -import dr.math.BFloat; - -import java.util.HashMap; - -public class HomologyRecursion { - - /** Array of 0-1 vectors, encoding the alignment as columns */ - IntMathVec[] iAlignment; - - /** Array of arrays, encoding the sequences (in rows). No gaps. Range [0,iNumNucs). */ - int[][] iSequences; - - /** - * Array encoding the tree. - * iParent[iChild] is the parent of iChild, except -1 = root's parent. - * Parent must be > child, and leaf indices must correspond to indices into alignment vectors - */ - private int[] iParent; - - /** Length of incoming branches to each tree node. Root is assumed to be infinity */ - private double[] iTau; - - /** Parameters of the TKF91 model */ - double iLambda; - double iMu; - - /** Number of nucleotides */ - int iNumNucs; - - /** Transition probability matrices, iTrans[node][from][to], for each tree node except root */ - double[][][] iTrans; - - /** Equilibrium probabilities for nucleotides. */ - double[] iEquil; - - /** Intermediate results for TKF91 model, initialised in recursion(), used in treeRecursion() */ - private double iH[], iN[], iB[], iE[]; - - /** TKF91-related result for initialising the DP table */ - private double iInitial; - - /** Class that implements a fast version of treeLikelihood */ - private NativeTreeLikelihood iNativeMethod; - - /** Labels used in local array iState[] */ - static private final int eFree = 0, ePossible = 1, eEdgeUsed = 2, eUsed = 3; - - /** Max dimension of unalignable region */ - static private final int cMaxUnalignDimension = 10; - - /** Minimum edge length */ - static private final double MIN_EDGE_LENGTH = 1e-3; - - /** Error count */ - static int sBigUnalignableRegion = 0; - - String PrintDouble(double[] d) { - String str = ""; - for(double aD : d) { - str = str + aD + " "; - } - return str; - } - - void checkConsistency() { - // Checks whether variables are init'ed properly - int iCols = iAlignment.length; - int iRows = iAlignment[0].iV.length; - String iErr = ""; - IntMathVec iPos = new IntMathVec( iRows ); - for (int i=0; i=iNumNucs)) { - iErr = "Nucleotide codes in iSequences not in range, " + iSequences[j][i] + "not in [0,"+(iNumNucs-1)+"]"; - } - } - } - int[] iChildren = new int[ iParent.length ]; - for (int i=0; i= numStates) ? 0 : 1); - } - iAlignment[i] = new IntMathVec(column); - } - } - - /** - * Initializes the iSequence array from the given alignment. - */ - private void initSequences(Alignment alignment, int[] treeIndex) { - - int numSeqs = alignment.getSequenceCount(); - DataType dataType = alignment.getDataType(); - int numStates = dataType.getStateCount(); - - iSequences = new int[numSeqs][]; - - for (int i = 0; i < numSeqs; i++) { - - int seqLength = 0; - for (int j =0; j < alignment.getSiteCount(); j++) { - int state = alignment.getState(i, j); - if (state>=0 && state=0 && state iTable = new HashMap(); - - IntMathVec[] iAlignment = new IntMathVec[iLen]; - for (int i=iStartCol; i<=iEndCol; i++) { - iAlignment[i-iStartCol] = new IntMathVec(iLeaves); - for (int j=0; j= 0; --iPosPtr) { - int iCurPtr = iPossibles[ iPosPtr ]; - if (iState[ iCurPtr ] == ePossible) { - iState[ iCurPtr ] = eEdgeUsed; - iNewPos.add( iAlignment[ iCurPtr ] ); - // Compute signature vector - iSignature.addMultiple( iAlignment[ iCurPtr ], iPosPtr+1 ); - // Signal: non-zero combination found, and stop - iFoundNonZero = true; - iPosPtr = 0; - } else { - // It was eEdgeUsed (i.e., digit == 1), so reset digit and continue - iState[ iCurPtr ] = ePossible; - iNewPos.subtract( iAlignment[ iCurPtr ] ); - iSignature.addMultiple( iAlignment[ iCurPtr ], -iPosPtr-1 ); - } - } - - if (iFoundNonZero) { - //System.out.print("Reading from pos " + iPos); - int iLeft = iTable.get(iPos); - //System.out.print(" left=" + iLeft); - int iRight; - Object iRightObj = iTable.get( iNewPos ); - if (iRightObj == null) { - iRight = 0; - iUnusedPos = true; - } else { - iRight = (Integer) iRightObj; - iUnusedPos = false; - } - //System.out.print(" right=" + iRight); - iRight += iLeft; - //System.out.print(" sig=" + iSignature); - // And store - //System.out.println(" Storing pos " + iNewPos); - // If we are storing a value at a previously unused position, make sure we use a fresh key object - if (iUnusedPos) { - iTable.put(iNewPos.clone(), iRight); - } else { - iTable.put( iNewPos, iRight); - } - } - - } while (iFoundNonZero); - - // Now find next entry in DP table. Use farthest unused vector - --iPtr; - while (iPtr >= 0 && iState[iPtr] != ePossible) { - // Undo any possible used vector that we encounter - if (iState[iPtr] == eUsed) { - iPos.subtract( iAlignment[iPtr] ); - iState[iPtr] = eFree; - } - --iPtr; - } - - if (iPtr == -1) { - // No more unused vectors, so we also fell through the edge loop above, - // hence iNewPos contains the final position - return iTable.get(iNewPos); - } - - - // Now use this farthest-out possible vector - iState[iPtr] = eUsed; - iPos.add( iAlignment[iPtr] ); - if (iPtr <= iFirstNotUsed) - iFirstNotUsed++; - - } while (true); - - } // recursion - - - - /** - * @returns the log of the hastings ratio - * I cannot guarantee it works, however :) Istvan 12/06/2003 - * Version 2.0 It returns with a statistically correct Hastings ratio - */ - public double propose(int[][] iAlignment, double[][][] iProbs, double[] iBasefreqs, int[] iParent, double[] iTau, int[][] returnedAlignment, double iP, double exponent, double gapPenalty) { - - int iL1; - // length of the cut out alignment - int iPos; - // position of the cut out alignment (first index) - int iL2; - // length of the obtained alignment - int[][][] iProfile = new int[iParent.length][iParent.length][cMaxlength]; - // profiles obtained in the proposal - int[][] iTempProfile = new int[iParent.length][cMaxlength]; - // temporary profile since at the stochastic traceback we get the profile in reverse order - int[] iXP = new int[iParent.length], iYP = new int[iParent.length]; - // length of a profile (X) and number of sequences involved into the profile (Y) - double iTempdouble1 = 0.0, iTempdouble2 = 0.0, iTempdouble3 = 0.0, iTempdouble4 = 0.0; - // temporal variables in the dp recursion and stochastic traceback - double iProposalLoglikelihood = 0.0; - // loglikelihood of the proposal, what else? - int iTempint1; - // temporal variables for counting gaps, iTempint1 is also used at child-sorting - double[][] iScoring = new double[iProbs[0].length][iProbs[0][0].length]; - // scoring table for the dynamic programming - int[] iChild1 = new int[iParent.length], iChild2 = new int[iParent.length]; - // these arrays make the work on the tree easier - int[] iSorter = new int[iParent.length]; - // this array helps at sorting children so the profile of root will be the correct multiple alignment - boolean iTempBoole; - // temporary boolean variable for checking all-gap columns - int[][] iProfileNumber = new int[iParent.length][iAlignment.length]; - - - //Testing preconditions - if (iP <= 0.0 || iP >= 1.0) throw new IllegalArgumentException("iP must be in range (0,1)"); - if (exponent < 1.0) throw new IllegalArgumentException("exponent must be in range [1,+infinity)"); - if (gapPenalty >= 0.0) throw new IllegalArgumentException("gapPenalty must be in range (-infinity,0)"); - - cGap = gapPenalty; - cBasis = exponent; - - - - /* obtaining iChild1 and iChild2 */ - - for(int i = 0; i < iParent.length - 1; i++) { - if(iChild1[iParent[i]] == 0) { - iChild1[iParent[i]] = i; - } else { - iChild2[iParent[i]] = i; - } - } - - // now sorting children... - - for(int i = 0; i < iAlignment.length; i++) - iSorter[i]=i; - // iSorter for leaves - for(int i = iAlignment.length; i < iParent.length; i++) { - if(iSorter[iChild1[i]] > iSorter[iChild2[i]]) - iSorter[i] = iSorter[iChild2[i]]; - else - iSorter[i] = iSorter[iChild1[i]]; - // iSorter for internal nodes, it gets the lower value - - if(iSorter[iChild1[i]] > iSorter[iChild2[i]]) { - // iChild1[i] has the smaller iSorter value - // this guarantees that the root's profile contains the sequences in the proper order - iTempint1 = iChild1[i]; - iChild1[i] = iChild2[i]; - iChild2[i] = iTempint1; - } - } - /* cutting a part of the alignment */ - - // obtaining the length of the cut out part (iL1) and the first index (iPos) - for(iL1=1; iL1 < iAlignment[0].length && Math.random() > iP; iL1++); - - - //iL1 = 1; - iPos = r.nextInt(iAlignment[0].length - iL1 + 1); - - //System.out.println("Window size = " + iL1); - // collecting the cut out sequences from the alignment - // they will be the first profiles - for(int i = 0; i < iAlignment.length; i++) { - iYP[i] = 1; - for(int j = iPos; j iTempdouble2) - iDP[i][j] = iTempdouble1; - else - iDP[i][j] = iTempdouble2; - if(iTempdouble3 > iDP[i][j]) - iDP[i][j] = iTempdouble3; - } - - - // traceback, now not stochastic - int i = iXP[iChild1[k]]; - int j = iXP[iChild2[k]]; - int n = iXP[k]; - while(n > 0) { - - - if(i > 0){ - //System.out.println("i = " + i + "; j = " + j); - - iTempdouble1 = iDP[i - 1][j] + cGap; - } - - - - if(j > 0) { - //System.out.println("i = " + i + "; j = " + j); - - iTempdouble2 = iDP[i][j - 1] + cGap; - } - - - if(i > 0 && j > 0) { - int iCounter = 0; - iTempdouble3 = 0.0; - for(int l = 0; l < iYP[iChild1[k]]; l++) - for(int m = 0; m < iYP[iChild2[k]]; m++) { - if(iProfile[iChild1[k]][l][i - 1] != cGapsymbol && iProfile[iChild2[k]][m][j - 1] != cGapsymbol){ - iTempdouble3 += iScoring[iProfile[iChild1[k]][l][i - 1]][iProfile[iChild2[k]][m][j - 1]]; - iCounter++; - } - } - iTempdouble3 = iDP[i - 1][j - 1] + iTempdouble3/iCounter; - } - - - // normalising - iTempdouble4 = 0.0; - if(i > 0) - iTempdouble4 += Math.exp(iTempdouble1 * Math.log(cBasis)); - if(j > 0) - iTempdouble4 += Math.exp(iTempdouble2 * Math.log(cBasis)); - if(i > 0 && j > 0) - iTempdouble4 += Math.exp(iTempdouble3 * Math.log(cBasis)); - - - if(i > 0) - iTempdouble1 = Math.exp(iTempdouble1 * Math.log(cBasis))/iTempdouble4; - else - iTempdouble1 = 0.0; - - - if(j > 0) - iTempdouble2 = Math.exp(iTempdouble2 * Math.log(cBasis))/iTempdouble4; - else - iTempdouble2 = 0.0; - - - if(i > 0 && j > 0) - iTempdouble3 = Math.exp(iTempdouble3 * Math.log(cBasis))/iTempdouble4; - else - iTempdouble3 = 0.0; - - //System.out.println("Sum in the second DP: " + (iTempdouble1+iTempdouble2+iTempdouble3)); - - - // finding the proper step (all-gap subcolumns tell us the way - iTempBoole = true; - for(int l = 0; l < iYP[iChild1[k]] && iTempBoole; l++) - iTempBoole = (iProfile[k][l][n-1] == cGapsymbol); - - - if(iTempBoole) { - // all the first part is gap, so we decrease j - j--; - iProposalLoglikelihood += Math.log(iTempdouble2); - n--; - } - else { - iTempBoole = true; - for(int l = iYP[iChild1[k]]; l < iYP[iChild1[k]] + iYP[iChild2[k]] && iTempBoole; l++) - iTempBoole = (iProfile[k][l][n-1] == cGapsymbol); - if(iTempBoole) { - // all the second part is gap, so we decrease i - i--; - iProposalLoglikelihood += Math.log(iTempdouble1); - n--; - } - else { - // no all-gap subcolumn, decreasing both i and j; - i--; - j--; - iProposalLoglikelihood += Math.log(iTempdouble3); - n--; - } - } - - - } // end of traceback - - //System.out.println("iProposalLogLikelihood2=" + iProposalLoglikelihood); - } // end of k - - //System.out.println("iL1=" + iL1); - //System.out.println("iL2=" + iL2); - return iProposalLoglikelihood + (iL1 - iL2)*Math.log(1.0-iP); - } -} \ No newline at end of file diff --git a/src/dr/oldevomodel/indel/NativeTreeLikelihood.java b/src/dr/oldevomodel/indel/NativeTreeLikelihood.java deleted file mode 100644 index 9576d745d7..0000000000 --- a/src/dr/oldevomodel/indel/NativeTreeLikelihood.java +++ /dev/null @@ -1,176 +0,0 @@ -/* - * NativeTreeLikelihood.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.indel; - - - - -/** - * NativeTreeLikelihood - calls an implementation of HomologyRecursion.treeRecursion in C. - * - * @author Gerton Lunter - * - * 10/9/2003 - * - */ - -public class NativeTreeLikelihood { - - private static boolean isNativeAvailable = false; - private int[][] iSequences; // rest are references to existing arrays - private int iNN; - private int iMUD; - private long iStaticDataHandle; - - static { - try { - - System.loadLibrary("NativeTreeLikelihood"); - System.err.println("Fast TKF91 homology integrator code found"); - isNativeAvailable = true; - - } catch (UnsatisfiedLinkError e) { - - System.err.println("Using Java TKF91 homology integrator code"); - - } - } - - - /** - * Constructor - * - */ - - public NativeTreeLikelihood() { } - - - /** - * Hello, anybody? - * - */ - - public boolean isAvailable() { - return isNativeAvailable; - } - - /** - * Initialisation. Returns with 'handle' (actually a pointer) to static data. - * - */ - - private native long nativeInit(int[] iParent, double[] iEquil, double[] iTrans, - double[] iH, double[] iN, double[] iE, double[] iB); - - /** - * The actual recursion. 'iSD' is the handle returned by nativeInit. - * - */ - - private native double nativeTreeRecursion(int[] iSignature, int[] iColumn, int iNumNucs, int iMUD, long iSD); - - /** - * Relinquishes handle. - * - */ - - private native void nativeDestruct(long iSD); - - - /** - * Initialiser - * - */ - - public void init(int iNumNucs, int iMaxUnalignDimension, int[] iParent, double[] iEquil, double[][][] iTrans, - int[][] iSequences0, - double[] iN, double[] iH, double[] iE, double[] iB) - { - if (!isNativeAvailable) - return; - - // copy data into local variables - iNN = iNumNucs; - iMUD = iMaxUnalignDimension; - iSequences = iSequences0; - - // translate iTrans[][][] array into flat array - int iNumNodes = iTrans.length; - double[] iFlatTrans = new double[ iNN*iNN*iNumNodes ]; - for (int i=0; i - *

- * Created by - * - * @author Alexander V. Alekseyenko (alexander.alekseyenko@gmail.com) - * Date: 10/14/13 - * Time: 12:13 PM - */ -public class LineageModelLikelihood extends AbstractModelLikelihood { - - protected int numSamples; - protected int numSNPs; - protected int numLineages; - protected double normalization; - protected MatrixParameter mixtureMatrix; - protected LineageSitePatterns patterns; - protected Parameter errorRate; - protected MatrixParameter refData; - protected MatrixParameter nonData; - - public LineageModelLikelihood(LineageSitePatterns patterns, MatrixParameter mixtureMatrix, Parameter errorRate, - MatrixParameter refData, MatrixParameter nonData) - { - super(LINEAGE_MODEL); - - numSamples = mixtureMatrix.getRowDimension(); - numSNPs = patterns.getSiteCount(); - numLineages = mixtureMatrix.getColumnDimension(); - - this.mixtureMatrix = mixtureMatrix; - this.patterns = patterns; - this.errorRate = errorRate; - this.refData = refData; - this.nonData = nonData; - - normalization = 0.0; - for (int j = 0; j < numSNPs; j++){ - for (int i =0; i < numSamples; i++){ - normalization += dr.math.Binomial.logChoose(Math.round(refData.getParameterValue(i,j) + - nonData.getParameterValue(i,j)), Math.round(nonData.getParameterValue(i,j))); - } - } - - addVariable(errorRate); - addModel(patterns); - addVariable(mixtureMatrix); - } - @Override - protected void handleModelChangedEvent(Model model, Object object, int index) { - if(model == mixtureMatrix || model == patterns || model == errorRate) - makeDirty(); - } - - @Override - protected void handleVariableChangedEvent(Variable variable, int index, Variable.ChangeType type) { - } - - @Override - protected void storeState() { - storedLogLikelihood = logLikelihood; - storedLikelihoodKnown = likelihoodKnown; - } - - @Override - protected void restoreState() { - logLikelihood = storedLogLikelihood; - likelihoodKnown = storedLikelihoodKnown; - } - - @Override - protected void acceptState() { - } - - public Model getModel() { - return this; - } - - public final double getLogLikelihood() { - if (!likelihoodKnown) { - logLikelihood = calculateLogLikelihood(); - likelihoodKnown = true; - } - return logLikelihood; - } - - protected double calculateLogLikelihood() { - double logLike=normalization, p; - - int i, j, k; - - for (j = 0; j < numSNPs; j++) - { - for (i =0; i < numSamples; i++) - { - p = 0; - for (k =0; k < numLineages; k++) - { - p += mixtureMatrix.getParameterValue(k,i)*(1-patterns.getState(k, j)); - } - p = p - 2*errorRate.getParameterValue(0)*p +errorRate.getParameterValue(0); - logLike += refData.getParameterValue(i,j)*Math.log(p) + nonData.getParameterValue(i,j)*Math.log(1-p); - } - } - return logLike; - } - - - public void makeDirty() { - likelihoodKnown = false; - } - protected boolean likelihoodKnown = false; - protected double logLikelihood = 0; - private double storedLogLikelihood; - private boolean storedLikelihoodKnown = false; - - // ************************************************************** - // XMLElement IMPLEMENTATION - // ************************************************************** - -// public Element createElement(Document d) { -// throw new RuntimeException("Not implemented yet!"); -// } - - public static final String LINEAGE_MODEL = "LINEAGE_MODEL"; - public static final String LINEAGE_MODEL_PARSER = "lineageModel"; - public static final String MIXTURE = "mixture"; - public static final String REFERENCE = "ref"; - public static final String NON_REFERENCE = "non"; - - public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { - - public String getParserName() { - return LINEAGE_MODEL_PARSER; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - MatrixParameter nonData=null, refData=null, mixtureMatrix=null; - Parameter errorRate=null; - LineageSitePatterns patterns=null; - - for(int i=0; i - *

- * Created by - * - * @author Alexander V. Alekseyenko (alexander.alekseyenko@gmail.com) - * Date: 10/14/13 - * Time: 11:03 AM - */ -public class LineageSitePatterns extends AbstractModel implements SiteList, dr.util.XHTMLable{ - public static final String LINEAGE_PATTERNS = "LineagePatterns"; - - /** - * the source alignment - */ - protected SiteList siteList = null; - - /** - * number of sites - */ - protected int siteCount = 0; - - /** - * number of patterns - */ - protected int patternCount = 0; - - /** - * length of site patterns - */ - protected int patternLength = 0; - - /** - * site -> site pattern - */ - protected int[] sitePatternIndices; - - /** - * count of invariant patterns - */ - protected int invariantCount; - - /** - * weights of each site pattern - */ - protected double[] weights; - - /** - * site patterns [site pattern][taxon] - */ - protected int[][] patterns; - - protected int from, to, every; - - protected boolean strip = true; // Strip out completely ambiguous sites - - protected boolean unique = true; // Compress into weighted list of unique patterns - - /** - * Constructor - */ - public LineageSitePatterns(Alignment alignment) { - this(alignment, null, 0, 0, 1); - } - - /** - * Constructor - */ - public LineageSitePatterns(Alignment alignment, TaxonList taxa) { - this(alignment, taxa, 0, 0, 1); - } - - /** - * Constructor - */ - public LineageSitePatterns(Alignment alignment, int from, int to, int every) { - this(alignment, null, from, to, every); - } - -// /** -// * Constructor for dnds -// */ -// public SitePatterns(Alignment alignment, int from, int to, int every, boolean unique) { -// this(alignment, null, from, to, every, unique); -// } - - /** - * Constructor - */ - - public LineageSitePatterns(Alignment alignment, TaxonList taxa, int from, int to, int every) { - this(alignment,taxa,from,to,every,true); - } - - public LineageSitePatterns(Alignment alignment, TaxonList taxa, int from, int to, int every, boolean strip) { - this(alignment, taxa, from, to, every, strip, true); - } - - public LineageSitePatterns(Alignment alignment, TaxonList taxa, int from, int to, int every, boolean strip, boolean unique) { - super(LINEAGE_PATTERNS); - if (taxa != null) { - SimpleAlignment a = new SimpleAlignment(); - - for (int i = 0; i < alignment.getSequenceCount(); i++) { - if (taxa.getTaxonIndex(alignment.getTaxonId(i)) != -1) { - a.addSequence(alignment.getSequence(i)); - } - } - - alignment = a; - } - this.strip = strip; - this.unique = unique; - - setPatterns(alignment, from, to, every); - } - - /** - * Constructor - */ - public LineageSitePatterns(SiteList siteList) { - this(siteList, -1, -1, 1); - } - - /** - * Constructor - */ - public LineageSitePatterns(SiteList siteList, int from, int to, int every) { - super(LINEAGE_PATTERNS); - setPatterns(siteList, from, to, every); - } - - public SiteList getSiteList() { - return siteList; - } - - public int getFrom() { - return from; - } - - public int getTo() { - return to; - } - - public int getEvery() { - return every; - } - - public void setFrom(int from) { - setPatterns(getSiteList(), from, getTo(), getEvery()); - } - - public void setTo(int to) { - setPatterns(getSiteList(), getFrom(), to, getEvery()); - } - - public void setEvery(int every) { - setPatterns(getSiteList(), getFrom(), getTo(), every); - } - - /** - * sets up pattern list using an alignment - */ - public void setPatterns(SiteList siteList, int from, int to, int every) { - - this.siteList = siteList; - this.from = from; - this.to = to; - this.every = every; - - if (siteList == null) { - return; - } - - if (from <= -1) - from = 0; - - if (to <= -1) - to = siteList.getSiteCount() - 1; - - if (every <= 0) - every = 1; - - siteCount = ((to - from) / every) + 1; - - patternCount = 0; - - patterns = new int[siteCount][]; - - sitePatternIndices = new int[siteCount]; - weights = new double[siteCount]; - - invariantCount = 0; - int[] pattern; - - int site = 0; - - for (int i = from; i <= to; i += every) { - pattern = siteList.getSitePattern(i); - - if (!strip || !isInvariant(pattern) || - (!isGapped(pattern) && - !isAmbiguous(pattern) && - !isUnknown(pattern))) { - - sitePatternIndices[site] = addPattern(pattern); - - } else { - sitePatternIndices[site] = -1; - } - site++; - } - } - - /** - * adds a pattern to the pattern list - * - * @return the index of the pattern in the pattern list - */ - private int addPattern(int[] pattern) { - - for (int i = 0; i < patternCount; i++) { - - if (unique && comparePatterns(patterns[i], pattern)) { - - weights[i] += 1.0; - return i; - } - } - - if (isInvariant(pattern)) { - invariantCount++; - } - - int index = patternCount; - patterns[index] = pattern; - weights[index] = 1.0; - patternCount++; - - return index; - } - - /** - * @return true if the pattern is invariant - */ - private boolean isGapped(int[] pattern) { - int len = pattern.length; - - for (int i = 0; i < len; i++) { - if (getDataType().isGapState(pattern[i])) { - return true; - } - } - return false; - } - - /** - * @return true if the pattern is invariant - */ - private boolean isAmbiguous(int[] pattern) { - int len = pattern.length; - - for (int i = 0; i < len; i++) { - if (getDataType().isAmbiguousState(pattern[i])) { - return true; - } - } - return false; - } - - /** - * @return true if the pattern is invariant - */ - private boolean isUnknown(int[] pattern) { - int len = pattern.length; - - for (int i = 0; i < len; i++) { - if (getDataType().isUnknownState(pattern[i])) { - return true; - } - } - return false; - } - - /** - * @return true if the pattern is invariant - */ - private boolean isInvariant(int[] pattern) { - int len = pattern.length; - - int state = pattern[0]; - for (int i = 1; i < len; i++) { - if (pattern[i] != state) { - return false; - } - } - - return true; - } - - /** - * compares two patterns - * - * @return true if they are identical - */ - protected boolean comparePatterns(int[] pattern1, int[] pattern2) { - - int len = pattern1.length; - for (int i = 0; i < len; i++) { - if (pattern1[i] != pattern2[i]) { - return false; - } - } - - return true; - } - - /** - * @return number of invariant sites (these will be first in the list). - */ - public int getInvariantCount() { - return invariantCount; - } - - // ************************************************************** - // SiteList IMPLEMENTATION - // ************************************************************** - - /** - * @return number of sites - */ - public int getSiteCount() { - return siteCount; - } - - /** - * Gets the pattern of site as an array of state numbers (one per sequence) - * - * @return the site pattern at siteIndex - */ - public int[] getSitePattern(int siteIndex) { - final int sitePatternIndice = sitePatternIndices[siteIndex]; - return sitePatternIndice >= 0 ? patterns[sitePatternIndice] : null; - } - - @Override - public double[][] getUncertainSitePattern(int siteIndex) { - throw new UnsupportedOperationException("uncertain patterns not implemented yet"); - } - - /** - * Gets the pattern index at a particular site - * - * @return the patternIndex - */ - public int getPatternIndex(int siteIndex) { - return sitePatternIndices[siteIndex]; - } - - /** - * @return the sequence state at (taxon, site) - */ - public int getState(int taxonIndex, int siteIndex) { - final int sitePatternIndice = sitePatternIndices[siteIndex]; - // is that right? - return sitePatternIndice >= 0 ? patterns[sitePatternIndice][taxonIndex] : getDataType().getGapState(); - } - - @Override - public double[] getUncertainState(int taxonIndex, int siteIndex) { - throw new UnsupportedOperationException("uncertain patterns not implemented yet"); - } - - // ************************************************************** - // PatternList IMPLEMENTATION - // ************************************************************** - - /** - * @return number of patterns - */ - public int getPatternCount() { - return patternCount; - } - - /** - * @return number of states for this siteList - */ - public int getStateCount() { - if (siteList == null) throw new RuntimeException("SitePatterns has no alignment"); - return siteList.getStateCount(); - } - - /** - * Gets the length of the pattern strings which will usually be the - * same as the number of taxa - * - * @return the length of patterns - */ - public int getPatternLength() { - return getTaxonCount(); - } - - /** - * Gets the pattern as an array of state numbers (one per sequence) - * - * @return the pattern at patternIndex - */ - public int[] getPattern(int patternIndex) { - return patterns[patternIndex]; - } - - @Override - public double[][] getUncertainPattern(int patternIndex) { - throw new UnsupportedOperationException("uncertain patterns not implemented yet"); - } - - /** - * @return state at (taxonIndex, patternIndex) - */ - public int getPatternState(int taxonIndex, int patternIndex) { - return patterns[patternIndex][taxonIndex]; - } - - @Override - public double[] getUncertainPatternState(int taxonIndex, int patternIndex) { - throw new UnsupportedOperationException("uncertain patterns not implemented yet"); - } - - /** - * Gets the weight of a site pattern - */ - public double getPatternWeight(int patternIndex) { - return weights[patternIndex]; - } - - /** - * @return the array of pattern weights - */ - public double[] getPatternWeights() { - return weights; - } - - /** - * @return the DataType of this siteList - */ - public DataType getDataType() { - if (siteList == null) throw new RuntimeException("SitePatterns has no alignment"); - return siteList.getDataType(); - } - - /** - * @return the frequency of each state - */ - public double[] getStateFrequencies() { - return PatternList.Utils.empiricalStateFrequencies(this); - } - - @Override - public boolean areUnique() { - return unique; - } - - @Override - public boolean areUncertain() { - return false; - } - - // ************************************************************** - // TaxonList IMPLEMENTATION - // ************************************************************** - - /** - * @return a count of the number of taxa in the list. - */ - public int getTaxonCount() { - if (siteList == null) throw new RuntimeException("SitePatterns has no alignment"); - return siteList.getTaxonCount(); - } - - /** - * @return the ith taxon. - */ - public Taxon getTaxon(int taxonIndex) { - if (siteList == null) throw new RuntimeException("SitePatterns has no alignment"); - return siteList.getTaxon(taxonIndex); - } - - /** - * @return the ID of the ith taxon. - */ - public String getTaxonId(int taxonIndex) { - if (siteList == null) throw new RuntimeException("SitePatterns has no alignment"); - return siteList.getTaxonId(taxonIndex); - } - - /** - * returns the index of the taxon with the given id. - */ - public int getTaxonIndex(String id) { - if (siteList == null) throw new RuntimeException("SitePatterns has no alignment"); - return siteList.getTaxonIndex(id); - } - - /** - * returns the index of the given taxon. - */ - public int getTaxonIndex(Taxon taxon) { - if (siteList == null) throw new RuntimeException("SitePatterns has no alignment"); - return siteList.getTaxonIndex(taxon); - } - - public List asList() { - List taxa = new ArrayList(); - for (int i = 0, n = getTaxonCount(); i < n; i++) { - taxa.add(getTaxon(i)); - } - return taxa; - } - - public Iterator iterator() { - return new Iterator() { - private int index = -1; - - public boolean hasNext() { - return index < getTaxonCount() - 1; - } - - public Taxon next() { - index ++; - return getTaxon(index); - } - - public void remove() { /* do nothing */ } - }; - } - - /** - * @param taxonIndex the index of the taxon whose attribute is being fetched. - * @param name the name of the attribute of interest. - * @return an object representing the named attributed for the given taxon. - */ - public Object getTaxonAttribute(int taxonIndex, String name) { - if (siteList == null) throw new RuntimeException("SitePatterns has no alignment"); - return siteList.getTaxonAttribute(taxonIndex, name); - } - - // ************************************************************** - // Identifiable IMPLEMENTATION - // ************************************************************** - - protected String id = null; - - /** - * @return the id. - */ - public String getId() { - return id; - } - - /** - * Sets the id. - */ - public void setId(String id) { - this.id = id; - } - - // ************************************************************** - // XHTMLable IMPLEMENTATION - // ************************************************************** - - public String toXHTML() { - String xhtml = "

Pattern List pattern count = "; - xhtml += getPatternCount(); - xhtml += " invariant count = "; - xhtml += getInvariantCount(); - xhtml += "

"; - - xhtml += "
";
-
-        int count, state;
-        int type = getDataType().getType();
-
-        count = getPatternCount();
-
-        int length, maxLength = 0;
-        for (int i = 0; i < count; i++) {
-            length = Integer.toString((int) getPatternWeight(i)).length();
-            if (length > maxLength)
-                maxLength = length;
-        }
-
-        for (int i = 0; i < count; i++) {
-            length = Integer.toString(i + 1).length();
-            for (int j = length; j < maxLength; j++)
-                xhtml += " ";
-            xhtml += Integer.toString(i + 1) + ": ";
-
-            length = Integer.toString((int) getPatternWeight(i)).length();
-            xhtml += Integer.toString((int) getPatternWeight(i));
-            for (int j = length; j <= maxLength; j++)
-                xhtml += " ";
-
-            for (int j = 0; j < getTaxonCount(); j++) {
-                state = getPatternState(j, i);
-
-                if (type == DataType.NUCLEOTIDES) {
-                    xhtml += Nucleotides.INSTANCE.getChar(state) + " ";
-                } else if (type == DataType.CODONS) {
-                    xhtml += Codons.UNIVERSAL.getTriplet(state) + " ";
-                } else {
-                    xhtml += AminoAcids.INSTANCE.getChar(state) + " ";
-                }
-            }
-            xhtml += "\n";
-        }
-        xhtml += "
"; - return xhtml; - } - - - /* - * AbstractModel implementation - */ - - @Override - protected void handleModelChangedEvent(Model model, Object object, int index) { - //AUTOGENERATED METHOD IMPLEMENTATION - } - - @Override - protected void handleVariableChangedEvent(Variable variable, int index, Variable.ChangeType type) { - //AUTOGENERATED METHOD IMPLEMENTATION - } - - @Override - protected void storeState() { - //AUTOGENERATED METHOD IMPLEMENTATION - } - - @Override - protected void restoreState() { - //AUTOGENERATED METHOD IMPLEMENTATION - } - - @Override - protected void acceptState() { - //AUTOGENERATED METHOD IMPLEMENTATION - } -} diff --git a/src/dr/oldevomodel/lineage/LineageSitePatternsParser.java b/src/dr/oldevomodel/lineage/LineageSitePatternsParser.java deleted file mode 100644 index aad342f392..0000000000 --- a/src/dr/oldevomodel/lineage/LineageSitePatternsParser.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * LineageSitePatternsParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.lineage; - -import dr.evolution.alignment.Alignment; -import dr.evolution.alignment.PatternList; -import dr.evolution.util.TaxonList; -import dr.xml.*; - -import java.util.logging.Logger; - -/** - * @author Alexander Alekseyenko - * @author Jack O'Brien - */ -public class LineageSitePatternsParser extends AbstractXMLObjectParser { - - public static final String PATTERNS = "lineageSNPS"; - public static final String FROM = "from"; - public static final String TO = "to"; - public static final String EVERY = "every"; - public static final String TAXON_LIST = "taxonList"; - public static final String STRIP = "strip"; - public static final String UNIQUE = "unique"; - - - public String getParserName() { - return PATTERNS; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - Alignment alignment = (Alignment) xo.getChild(Alignment.class); - TaxonList taxa = null; - - int from = 0; - int to = -1; - int every = xo.getAttribute(EVERY, 1); - - boolean strip = xo.getAttribute(STRIP, true); - - boolean unique = xo.getAttribute(UNIQUE, true); - - if (xo.hasAttribute(FROM)) { - from = xo.getIntegerAttribute(FROM) - 1; - if (from < 0) - throw new XMLParseException("illegal 'from' attribute in patterns element"); - } - - if (xo.hasAttribute(TO)) { - to = xo.getIntegerAttribute(TO) - 1; - if (to < 0 || to < from) - throw new XMLParseException("illegal 'to' attribute in patterns element"); - } - - if (every <= 0) throw new XMLParseException("illegal 'every' attribute in patterns element"); - - if (xo.hasChildNamed(TAXON_LIST)) { - taxa = (TaxonList) xo.getElementFirstChild(TAXON_LIST); - } - - if (from > alignment.getSiteCount()) - throw new XMLParseException("illegal 'from' attribute in patterns element"); - - if (to > alignment.getSiteCount()) - throw new XMLParseException("illegal 'to' attribute in patterns element"); - - LineageSitePatterns patterns = new LineageSitePatterns(alignment, taxa, from, to, every, strip, unique); - - int f = from + 1; - int t = to + 1; // fixed a *display* error by adding + 1 for consistency with f = from + 1 - if (to == -1) t = alignment.getSiteCount(); - - if (xo.hasAttribute(XMLParser.ID)) { - final Logger logger = Logger.getLogger("dr.evoxml"); - logger.info("Site patterns '" + xo.getId() + "' created from positions " + - Integer.toString(f) + "-" + Integer.toString(t) + - " of alignment '" + alignment.getId() + "'"); - - if (every > 1) { - logger.info(" only using every " + every + " site"); - } - logger.info(" pattern count = " + patterns.getPatternCount()); - } - - return patterns; - } - - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private final XMLSyntaxRule[] rules = { - AttributeRule.newIntegerRule(FROM, true, "The site position to start at, default is 1 (the first position)"), - AttributeRule.newIntegerRule(TO, true, "The site position to finish at, must be greater than " + FROM + ", default is length of given alignment"), - AttributeRule.newIntegerRule(EVERY, true, "Determines how many sites are selected. A value of 3 will select every third site starting from " + FROM + ", default is 1 (every site)"), - new ElementRule(TAXON_LIST, - new XMLSyntaxRule[]{new ElementRule(TaxonList.class)}, true), - new ElementRule(Alignment.class), - AttributeRule.newBooleanRule(STRIP, true, "Strip out completely ambiguous sites"), - AttributeRule.newBooleanRule(UNIQUE, true, "Return a weight list of unique patterns"), - }; - - public String getParserDescription() { - return "A weighted list of the unique site patterns (unique columns) in an alignment."; - } - - public Class getReturnType() { - return PatternList.class; - } - -} diff --git a/src/dr/oldevomodel/sitemodel/AlignmentScore.java b/src/dr/oldevomodel/sitemodel/AlignmentScore.java deleted file mode 100644 index 3df43d4667..0000000000 --- a/src/dr/oldevomodel/sitemodel/AlignmentScore.java +++ /dev/null @@ -1,280 +0,0 @@ -/* - * AlignmentScore.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.sitemodel; - -import dr.evolution.alignment.Alignment; -import dr.evolution.alignment.ExtractPairs; -import dr.evolution.alignment.GapUtils; -import dr.evolution.alignment.SitePatterns; -import dr.evolution.datatype.Nucleotides; -import dr.evolution.io.Importer; -import dr.evolution.io.NexusImporter; -import dr.oldevomodel.substmodel.FrequencyModel; -import dr.oldevomodel.substmodel.HKY; -import dr.oldevomodel.substmodel.SubstitutionModel; -import dr.inference.model.Parameter; -import dr.math.DifferentialEvolution; -import dr.math.MultivariateFunction; -import dr.math.UnivariateFunction; -import dr.math.UnivariateMinimum; - -import java.io.FileReader; -import java.util.*; - -/** - * @author alexei - */ -public class AlignmentScore implements UnivariateFunction, MultivariateFunction { - - SiteModel siteModel; - ScoreMatrix scoreMatrix; - SitePatterns sitePatterns; - - public AlignmentScore(ScoreMatrix scoreMatrix, SitePatterns sitePatterns) { - this.scoreMatrix = scoreMatrix; - this.siteModel = scoreMatrix.siteModel; - this.sitePatterns = sitePatterns; - } - - /** - * compute function value - * - * @param argument function argument (vector) - * @return function value - */ - public double evaluate(double[] argument) { - - double kappa = argument[0]; - double time = argument[1]; - - ((HKY)((GammaSiteModel)siteModel).getSubstitutionModel()).setKappa(kappa); - - scoreMatrix.setTime(time); - - // must return negative logLikelihood because optimizer finds minimum - return -scoreMatrix.getScore(sitePatterns); - } - - /** - * compute function value - * - * @param time - * @return function value - */ - public double evaluate(double time) { - scoreMatrix.setTime(time); - - // must return negative logLikelihood because optimizer finds minimum - return -scoreMatrix.getScore(sitePatterns); - } - - /** - * get number of arguments - * - * @return number of arguments - */ - public int getNumArguments() { - return 2; - } - - /** - * get lower bound of argument - * - * @return lower bound - */ - public double getLowerBound() { - return 0.0; //To change body of implemented methods use File | Settings | File Templates. - } - - /** - * get upper bound of argument - * - * @return upper bound - */ - public double getUpperBound() { - return 10.0; //To change body of implemented methods use File | Settings | File Templates. - } - - /** - * get lower bound of argument n - * - * @param n argument number - * @return lower bound - */ - public double getLowerBound(int n) { - - return 0; - } - - /** - * get upper bound of argument n - * - * @param n argument number - * @return upper bound - */ - public double getUpperBound(int n) { - if (n == 0) return 100; - if (n == 1) return 100; - return 10; - } - - public static double[] getAlignmentScore(ScoreMatrix scoreMatrix, SitePatterns sitePatterns) { - - AlignmentScore alignmentScore = new AlignmentScore(scoreMatrix, sitePatterns); - - double[] params = new double[alignmentScore.getNumArguments()]; - DifferentialEvolution de = new DifferentialEvolution(params.length,params.length*10); - for (int i = 0; i < params.length; i++) params[i] = 0.5; - - de.optimize(alignmentScore, params,1e-6, 1e-6); - double score = alignmentScore.evaluate(params); - - double[] results = new double[params.length + 1]; - System.arraycopy(params, 0, results, 0, params.length); - results[params.length] = score; - - return results; - } - - public static double getGeneticDistance(ScoreMatrix scoreMatrix, SitePatterns sitePatterns) { - - AlignmentScore alignmentScore = new AlignmentScore(scoreMatrix, sitePatterns); - - double[] params = new double[alignmentScore.getNumArguments()]; - DifferentialEvolution de = new DifferentialEvolution(params.length,params.length*10); - for (int i = 0; i < params.length; i++) params[i] = 0.5; - - de.optimize(alignmentScore, params,1e-6, 1e-6); - //double score = alignmentScore.evaluate(params); - - return params[params.length-1]; - - } - - public static double[] getFastAlignmentScore(ScoreMatrix scoreMatrix, SitePatterns sitePatterns) { - - AlignmentScore alignmentScore = new AlignmentScore(scoreMatrix, sitePatterns); - - UnivariateMinimum de = new UnivariateMinimum(); - - double time = de.optimize(alignmentScore, 1e-6); - double score = alignmentScore.evaluate(time); - - return new double[] {time, score}; - } - - - private static void printFrequencyTable(List list) { - int max = 0; - int total = 0; - for (Integer size : list) { - if (size > max) max = size; - total += size; - } - int[] freqs = new int[max+1]; - for (Integer size : list) { - freqs[size] += 1; - } - - for (int i = 0; i < freqs.length; i++) { - System.out.println(i + "\t" + freqs[i]); - } - System.out.println("Total = " + total); - } - - public static void main(String[] args) throws java.io.IOException, Importer.ImportException { - - NexusImporter importer = new NexusImporter(new FileReader(args[0])); - - Alignment alignment = importer.importAlignment(); - - ExtractPairs pairs = new ExtractPairs(alignment); - - Parameter muParam = new Parameter.Default(1.0); - Parameter kappaParam = new Parameter.Default(1.0); - kappaParam.addBounds(new Parameter.DefaultBounds(100.0, 0.0, 1)); - muParam.addBounds(new Parameter.DefaultBounds(1.0, 1.0, 1)); - - Parameter freqParam = new Parameter.Default(alignment.getStateFrequencies()); - - FrequencyModel freqModel = new FrequencyModel(Nucleotides.INSTANCE,freqParam); - - SubstitutionModel substModel = new HKY(kappaParam, freqModel); - - SiteModel siteModel = new GammaSiteModel(substModel, muParam, null, 1, null); - - ScoreMatrix scoreMatrix = new ScoreMatrix(siteModel, 0.1); - - - double threshold = 0.1; - - List pairDistances = new ArrayList(); - Set sequencesUsed = new HashSet(); - List allGaps = new ArrayList(); - for (int i = 0; i < alignment.getSequenceCount(); i++) { - for (int j = i+1; j < alignment.getSequenceCount(); j++) { - Alignment pairAlignment = pairs.getPairAlignment(i,j); - if (pairAlignment != null) { - SitePatterns patterns = new SitePatterns(pairAlignment); - - double distance = getGeneticDistance(scoreMatrix, patterns); - if (distance < threshold) { - List gaps = new ArrayList(); - GapUtils.getGapSizes(pairAlignment, gaps); - pairDistances.add(new PairDistance(i,j,distance, gaps, pairAlignment.getSiteCount())); - System.out.print("."); - } else { - System.out.print("*"); - } - } else { - System.out.print("x"); - } - } - System.out.println(); - } - - Collections.sort(pairDistances); - int totalLength = 0; - for (PairDistance pairDistance : pairDistances) { - - Integer x = pairDistance.x; - Integer y = pairDistance.y; - - if (!sequencesUsed.contains(x) && !sequencesUsed.contains(y)) { - allGaps.addAll(pairDistance.gaps); - sequencesUsed.add(x); - sequencesUsed.add(y); - System.out.println("Added pair (" + x + "," + y + ") d=" + pairDistance.distance + " L=" + pairDistance.alignmentLength); - totalLength += pairDistance.alignmentLength; - } - } - - printFrequencyTable(allGaps); - System.out.println("total length=" + totalLength); - } -} diff --git a/src/dr/oldevomodel/sitemodel/CategoryParameterStatistic.java b/src/dr/oldevomodel/sitemodel/CategoryParameterStatistic.java deleted file mode 100644 index 973c0d6343..0000000000 --- a/src/dr/oldevomodel/sitemodel/CategoryParameterStatistic.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * CategoryParameterStatistic.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.sitemodel; - -import dr.inference.model.BooleanStatistic; -import dr.inference.model.Statistic; -import dr.xml.*; - - -/** - * Performs test of whether a category parameter has a given minimum number of sites in each category - * - * @author Roald Forsberg - */ -public class CategoryParameterStatistic extends Statistic.Abstract implements BooleanStatistic { - - private static String MINIMUM_NUMBER = "minimumNumber"; - - public CategoryParameterStatistic(String name, - SampleStateAndCategoryModel siteModel, - int minimumNumber) { - - super(name); - this.minimumNumber = minimumNumber; - this.siteModel = siteModel; - this.categoryCount = siteModel.getCategoryCount(); - } - - public int getDimension() { - return 1; - } - - /** - * @return boolean result of test. - */ - public double getStatisticValue(int dim) { - return getBoolean(dim) ? 1.0 : 0.0; - } - - /** - * @return boolean result of test. - */ - public boolean getBoolean(int dim) { - for (int i = 0; i < categoryCount; i++) { - if (siteModel.getSitesInCategoryCount(i) < minimumNumber) - return false; - } - - return true; - } - - public static dr.xml.XMLObjectParser PARSER = new dr.xml.AbstractXMLObjectParser() { - - public String getParserName() { - return "categoryParameterStatistic"; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - SampleStateAndCategoryModel siteModel = null; - String name = xo.getAttribute("name", null); - - int minimum = xo.getAttribute(MINIMUM_NUMBER, 0); - - for (int i = 0; i < xo.getChildCount(); i++) { - if (xo.getChild(i) instanceof SampleStateAndCategoryModel) { - siteModel = (SampleStateAndCategoryModel) xo.getChild(i); - } - } - - if (siteModel == null) - throw new XMLParseException(getParserName() + " must contain a SampleStateAndCategoryModel."); - if (minimum < 1) throw new XMLParseException(getParserName() + " minimum number must be greater than 0."); - return new CategoryParameterStatistic(name, siteModel, minimum); - } - - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - - public String getParserDescription() { - return "A statistic that returns true if the minimum number of sites in a category are present"; - } - - public Class getReturnType() { - return CategoryParameterStatistic.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{ - new StringAttributeRule(NAME, "A name for this statistic for the purposes of logging"), - AttributeRule.newIntegerRule(MINIMUM_NUMBER), - new ElementRule(SampleStateAndCategoryModel.class) - }; - - }; - - private int minimumNumber; - private int categoryCount; - private SampleStateAndCategoryModel siteModel; - -} diff --git a/src/dr/oldevomodel/sitemodel/CategorySampleModel.java b/src/dr/oldevomodel/sitemodel/CategorySampleModel.java deleted file mode 100644 index d015eb4eb7..0000000000 --- a/src/dr/oldevomodel/sitemodel/CategorySampleModel.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * CategorySampleModel.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.sitemodel; - - -/** - * - * @author Roald Forsberg -*/ - -public interface CategorySampleModel extends SiteModel{ - - /** - * can be called by a CategoryOperator object - */ - void toggleRandomSite(); - - void addSitesInCategoryCount(int category); - - void subtractSitesInCategoryCount(int category); - - int getSitesInCategoryCount(int category); - - - /** - * provide information to the categoriesParameter - * about the number of sites - */ - void setCategoriesParameter(int siteCount); - - -} \ No newline at end of file diff --git a/src/dr/oldevomodel/sitemodel/CategorySiteModel.java b/src/dr/oldevomodel/sitemodel/CategorySiteModel.java deleted file mode 100644 index d4e7ccf7ab..0000000000 --- a/src/dr/oldevomodel/sitemodel/CategorySiteModel.java +++ /dev/null @@ -1,277 +0,0 @@ -/* - * CategorySiteModel.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.sitemodel; - -import dr.oldevomodel.substmodel.FrequencyModel; -import dr.oldevomodel.substmodel.SubstitutionModel; -import dr.inference.model.AbstractModel; -import dr.inference.model.Model; -import dr.inference.model.Parameter; -import dr.inference.model.Variable; - -/** - * CategorySiteModel - A SiteModel that has a different rate for each category; - * - * @author Alexei Drummond - */ - -public class CategorySiteModel extends AbstractModel implements SiteModel { - - /** - * @param rateParameter (relative to the rate of category 1) - */ - public CategorySiteModel(SubstitutionModel substitutionModel, - Parameter muParameter, - Parameter rateParameter, - String categoryString, - String stateString, - int relativeTo) { - - super(SITE_MODEL); - - this.substitutionModel = substitutionModel; - addModel(substitutionModel); - - this.muParameter = muParameter; - addVariable(muParameter); - muParameter.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, 0.0, 1)); - - this.rateParameter = rateParameter; - addVariable(rateParameter); - rateParameter.addBounds(new Parameter.DefaultBounds(Double.MAX_VALUE, Double.MIN_VALUE, rateParameter.getDimension())); - - states = stateString; - - if (states.length() != (rateParameter.getDimension() + 1)) { - throw new IllegalArgumentException("States must have one more dimension than rate parameter!"); - } - categoryCount = states.length(); - - categories = new int[categoryString.length()]; - categoryWeights = new int[categoryCount]; - categoryRates = new double[categoryCount]; - for (int i = 0; i < categories.length; i++) { - char state = categoryString.charAt(i); - categories[i] = states.indexOf(state); - categoryWeights[categories[i]] += 1; - } - - siteCount = categories.length; - this.relativeTo = relativeTo; - ratesKnown = false; - } - - /** - * set mu - */ - public void setMu(double mu) { - muParameter.setParameterValue(0, mu); - } - - /** - * @return mu - */ - public final double getMu() { - return muParameter.getParameterValue(0); - } - - - public Parameter getMutationRateParameter() { - return muParameter; - } - - // ***************************************************************** - // Interface SiteModel - // ***************************************************************** - - public boolean integrateAcrossCategories() { - return false; - } - - public int getCategoryCount() { - return categoryCount; - } - - public int getCategoryOfSite(int site) { - - return categories[site]; - } - - public double getRateForCategory(int category) { - synchronized (this) { - if (!ratesKnown) { - calculateCategoryRates(); - } - } - double mu = 1.0; - if (muParameter != null) { - mu = muParameter.getParameterValue(0); - } - - return categoryRates[category] * mu; - } - - public double[] getCategoryRates() { - synchronized (this) { - if (!ratesKnown) { - calculateCategoryRates(); - } - } - double[] rates = new double[categoryRates.length]; - double mu = 1.0; - if (muParameter != null) { - mu = muParameter.getParameterValue(0); - } - for (int i = 0; i < rates.length; i++) { - rates[i] = categoryRates[i] * mu; - } - - return rates; - } - - public void getTransitionProbabilities(double substitutions, double[] matrix) { - substitutionModel.getTransitionProbabilities(substitutions, matrix); - } - - /** - * Get the expected proportion of sites in this category. - * - * @param category the category number - * @return the proportion. - */ - public double getProportionForCategory(int category) { - throw new UnsupportedOperationException(); - } - - /** - * Get an array of the expected proportion of sites in this category. - * - * @return an array of the proportion. - */ - public double[] getCategoryProportions() { - throw new UnsupportedOperationException(); - } - - /** - * - */ - private void calculateCategoryRates() { - - categoryRates[relativeTo] = 1.0; - double total = 1.0; - int count = 0; - for (int i = 0; i < categoryRates.length; i++) { - if (i != relativeTo) { - categoryRates[i] = rateParameter.getParameterValue(count); - total = categoryRates[i] * categoryWeights[i]; - count += 1; - } - } - total /= (double) siteCount; - - // normalize so that total output rate is 1.0 - for (int i = 0; i < categoryRates.length; i++) { - categoryRates[i] /= total; - } - - ratesKnown = true; - } - - /** - * Get the frequencyModel for this SiteModel. - * - * @return the frequencyModel. - */ - public FrequencyModel getFrequencyModel() { - return substitutionModel.getFrequencyModel(); - } - - /** - * Get the substitutionModel for this SiteModel. - * - * @return the substitutionModel. - */ - public SubstitutionModel getSubstitutionModel() { - return substitutionModel; - } - - // ***************************************************************** - // Interface ModelComponent - // ***************************************************************** - - protected void handleModelChangedEvent(Model model, Object object, int index) { - // Substitution model has changed so fire model changed event - listenerHelper.fireModelChanged(this, object, index); - } - - public void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) { - if (variable == rateParameter) { - ratesKnown = false; - } - listenerHelper.fireModelChanged(this, variable, index); - } - - protected void storeState() { - } // no additional state needs storing - - protected void restoreState() { - ratesKnown = false; - } - - protected void acceptState() { - } // no additional state needs accepting - - /** - * the substitution model for these sites - */ - private SubstitutionModel substitutionModel = null; - - /** - * mutation rate parameter - */ - private final Parameter muParameter; - - /** - * rates parameter - */ - private final Parameter rateParameter; - - private boolean ratesKnown; - - private final int categoryCount; - - private final double[] categoryRates; - - - private final int[] categoryWeights; - private final int[] categories; - private final String states; - private final int siteCount; - private int relativeTo = 0; - -} diff --git a/src/dr/oldevomodel/sitemodel/DirichletSiteModel.java b/src/dr/oldevomodel/sitemodel/DirichletSiteModel.java deleted file mode 100644 index 31ac1e2ae8..0000000000 --- a/src/dr/oldevomodel/sitemodel/DirichletSiteModel.java +++ /dev/null @@ -1,312 +0,0 @@ -/* - * DirichletSiteModel.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.sitemodel; - -import dr.oldevomodel.substmodel.FrequencyModel; -import dr.oldevomodel.substmodel.SubstitutionModel; -import dr.inference.model.AbstractModel; -import dr.inference.model.Model; -import dr.inference.model.Parameter; -import dr.inference.model.Variable; -import dr.xml.*; - -import java.util.logging.Logger; - -/** - * DirichletSiteModel - A SiteModel that has a free rate parameter for each category. - * These rate parameters are constrained to sum to 1. - * - * @author Benjamin Redelings - */ - -public class DirichletSiteModel extends AbstractModel implements SiteModel { - - public static final String SUBSTITUTION_MODEL = "substitutionModel"; - public static final String DIRICHLET_SITE_MODEL = "DirichletSiteModel"; - public static final String CATEGORIES = "categories"; - public static final String RATES = "rates"; - - /** - * Constructor for gamma+invar distributed sites. Either shapeParameter or - * invarParameter (or both) can be null to turn off that feature. - */ - public DirichletSiteModel(SubstitutionModel substitutionModel, int n_categories) { - this(substitutionModel, new Parameter.Default(new double[n_categories])); - } - - public DirichletSiteModel(SubstitutionModel substitutionModel, Parameter ratesParameter) { - super(DIRICHLET_SITE_MODEL); - - // Set substitution model - this.substitutionModel = substitutionModel; - addModel(substitutionModel); - - // Allocate array for categories and proportions - int n_categories = ratesParameter.getDimension(); - categoryRates = new double[n_categories]; - categoryProportions = new double[n_categories]; - - // We haven't calculated any rates yet. - ratesKnown = false; - - // Initialize the rate parameter value - for(int i=0;i 0) { - Logger.getLogger("dr.evomodel").info("Creating site model: " + msg); - } else { - Logger.getLogger("dr.evomodel").info("Creating site model."); - } - - return new DirichletSiteModel(substitutionModel, ratesParameter); - } - - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - - public String getParserDescription() { - return "A SiteModel that has Dirichlet distributed rates across sites"; - } - - public Class getReturnType() { - return DirichletSiteModel.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private final XMLSyntaxRule[] rules = { - new ElementRule(SUBSTITUTION_MODEL, new XMLSyntaxRule[]{ - new ElementRule(SubstitutionModel.class) - }), - new ElementRule(RATES, new XMLSyntaxRule[]{ - new ElementRule(Parameter.class) - }) - }; - }; - - /** - * the substitution model for these sites - */ - private SubstitutionModel substitutionModel = null; - - /** - * the substitution rates: these sum to 1 - */ - private Parameter ratesParameter; - - private boolean ratesKnown; - - private double[] categoryRates; - - private double[] categoryProportions; -} diff --git a/src/dr/oldevomodel/sitemodel/DiscretizedLociRates.java b/src/dr/oldevomodel/sitemodel/DiscretizedLociRates.java deleted file mode 100644 index bfd2722726..0000000000 --- a/src/dr/oldevomodel/sitemodel/DiscretizedLociRates.java +++ /dev/null @@ -1,134 +0,0 @@ -/* - * DiscretizedLociRates.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.sitemodel; - -import dr.inference.model.*; -import dr.inference.distribution.ParametricDistributionModel; - -/** - * @author Chieh-Hsi Wu - * - * This class models the relative loci rates using the given discritized parametric distribution. - */ -public class DiscretizedLociRates extends AbstractModel { - - private CompoundParameter lociRates; - private Parameter rateCategoryParameter; - private ParametricDistributionModel distrModel; - private double normalizeRateTo; - private double[] rates; - private boolean normalize; - private int categoryCount; - private double scaleFactor; - private boolean completeSetup; - - - public DiscretizedLociRates( - CompoundParameter lociRates, - Parameter rateCategoryParameter, - ParametricDistributionModel model, - boolean normalize, - double normalizeLociRateTo, - int categoryCount) { - super("DiscretizedLociRatesModel"); - this.lociRates = lociRates; - - this.rateCategoryParameter = rateCategoryParameter; - //Force the boundaries of rateCategoryParameter to match the category count - Parameter.DefaultBounds bound = new Parameter.DefaultBounds(categoryCount - 1, 0, rateCategoryParameter.getDimension()); - this.rateCategoryParameter.addBounds(bound); - - this.distrModel = model; - this.normalizeRateTo = normalizeLociRateTo; - this.normalize = normalize; - this.categoryCount = categoryCount; - rates = new double[categoryCount]; - completeSetup = true; - setupRates(); - - - addModel(distrModel); - addVariable(this.rateCategoryParameter); - - } - - private void setupRates(){ - if(completeSetup){ - - double categoryIntervalSize = 1.0/categoryCount; - for(int i = 0; i < categoryCount; i++){ - rates[i]= distrModel.quantile((i+0.5)*categoryIntervalSize); - } - } - if(normalize){ - computeFactor(); - } - - completeSetup = false; - int lociCount = rateCategoryParameter.getDimension(); - for(int i = 0; i < lociCount; i ++){ - lociRates.setParameterValue(i,rates[(int)rateCategoryParameter.getParameterValue(i)]*scaleFactor); - } - - } - public void handleModelChangedEvent(Model model, Object object, int index) { - if (model == distrModel) { - completeSetup = true; - setupRates(); - //System.out.println("speed investigation 1"); - fireModelChanged(); - }else if (model == rateCategoryParameter) { - //System.out.println("speed investigation 2"); - setupRates(); - fireModelChanged(null, index); - } - } - - protected final void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) { - //System.out.println("speed investigation 3"); - setupRates(); - fireModelChanged(null, index); - } - - protected void storeState() { - } - protected void acceptState() { - } - protected void restoreState() { - //setupRates(); - } - private void computeFactor(){ - double sumRates = 0.0; - int lociCount = rateCategoryParameter.getDimension(); - for(int i = 0; i < lociCount; i++){ - sumRates += rates[(int)rateCategoryParameter.getParameterValue(i)]; - } - scaleFactor = normalizeRateTo/(sumRates/lociCount); - } - -} diff --git a/src/dr/oldevomodel/sitemodel/GammaSiteBMA.java b/src/dr/oldevomodel/sitemodel/GammaSiteBMA.java deleted file mode 100644 index 63d50689e7..0000000000 --- a/src/dr/oldevomodel/sitemodel/GammaSiteBMA.java +++ /dev/null @@ -1,289 +0,0 @@ -/* - * GammaSiteBMA.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.sitemodel; - -import dr.oldevomodel.substmodel.SubstitutionModel; -import dr.oldevomodel.substmodel.FrequencyModel; -import dr.inference.model.*; -import dr.math.distributions.GammaDistribution; - -/** - * @author Chieh-Hsi Wu - * - * BSSVS on Gamma site model - * - */ -public class GammaSiteBMA extends AbstractModel implements SiteModel { - - private SubstitutionModel substitutionModel = null; - private Parameter muParameter =null; - private Variable modelChoose = null; - private Variable logShape = null; - private Variable logitInvar = null; - private int categoryCount = -1; - private double[] categoryRates; - private double[] categoryProportions; - private boolean ratesKnown; - public static final int SHAPE_INDEX = 0; - public static final int INVAR_INDEX = 1; - public static final int PRESENT = 1; - public static final int ABSENT = 0; - - public GammaSiteBMA(SubstitutionModel substitutionModel, - Parameter muParameter, - Variable logitInvar, - Variable logShape, - int categoryCount, - Variable modelChoose){ - super("GammaSiteBMA"); - - this.substitutionModel = substitutionModel; - addModel(substitutionModel); - - addVariable(muParameter); - muParameter.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, 0.0, 1)); - this.muParameter = muParameter; - - addVariable(logShape); - logShape.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, 1)); - this.logShape = logShape; - - addVariable(logitInvar); - logitInvar.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, 1)); - this.logitInvar = logitInvar; - - - - //the modelChoose integer variable is of length = 2, - //where indices 0 and 1 indicates the presence or absence of alpha and pInvar repectively. - addVariable(modelChoose); - modelChoose.addBounds(new Bounds.Int(modelChoose,0,1)); - this.modelChoose = modelChoose; - this.categoryCount = categoryCount +1; - - categoryRates = new double[this.categoryCount]; - categoryProportions = new double[this.categoryCount]; - - ratesKnown = false; - - } - - public boolean integrateAcrossCategories() { - return true; - } - - public int getCategoryCount() { - return categoryCount; - } - - public int getCategoryOfSite(int site) { - throw new IllegalArgumentException("Integrating across categories"); - } - - public double getRateForCategory(int category) { - synchronized (this) { - if (!ratesKnown) { - calculateCategoryRates(); - } - } - - final double mu = (muParameter != null) ? muParameter.getParameterValue(0) : 1.0; - - return categoryRates[category] * mu; - } - - - public double[] getCategoryRates() { - synchronized (this) { - if (!ratesKnown) { - calculateCategoryRates(); - } - } - - final double mu = (muParameter != null) ? muParameter.getParameterValue(0) : 1.0; - - final double[] rates = new double[categoryRates.length]; - for (int i = 0; i < rates.length; i++) { - rates[i] = categoryRates[i] * mu; - } - - return rates; - } - - public void getTransitionProbabilities(double substitutions, double[] matrix) { - substitutionModel.getTransitionProbabilities(substitutions, matrix); - } - - /** - * Get the expected proportion of sites in this category. - * - * @param category the category number - * @return the proportion. - */ - public double getProportionForCategory(int category) { - synchronized (this) { - if (!ratesKnown) { - calculateCategoryRates(); - } - } - - return categoryProportions[category]; - } - - /** - * Get an array of the expected proportion of sites in this category. - * - * @return an array of the proportion. - */ - public double[] getCategoryProportions() { - synchronized (this) { - if (!ratesKnown) { - calculateCategoryRates(); - } - } - - return categoryProportions; - } - - /** - * discretization of gamma distribution with equal proportions in each - * category - */ - private void calculateCategoryRates() { - - double propVariable = 1.0; - int cat = 0; - //System.out.println("modelChoose: "+ modelChoose.getValue(0)+" "+modelChoose.getValue(1)); - //If including the site invariant parameter. - - categoryRates[0] = 0.0; - //back transform from logit space - categoryProportions[0] = modelChoose.getValue(INVAR_INDEX)*(1/(1+Math.exp(-logitInvar.getValue(0)))); - - propVariable = 1.0 - categoryProportions[0]; - cat = 1; - - - //If including the gamma shape parameter. - if (modelChoose.getValue(SHAPE_INDEX) == PRESENT) { - - //back transform from log-space - final double a = Math.exp(logShape.getValue(0)); - double mean = 0.0; - final int gammaCatCount = categoryCount - cat; - - for (int i = 0; i < gammaCatCount; i++) { - - categoryRates[i + cat] = GammaDistribution.quantile((2.0 * i + 1.0) / (2.0 * gammaCatCount), a, 1.0 / a); - //sum of the gamma categorical rates - mean += categoryRates[i + cat]; - - categoryProportions[i + cat] = propVariable / gammaCatCount; - } - - //mean rate over all categories. - mean = (propVariable * mean) / gammaCatCount; - - for (int i = 0; i < gammaCatCount; i++) { - //divide rates by the mean so that the average across all sites equals to 1.0 - categoryRates[i + cat] /= mean; - - } - } else { - - final int gammaCatCount = categoryCount - cat; - for (int i = 0; i < gammaCatCount; i++) { - categoryRates[i + cat] = 1.0 / propVariable; - categoryProportions[i + cat] = propVariable/gammaCatCount; - } - } - - /*for(int i = 0; i < categoryRates.length;i++){ - System.out.print(categoryRates[i]+" "); - } - System.out.println();*/ - ratesKnown = true; - } - - /** - * Get the frequencyModel for this SiteModel. - * - * @return the frequencyModel. - */ - public FrequencyModel getFrequencyModel() { - return substitutionModel.getFrequencyModel(); - } - - /** - * Get the substitutionModel for this SiteModel. - * - * @return the substitutionModel. - */ - public SubstitutionModel getSubstitutionModel() { - return substitutionModel; - } - - // ***************************************************************** - // Interface ModelComponent - // ***************************************************************** - - protected void handleModelChangedEvent(Model model, Object object, int index) { - // Substitution model has changed so fire model changed event - listenerHelper.fireModelChanged(this, object, index); - } - - protected final void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) { - if (variable == logShape) { - ratesKnown = false; - } else if (variable == logitInvar) { - ratesKnown = false; - } else if (variable == modelChoose) { - //System.out.println("Changing model"); - ratesKnown = false; - } else { - // is the muParameter and nothing needs to be done - } - listenerHelper.fireModelChanged(this, variable, index); - } - - protected void storeState() { - /*System.out.println("store, modelChoose: "+ modelChoose.getValue(0)+" "+modelChoose.getValue(1) ); - for(int i = 0; i < categoryRates.length;i++){ - System.out.print(categoryRates[i]+" "); - } - System.out.println();*/ - } // no additional state needs storing - - protected void restoreState() { - //System.out.println("restore, modelChoose: "+ modelChoose.getValue(0)+" "+modelChoose.getValue(1) ); - ratesKnown = false; - } - - protected void acceptState() { - } // no additional state needs accepting -} diff --git a/src/dr/oldevomodel/sitemodel/GammaSiteModel.java b/src/dr/oldevomodel/sitemodel/GammaSiteModel.java deleted file mode 100644 index fff849cae6..0000000000 --- a/src/dr/oldevomodel/sitemodel/GammaSiteModel.java +++ /dev/null @@ -1,388 +0,0 @@ -/* - * GammaSiteModel.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.sitemodel; - -import dr.oldevomodel.substmodel.FrequencyModel; -import dr.oldevomodel.substmodel.SubstitutionModel; -import dr.inference.model.AbstractModel; -import dr.inference.model.Model; -import dr.inference.model.Parameter; -import dr.inference.model.Variable; -import dr.math.distributions.GammaDistribution; - -/** - * GammaSiteModel - A SiteModel that has a gamma distributed rates across sites. - * - * @author Andrew Rambaut - */ - -public class GammaSiteModel extends AbstractModel implements SiteModel { - - public GammaSiteModel(SubstitutionModel substitutionModel) { - this(substitutionModel, - null, - null, - 0, - null); - } - - public GammaSiteModel(SubstitutionModel substitutionModel, double alpha, int categoryCount) { - this(substitutionModel, - null, - new Parameter.Default(alpha), - categoryCount, - null); - } - - public GammaSiteModel(SubstitutionModel substitutionModel, double pInvar) { - this(substitutionModel, - null, - null, - 0, - new Parameter.Default(pInvar)); - } - - public GammaSiteModel(SubstitutionModel substitutionModel, double alpha, int categoryCount, double pInvar) { - this(substitutionModel, - null, - new Parameter.Default(alpha), - categoryCount, - new Parameter.Default(pInvar)); - } - - /** - * Constructor for gamma+invar distributed sites. Either shapeParameter or - * invarParameter (or both) can be null to turn off that feature. - */ - public GammaSiteModel(SubstitutionModel substitutionModel, - Parameter muParameter, - Parameter shapeParameter, int gammaCategoryCount, - Parameter invarParameter) { - - super(SITE_MODEL); - - this.substitutionModel = substitutionModel; - addModel(substitutionModel); - - this.muParameter = muParameter; - if (muParameter != null) { - addVariable(muParameter); - muParameter.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, 0.0, 1)); - } - - this.shapeParameter = shapeParameter; - if (shapeParameter != null) { - this.categoryCount = gammaCategoryCount; - - addVariable(shapeParameter); - - // The quantile calculator fails when the shape parameter goes much below - // 1E-3 so we have put a hard lower bound on it. If this is not there then - // the category rates can go to 0 and cause a -Inf likelihood (whilst this - // is not a problem as the state will be rejected, it could mask other issues - // and this seems the better approach. - shapeParameter.addBounds(new Parameter.DefaultBounds(1.0E3, 1.0E-3, 1)); - } else { - this.categoryCount = 1; - } - - this.invarParameter = invarParameter; - if (invarParameter != null) { - this.categoryCount += 1; - - addVariable(invarParameter); - invarParameter.addBounds(new Parameter.DefaultBounds(1.0, 0.0, 1)); - } - - categoryRates = new double[this.categoryCount]; - categoryProportions = new double[this.categoryCount]; - - ratesKnown = false; - } - - /** - * set mu - */ - public void setMu(double mu) { - muParameter.setParameterValue(0, mu); - } - - /** - * @return mu - */ - public final double getMu() { - return muParameter.getParameterValue(0); - } - - /** - * set alpha - */ - public void setAlpha(double alpha) { - shapeParameter.setParameterValue(0, alpha); - ratesKnown = false; - } - - /** - * @return alpha - */ - public final double getAlpha() { - return shapeParameter.getParameterValue(0); - } - - public Parameter getMutationRateParameter() { - return muParameter; - } - - public Parameter getAlphaParameter() { - return shapeParameter; - } - - public Parameter getPInvParameter() { - return invarParameter; - } - - public void setMutationRateParameter(Parameter parameter) { - if (muParameter != null) removeVariable(muParameter); - muParameter = parameter; - if (muParameter != null) addVariable(muParameter); - } - - public void setAlphaParameter(Parameter parameter) { - if (shapeParameter != null) removeVariable(shapeParameter); - shapeParameter = parameter; - if (shapeParameter != null) addVariable(shapeParameter); - } - - public void setPInvParameter(Parameter parameter) { - if (invarParameter != null) removeVariable(invarParameter); - invarParameter = parameter; - if (invarParameter != null) addVariable(invarParameter); - } - - // ***************************************************************** - // Interface SiteModel - // ***************************************************************** - - public boolean integrateAcrossCategories() { - return true; - } - - public int getCategoryCount() { - return categoryCount; - } - - public int getCategoryOfSite(int site) { - throw new IllegalArgumentException("Integrating across categories"); - } - - public double getRateForCategory(int category) { - synchronized (this) { - if (!ratesKnown) { - calculateCategoryRates(); - } - } - - final double mu = (muParameter != null) ? muParameter.getParameterValue(0) : 1.0; - - return categoryRates[category] * mu; - } - - public double[] getCategoryRates() { - synchronized (this) { - if (!ratesKnown) { - calculateCategoryRates(); - } - } - - final double mu = (muParameter != null) ? muParameter.getParameterValue(0) : 1.0; - - final double[] rates = new double[categoryRates.length]; - for (int i = 0; i < rates.length; i++) { - rates[i] = categoryRates[i] * mu; - } - - return rates; - } - - public void getTransitionProbabilities(double substitutions, double[] matrix) { - substitutionModel.getTransitionProbabilities(substitutions, matrix); - } - - /** - * Get the expected proportion of sites in this category. - * - * @param category the category number - * @return the proportion. - */ - public double getProportionForCategory(int category) { - synchronized (this) { - if (!ratesKnown) { - calculateCategoryRates(); - } - } - - return categoryProportions[category]; - } - - /** - * Get an array of the expected proportion of sites in this category. - * - * @return an array of the proportion. - */ - public double[] getCategoryProportions() { - synchronized (this) { - if (!ratesKnown) { - calculateCategoryRates(); - } - } - - return categoryProportions; - } - - /** - * discretization of gamma distribution with equal proportions in each - * category - */ - private void calculateCategoryRates() { - - double propVariable = 1.0; - int cat = 0; - - if (invarParameter != null) { - categoryRates[0] = 0.0; - categoryProportions[0] = invarParameter.getParameterValue(0); - - propVariable = 1.0 - categoryProportions[0]; - cat = 1; - } - - if (shapeParameter != null) { - - final double a = shapeParameter.getParameterValue(0); - double mean = 0.0; - final int gammaCatCount = categoryCount - cat; - - for (int i = 0; i < gammaCatCount; i++) { - - categoryRates[i + cat] = GammaDistribution.quantile((2.0 * i + 1.0) / (2.0 * gammaCatCount), a, 1.0 / a); - mean += categoryRates[i + cat]; - - categoryProportions[i + cat] = propVariable / gammaCatCount; - } - - mean = (propVariable * mean) / gammaCatCount; - - for (int i = 0; i < gammaCatCount; i++) { - - categoryRates[i + cat] /= mean; - } - } else { - categoryRates[cat] = 1.0 / propVariable; - categoryProportions[cat] = propVariable; - } - - - ratesKnown = true; - } - - /** - * Get the frequencyModel for this SiteModel. - * - * @return the frequencyModel. - */ - public FrequencyModel getFrequencyModel() { - return substitutionModel.getFrequencyModel(); - } - - /** - * Get the substitutionModel for this SiteModel. - * - * @return the substitutionModel. - */ - public SubstitutionModel getSubstitutionModel() { - return substitutionModel; - } - - // ***************************************************************** - // Interface ModelComponent - // ***************************************************************** - - protected void handleModelChangedEvent(Model model, Object object, int index) { - // Substitution model has changed so fire model changed event - listenerHelper.fireModelChanged(this, object, index); - } - - protected final void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) { - if (variable == shapeParameter) { - ratesKnown = false; - } else if (variable == invarParameter) { - ratesKnown = false; - } else { - // is the muParameter and nothing needs to be done - } - listenerHelper.fireModelChanged(this, variable, index); - } - - protected void storeState() { - } // no additional state needs storing - - protected void restoreState() { - ratesKnown = false; - } - - protected void acceptState() { - } // no additional state needs accepting - - /** - * the substitution model for these sites - */ - private SubstitutionModel substitutionModel = null; - - /** - * mutation rate parameter - */ - private Parameter muParameter; - - /** - * shape parameter - */ - private Parameter shapeParameter; - - /** - * invariant sites parameter - */ - private Parameter invarParameter; - - private boolean ratesKnown; - - private int categoryCount; - - private double[] categoryRates; - - private double[] categoryProportions; -} diff --git a/src/dr/oldevomodel/sitemodel/PairDistance.java b/src/dr/oldevomodel/sitemodel/PairDistance.java deleted file mode 100644 index 7fa9df38c5..0000000000 --- a/src/dr/oldevomodel/sitemodel/PairDistance.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * PairDistance.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.sitemodel; - -import java.util.List; - -/** - * @author alexei - */ -public class PairDistance implements Comparable { - int x, y; - double distance; - List gaps = null; - int alignmentLength; - - public PairDistance(int x, int y, double distance, List gaps, int alignmentLength) { - this.x = x; - this.y = y; - this.distance = distance; - this.gaps = gaps; - this.alignmentLength = alignmentLength; - } - - public int compareTo(PairDistance p) { - if (p.distance > distance) return -1; - if (p.distance < distance) return 1; - return 0; - } -} \ No newline at end of file diff --git a/src/dr/oldevomodel/sitemodel/SampleQuantileLociRates.java b/src/dr/oldevomodel/sitemodel/SampleQuantileLociRates.java deleted file mode 100644 index ae28816bfc..0000000000 --- a/src/dr/oldevomodel/sitemodel/SampleQuantileLociRates.java +++ /dev/null @@ -1,137 +0,0 @@ -/* - * SampleQuantileLociRates.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.sitemodel; - -import dr.inference.model.*; -import dr.inference.distribution.ParametricDistributionModel; -import dr.oldevomodelxml.sitemodel.SampleQuantileLociRatesParser; - -/** - * @author Chieh-Hsi Wu - * Sampling relative loci rates from an underlying distribution by sampling quantiles. - */ -public class SampleQuantileLociRates extends AbstractModel { - private CompoundParameter lociRates; - private Parameter rateQuantileParameter; - private ParametricDistributionModel distrModel; - private double normalizeRateTo; - private boolean normalize; - private double scaleFactor; - private double[] rates; - - - - public SampleQuantileLociRates( - CompoundParameter lociRates, - Parameter rateQuantileParameter, - ParametricDistributionModel model, - boolean normalize, - double normalizeLociRateTo) { - super(SampleQuantileLociRatesParser.SAMPLE_QUANTILE_LOCI_RATES); - - this.lociRates = lociRates; - - this.rateQuantileParameter = rateQuantileParameter; - //Force the boundaries of rateCategoryParameter to match the category count - //Parameter.DefaultBounds bound = new Parameter.DefaultBounds(0.99, 0.01, rateQuantileParameter.getDimension()); - //this.rateQuantileParameter.addBounds(bound); - - this.distrModel = model; - this.normalizeRateTo = normalizeLociRateTo; - this.normalize = normalize; - rates = new double[rateQuantileParameter.getDimension()]; - setupRates(); - setupRelativeRates(); - - addModel(distrModel); - addVariable(this.rateQuantileParameter); - } - - private void setupRates(){ - for(int i = 0; i < rates.length; i++){ - rates[i]= distrModel.quantile(rateQuantileParameter.getParameterValue(i)); - //System.err.println("setupRates: "+rates[i]); - } - } - - private void setupRates(int rateQuantileParameterIndex){ - rates[rateQuantileParameterIndex]= distrModel.quantile(rateQuantileParameter.getParameterValue(rateQuantileParameterIndex)); - } - - public void handleModelChangedEvent(Model model, Object object, int index) { - if (model == distrModel) { - setupRates(); - setupRelativeRates(); - //System.out.println("speed investigation 1"); - fireModelChanged(); - }else if (model == rateQuantileParameter) { - //System.out.println("speed investigation 2"); - setupRates(index); - fireModelChanged(null, index); - } - } - - protected final void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) { - //System.out.println("speed investigation 3"); - setupRates(index); - setupRelativeRates(); - fireModelChanged(null, index); - } - - protected void storeState() { - } - protected void acceptState() { - } - protected void restoreState() { - //setupRates(); - } - private void setupRelativeRates(){ - //System.err.println("computeFactor: "+normalize); - if(normalize){ - computeFactor(); - } - int lociCount = rateQuantileParameter.getDimension(); - for(int i = 0; i < lociCount; i ++){ - //System.err.println(rates[i]*scaleFactor); - lociRates.setParameterValue(i,rates[i]*scaleFactor); - } - - } - - private void computeFactor(){ - double sumRates = 0.0; - int lociCount = rateQuantileParameter.getDimension(); - for(int i = 0; i < lociCount; i++){ - //System.err.println("computeFactor: "+rates[i]); - sumRates += rates[i]; - } - scaleFactor = normalizeRateTo/(sumRates/lociCount); - } - - -} diff --git a/src/dr/oldevomodel/sitemodel/SampleStateAndCategoryModel.java b/src/dr/oldevomodel/sitemodel/SampleStateAndCategoryModel.java deleted file mode 100644 index c51057e3a5..0000000000 --- a/src/dr/oldevomodel/sitemodel/SampleStateAndCategoryModel.java +++ /dev/null @@ -1,322 +0,0 @@ -/* - * SampleStateAndCategoryModel.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.sitemodel; - -import dr.oldevomodel.substmodel.FrequencyModel; -import dr.oldevomodel.substmodel.SubstitutionModel; -import dr.oldevomodel.substmodel.YangCodonModel; -import dr.oldevomodelxml.sitemodel.SampleStateAndCategoryModelParser; -import dr.inference.model.*; - -import java.util.Vector; - - -/** - * SampleStateAndCategoryModel - A SiteModel that has a discrete distribution of substitutionmodels over sites - * designed for sampling of rate categories. - * - * @author Roald Forsberg - */ - -public class SampleStateAndCategoryModel extends AbstractModel implements SiteModel, CategorySampleModel { - - public static final double OMEGA_MAX_VALUE = 100.0; - public static final double OMEGA_MIN_VALUE = 0.0; - - - /** - * Constructor - */ - public SampleStateAndCategoryModel(Parameter muParameter, - Parameter categoriesParameter, - Vector substitutionModels) { - - super(SampleStateAndCategoryModelParser.SAMPLE_STATE_AND_CATEGORY_MODEL); - - - this.substitutionModels = substitutionModels; - - for (int i = 0; i < substitutionModels.size(); i++) { - addModel((SubstitutionModel) substitutionModels.elementAt(i)); - - } - - this.categoryCount = substitutionModels.size(); - sitesInCategory = new int[categoryCount]; - // stateCount = ((SubstitutionModel)substitutionModels.elementAt(0)).getDataType().getStateCount(); - - this.muParameter = muParameter; - addVariable(muParameter); - muParameter.addBounds(new Parameter.DefaultBounds(1000.0, 0.0, 1)); - - this.categoriesParameter = categoriesParameter; - addVariable(categoriesParameter); - - if (categoryCount > 1) { - for (int i = 0; i < categoryCount; i++) { - Parameter p = (Parameter)((YangCodonModel) substitutionModels.elementAt(i)).getVariable(0); - Parameter lower = null; - Parameter upper = null; - - if (i == 0) { - upper = (Parameter)((YangCodonModel) substitutionModels.elementAt(i + 1)).getVariable(0); - p.addBounds(new omegaBounds(lower, upper)); - } else { - if (i == (categoryCount - 1)) { - lower = (Parameter)((YangCodonModel) substitutionModels.elementAt(i - 1)).getVariable(0); - p.addBounds(new omegaBounds(lower, upper)); - } else { - upper = (Parameter)((YangCodonModel) substitutionModels.elementAt(i + 1)).getVariable(0); - lower = (Parameter)((YangCodonModel) substitutionModels.elementAt(i - 1)).getVariable(0); - p.addBounds(new omegaBounds(lower, upper)); - } - } - } - } - } - - // ***************************************************************** - // Interface SiteModel - // ***************************************************************** - - public SubstitutionModel getSubstitutionModel() { - return null; - } - - public boolean integrateAcrossCategories() { - return false; - } - - public int getCategoryCount() { - return categoryCount; - } - - public int getCategoryOfSite(int site) { - return (int) categoriesParameter.getParameterValue(site); - } - - public double getRateForCategory(int category) { - throw new RuntimeException("getRateForCategory not available in this siteModel"); - } - - public double[] getCategoryRates() { - throw new RuntimeException("getCategoryRates not available in this siteModel"); - } - - public double getSubstitutionsForCategory(int category, double time) { - throw new RuntimeException("getSubstitutionsForCategory not available in this siteModel"); - } - - public void getTransitionProbabilities(double substitutions, double[] matrix) { - throw new RuntimeException("getTransitionProbabilities not available in this siteModel"); - } - - /** - * Get the frequencyModel for this SiteModel. - * - * @return the frequencyModel. - */ - public FrequencyModel getFrequencyModel() { - return ((SubstitutionModel) substitutionModels.elementAt(0)).getFrequencyModel(); - } - - // ***************************************************************** - // Interface CategorySampleModel - // ***************************************************************** - - /** - * provide information to the categoriesParameter - * about the number of sites - */ - public void setCategoriesParameter(int siteCount) { - categoriesParameter.setDimension(siteCount); - categoriesParameter.addBounds(new Parameter.DefaultBounds(categoryCount, 0.0, siteCount)); - for (int i = 0; i < siteCount; i++) { - - int r = (int) (Math.random() * categoryCount); - categoriesParameter.setParameterValue(i, r); - } - - for (int j = 0; j < categoryCount; j++) { - sitesInCategory[j] = 0; - } - - for (int i = 0; i < siteCount; i++) { - int value = (int) categoriesParameter.getParameterValue(i); - sitesInCategory[value] = sitesInCategory[value] + 1; - } - } - - public void addSitesInCategoryCount(int category) { - sitesInCategory[category] = sitesInCategory[category] + 1; - } - - public void subtractSitesInCategoryCount(int category) { - sitesInCategory[category] = sitesInCategory[category] - 1; - } - - public int getSitesInCategoryCount(int category) { - return sitesInCategory[category]; - } - - public void toggleRandomSite() { - } - - - /** - * Get the expected proportion of sites in this category. - * - * @param category the category number - * @return the proportion. - */ - public double getProportionForCategory(int category) { - throw new IllegalArgumentException("Not integrating across categories"); - } - - /** - * Get an array of the expected proportion of sites in this category. - * - * @return an array of the proportion. - */ - public double[] getCategoryProportions() { - throw new IllegalArgumentException("Not integrating across categories"); - } - - // ***************************************************************** - // Interface ModelComponent - // ***************************************************************** - - protected void handleModelChangedEvent(Model model, Object object, int index) { - // Substitution model has changed so fire model changed event - listenerHelper.fireModelChanged(this, object, index); - } - - protected final void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) { - - if (variable == categoriesParameter) // instructs TreeLikelihood to set update flag for this pattern - listenerHelper.fireModelChanged(this, this, index); - } - - protected void storeState() { - } - - protected void restoreState() { - } - - protected void acceptState() { - } // no additional state needs accepting - - public String toString() { - StringBuffer s = new StringBuffer(); - - for (int i = 0; i < categoryCount; i++) { - s.append(sitesInCategory[i] + "\t"); - } - /*for(int i = 0; i < categoriesParameter.getDimension(); i++){ - t = (int)(categoriesParameter.getParameterValue(i));// get result as integer - s.append(String.valueOf(t) + "\t"); - }*/ - - return s.toString(); - } - - private class omegaBounds implements Bounds { - - private final Parameter lowerOmega, upperOmega; - - public omegaBounds(Parameter lowerOmega, Parameter upperOmega) { - - this.lowerOmega = lowerOmega; - this.upperOmega = upperOmega; - } - - public omegaBounds(Parameter nearestOmega, boolean isUpper) { - - if (isUpper) { - lowerOmega = nearestOmega; - upperOmega = null; - } else { - lowerOmega = null; - upperOmega = nearestOmega; - } - } - - /** - * @return the upper limit of this hypervolume in the given dimension. - */ - public Double getUpperLimit(int dimension) { - - if (dimension != 0) - throw new RuntimeException("omega parameters have wrong dimension " + dimension); - - if (upperOmega == null) - return OMEGA_MAX_VALUE; - else - return upperOmega.getParameterValue(dimension); - - } - - /** - * @return the lower limit of this hypervolume in the given dimension. - */ - public Double getLowerLimit(int dimension) { - - if (dimension != 0) - throw new RuntimeException("omega parameters have wrong dimension " + dimension); - - if (lowerOmega == null) - return OMEGA_MIN_VALUE; - - else - return lowerOmega.getParameterValue(dimension); - } - - /** - * @return the dimensionality of this hypervolume. - */ - public int getBoundsDimension() { - return 1; - } - - } - - /** - * mutation rate parameter - */ - private final Parameter muParameter; - - private final int[] sitesInCategory; - - private final Parameter categoriesParameter; - - private final Vector substitutionModels; - - private final int categoryCount; - -// private int stateCount; -} diff --git a/src/dr/oldevomodel/sitemodel/SampleStateModel.java b/src/dr/oldevomodel/sitemodel/SampleStateModel.java deleted file mode 100644 index 30b7182dae..0000000000 --- a/src/dr/oldevomodel/sitemodel/SampleStateModel.java +++ /dev/null @@ -1,338 +0,0 @@ -/* - * SampleStateModel.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.sitemodel; - -import dr.oldevomodel.substmodel.FrequencyModel; -import dr.oldevomodel.substmodel.SubstitutionModel; -import dr.oldevomodel.substmodel.YangCodonModel; -import dr.oldevomodelxml.sitemodel.SampleStateModelParser; -import dr.inference.model.*; - -import java.util.Vector; - - -/** - * DiscreteSampleModel - A SiteModel that has a discrete distribution of substitutionmodels over sites - * designed for sampling of rate categories. - * - * @author Roald Forsberg - */ - -public class SampleStateModel extends AbstractModel implements SiteModel { - public static final double OMEGA_MAX_VALUE = 100.0; - public static final double OMEGA_MIN_VALUE = 0.0; - - /** - * Constructor - */ - public SampleStateModel(Parameter muParameter, - Parameter proportionParameter, - Vector substitutionModels) { - - super(SampleStateModelParser.SAMPLE_STATE_MODEL); - - - this.substitutionModels = substitutionModels; - - for (int i = 0; i < substitutionModels.size(); i++) { - addModel((SubstitutionModel) substitutionModels.elementAt(i)); - } - - this.categoryCount = substitutionModels.size(); - -// stateCount = ((SubstitutionModel)substitutionModels.elementAt(0)).getDataType().getStateCount(); - - addVariable(muParameter); - muParameter.addBounds(new Parameter.DefaultBounds(1000.0, 0.0, 1)); - - this.proportionParameter = proportionParameter; - addVariable(proportionParameter); - proportionParameter.addBounds(new Parameter.DefaultBounds(1.0, 0.0, proportionParameter.getDimension())); - - proportionParameter.setParameterValue(0, (0.5)); - for (int i = 1; i < categoryCount; i++) { - proportionParameter.setParameterValue(i, (0.5 / (categoryCount - 1))); - } - - if (categoryCount > 1) { - for (int i = 0; i < categoryCount; i++) { - Parameter p = (Parameter) ((YangCodonModel) substitutionModels.elementAt(i)).getVariable(0); - Parameter lower = null; - Parameter upper = null; - - if (i == 0) { - upper = (Parameter) ((YangCodonModel) substitutionModels.elementAt(i + 1)).getVariable(0); - p.addBounds(new omegaBounds(lower, upper)); - } else { - if (i == (categoryCount - 1)) { - lower = (Parameter) ((YangCodonModel) substitutionModels.elementAt(i - 1)).getVariable(0); - p.addBounds(new omegaBounds(lower, upper)); - } else { - upper = (Parameter) ((YangCodonModel) substitutionModels.elementAt(i + 1)).getVariable(0); - lower = (Parameter) ((YangCodonModel) substitutionModels.elementAt(i - 1)).getVariable(0); - p.addBounds(new omegaBounds(lower, upper)); - } - } - } - } - } - - // ***************************************************************** - // Interface SiteModel - // ***************************************************************** - - public SubstitutionModel getSubstitutionModel() { - return null; - } - - public boolean integrateAcrossCategories() { - return true; - } - - public int getCategoryCount() { - return categoryCount; - } - - public int getCategoryOfSite(int site) { - throw new IllegalArgumentException("Integrating across categories"); - } - - public double[] getCategoryRates() { - throw new RuntimeException("getCategoryRates not available in this siteModel"); - } - - public double getRateForCategory(int category) { - throw new RuntimeException("getRateForCategory not available in this siteModel"); - } - - public double getSubstitutionsForCategory(int category, double time) { - throw new RuntimeException("getSubstitutionsForCategory not available in this siteModel"); - } - - public void getTransitionProbabilities(double substitutions, double[] matrix) { - throw new RuntimeException("getTransitionProbabilities not available in this siteModel"); - } - - /** - * Get the frequencyModel for this SiteModel. - * - * @return the frequencyModel. - */ - public FrequencyModel getFrequencyModel() { - return ((SubstitutionModel) substitutionModels.elementAt(0)).getFrequencyModel(); - } - - /** - * Get the expected proportion of sites in this category. - * - * @param category the category number - * @return the proportion. - */ - public double getProportionForCategory(int category) { - return proportionParameter.getParameterValue(category); - } - - /** - * Get an array of the expected proportion of sites in this category. - * - * @return an array of the proportion. - */ - public double[] getCategoryProportions() { - double[] probs = new double[categoryCount]; - - for (int i = 0; i < categoryCount; i++) { - probs[i] = proportionParameter.getParameterValue(i); - } - - return probs; - } - - // ***************************************************************** - // Interface ModelComponent - // ***************************************************************** - - protected void handleModelChangedEvent(Model model, Object object, int index) { - // Substitution model has changed so fire model changed event - listenerHelper.fireModelChanged(this, object, index); - } - - - protected final void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) { - /*if(categoryCount > 1){ - for(int i = 0; i < categoryCount; i++){ - if(parameter == classSizes[i] && i == 0) // proportions have changed - resetProportions(i+1);// adjust the proportion of class above - if(parameter == classSizes[i] && i != 0) // proportions have changed - resetProportions(i-1);// adjust the proportion of class below - } - } else{}*/ - } - - protected void storeState() { - } - - protected void restoreState() { - } - - protected void acceptState() { - } // no additional state needs accepting - - public String toString() { - StringBuffer s = new StringBuffer(); - - return s.toString(); - } - - /*private void resetProportions(int classToAlter){ - double[] probs = getCategoryProportions(); - double sum = 0.0; - double current = classSizes[classToAlter].getParameterValue(0); - for(int i = 0; i < categoryCount; i++){ - sum += probs[i]; - } - sum = 1 - sum; - classSizes[classToAlter].setParameterValue(0,(current+sum)); - }*/ - - private class omegaBounds implements Bounds { - - private final Parameter lowerOmega, upperOmega; - - public omegaBounds(Parameter lowerOmega, Parameter upperOmega) { - - this.lowerOmega = lowerOmega; - this.upperOmega = upperOmega; - } - - public omegaBounds(Parameter nearestOmega, boolean isUpper) { - - if (isUpper) { - lowerOmega = nearestOmega; - upperOmega = null; - } else { - lowerOmega = null; - upperOmega = nearestOmega; - } - } - - /** - * @return the upper limit of this hypervolume in the given dimension. - */ - public Double getUpperLimit(int dimension) { - - if (dimension != 0) - throw new RuntimeException("omega parameters have wrong dimension " + dimension); - - if (upperOmega == null) - return OMEGA_MAX_VALUE; - else - return upperOmega.getParameterValue(dimension); - - } - - /** - * @return the lower limit of this hypervolume in the given dimension. - */ - public Double getLowerLimit(int dimension) { - - if (dimension != 0) - throw new RuntimeException("omega parameters have wrong dimension " + dimension); - - if (lowerOmega == null) - return OMEGA_MIN_VALUE; - - else - return lowerOmega.getParameterValue(dimension); - } - - /** - * @return the dimensionality of this hypervolume. - */ - public int getBoundsDimension() { - return 1; - } - - } - - class classSizeBounds implements Bounds { - - private final Parameter catProportionUnder; - private final Parameter catProportionAbove; - private final Parameter catProportion; - - public classSizeBounds(Parameter catProportion, Parameter catProportionUnder, Parameter catProportionAbove) { - - this.catProportionUnder = catProportionUnder; - this.catProportionAbove = catProportionAbove; - this.catProportion = catProportion; - } - - /** - * @return the upper limit of this hypervolume in the given dimension. - */ - public Double getUpperLimit(int dimension) { - - if (dimension != 0) - throw new RuntimeException("class size parameters have wrong dimension " + dimension); - if (catProportionUnder == null) - return catProportion.getParameterValue(dimension) + catProportionAbove.getParameterValue(dimension); - else - return catProportion.getParameterValue(dimension) + catProportionUnder.getParameterValue(dimension); - } - - /** - * @return the lower limit of this hypervolume in the given dimension. - */ - public Double getLowerLimit(int dimension) { - - if (dimension != 0) - throw new RuntimeException("class size parameters have wrong dimension " + dimension); - - return 0.0; - } - - /** - * @return the dimensionality of this hypervolume. - */ - public int getBoundsDimension() { - return 1; - } - - } - - private final Vector substitutionModels; - - /** - * class size parameters - */ - private final Parameter proportionParameter; - - private final int categoryCount; - -// private int stateCount; -} diff --git a/src/dr/oldevomodel/sitemodel/ScoreMatrix.java b/src/dr/oldevomodel/sitemodel/ScoreMatrix.java deleted file mode 100644 index dd9dd66f68..0000000000 --- a/src/dr/oldevomodel/sitemodel/ScoreMatrix.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * ScoreMatrix.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.sitemodel; - -import dr.evolution.alignment.SitePatterns; - -/** - * @author alexei - */ -public class ScoreMatrix { - - SiteModel siteModel; - double time; - double[] matrix; - - double[] logp; - - // base frequencies - - double[][] logOddScores; - double[][] pscores; - int stateCount; - - public ScoreMatrix(SiteModel siteModel, double time) { - this.siteModel = siteModel; - - logp = siteModel.getSubstitutionModel().getFrequencyModel().getFrequencies(); - - for (int i = 0; i < logp.length; i++) { - logp[i] = Math.log(logp[i]); - } - - stateCount = siteModel.getFrequencyModel().getFrequencyCount(); - matrix = new double[stateCount*stateCount]; - pscores = new double[stateCount][stateCount]; - logOddScores = new double[stateCount][stateCount]; - - setTime(time); - } - - public void setTime(double time) { - this.time = time; - siteModel.getSubstitutionModel().getTransitionProbabilities(time, matrix); - - //base frequencies - - for (int i = 0; i < stateCount; i++) { - for (int j = 0; j < stateCount; j++) { - pscores[i][j] = Math.log(matrix[i*stateCount + j]); - logOddScores[i][j] = pscores[i][j] - logp[i] - logp[j]; - } - } - } - - /** - * @param i state in first sequences - * @param j state in second sequences - * @return the score of aligning state i with state j - */ - public final double getScore(int i, int j) { - return pscores[i][j] - logp[j]; - } - - public final double getScore(SitePatterns patterns) { - - if (patterns.getPatternLength() != 2) throw new IllegalArgumentException(); - - double logL = 0.0; - for (int i = 0; i < patterns.getPatternCount(); i++) { - double weight = patterns.getPatternWeight(i); - int[] pattern = patterns.getPattern(i); - - int x = pattern[0]; - int y = pattern[1]; - - if (x < stateCount && y < stateCount) { - logL += getScore(x,y) * weight; - } - - } - return logL; - } -} diff --git a/src/dr/oldevomodel/sitemodel/SiteModel.java b/src/dr/oldevomodel/sitemodel/SiteModel.java deleted file mode 100644 index bcc792b82f..0000000000 --- a/src/dr/oldevomodel/sitemodel/SiteModel.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * SiteModel.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.sitemodel; - -import dr.oldevomodel.substmodel.FrequencyModel; -import dr.oldevomodel.substmodel.SubstitutionModel; - -/** - * SiteModel - Specifies how rates and substitution models vary across sites. - * - * @author Andrew Rambaut - * @author Alexei Drummond - */ - -public interface SiteModel extends SiteRateModel { - - public static final String SITE_MODEL = "siteModel"; - - /** - * Get this site model's substitution model - * - * @return the substitution model - */ - SubstitutionModel getSubstitutionModel(); - - /** - * Specifies whether SiteModel should integrate over the different categories at - * each site. If true, the SiteModel will calculate the likelihood of each site - * for each category. If false it will assume that there is each site can have a - * different category. - * - * @return the boolean - */ - boolean integrateAcrossCategories(); // TODO Consider moving into SiteRateModel - - /** - * Get the category of a particular site. If integrateAcrossCategories is true. - * then throws an IllegalArgumentException. - * - * @param site the index of the site - * @return the index of the category - */ - int getCategoryOfSite(int site); // TODO Consider moving into SiteRateModel - - /** - * Get the frequencyModel for this SiteModel. - * - * @return the frequencyModel. - */ - FrequencyModel getFrequencyModel(); -} \ No newline at end of file diff --git a/src/dr/oldevomodel/sitemodel/SiteRateModel.java b/src/dr/oldevomodel/sitemodel/SiteRateModel.java deleted file mode 100644 index c63ca42270..0000000000 --- a/src/dr/oldevomodel/sitemodel/SiteRateModel.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * SiteRateModel.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.sitemodel; - -import dr.inference.model.Model; - -/** - * @author Alexei J. Drummond - * @author Andrew Rambaut - * @author Marc A. Suchard - *

- * An attempt to harmonize **.beagle.**.SiteRateModel and **.SiteModel - */ - -public interface SiteRateModel extends Model { - - /** - * @return the number of categories of substitution processes - */ - int getCategoryCount(); - - /** - * Get an array of the relative rates of sites in each category. These - * may include the 'mu' parameter, an overall scaling of the siteRateModel. - * - * @return an array of the rates. - */ - double[] getCategoryRates(); - - /** - * Get an array of the expected proportion of sites in each category. - * - * @return an array of the proportions. - */ - double[] getCategoryProportions(); - - /** - * Get the rate for a particular category. This may include the 'mu' - * parameter, an overall scaling of the siteRateModel. - * - * @param category the category number - * @return the rate. - */ - double getRateForCategory(int category); - - /** - * Get the expected proportion of sites in this category. - * - * @param category the category number - * @return the proportion. - */ - double getProportionForCategory(int category); - -} diff --git a/src/dr/oldevomodel/substmodel/AbstractAminoAcidModel.java b/src/dr/oldevomodel/substmodel/AbstractAminoAcidModel.java deleted file mode 100644 index fb51a64021..0000000000 --- a/src/dr/oldevomodel/substmodel/AbstractAminoAcidModel.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * AbstractAminoAcidModel.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.substmodel; - -import dr.evolution.datatype.AminoAcids; - -/** - * base class of substitution models for amino acids - * - * - * @author Andrew Rambaut - */ -public abstract class AbstractAminoAcidModel extends AbstractSubstitutionModel -{ - // Constructor - public AbstractAminoAcidModel(String name, FrequencyModel freqModel) - { - super(name, AminoAcids.INSTANCE, freqModel); - } -} diff --git a/src/dr/oldevomodel/substmodel/AbstractCodonModel.java b/src/dr/oldevomodel/substmodel/AbstractCodonModel.java deleted file mode 100644 index bdf4612c06..0000000000 --- a/src/dr/oldevomodel/substmodel/AbstractCodonModel.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * AbstractCodonModel.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.substmodel; - -import dr.evolution.datatype.Codons; -import dr.evolution.datatype.GeneticCode; - -/** - * base class for codon rate matrices - * - * - * @author Andrew Rambaut - * @author Korbinian Strimmer - */ -abstract public class AbstractCodonModel extends AbstractSubstitutionModel { - - // Constructor - public AbstractCodonModel(String name, Codons codonDataType, FrequencyModel freqModel) - { - super(name, codonDataType, freqModel); - - this.codonDataType = codonDataType; - this.geneticCode = codonDataType.getGeneticCode(); - } - - protected void frequenciesChanged() { - // Nothing to precalculate - } - - protected void ratesChanged() { - // Nothing to precalculate - } - - protected Codons codonDataType; - protected GeneticCode geneticCode; -} \ No newline at end of file diff --git a/src/dr/oldevomodel/substmodel/AbstractCovarionDNAModel.java b/src/dr/oldevomodel/substmodel/AbstractCovarionDNAModel.java deleted file mode 100644 index 72cd5175ff..0000000000 --- a/src/dr/oldevomodel/substmodel/AbstractCovarionDNAModel.java +++ /dev/null @@ -1,239 +0,0 @@ -/* - * AbstractCovarionDNAModel.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.substmodel; - -import dr.evolution.datatype.OldHiddenNucleotides; -import dr.inference.model.Parameter; - -/** - * A general time reversible model of nucleotide evolution with - * covarion hidden rate categories. - * - * @author Alexei Drummond - */ -abstract public class AbstractCovarionDNAModel extends AbstractSubstitutionModel { - - public static final String HIDDEN_CLASS_RATES = "hiddenClassRates"; - public static final String SWITCHING_RATES = "switchingRates"; - public static final String FREQUENCIES = "frequencies"; - - /** - * @param name the name of the covarion substitution model - * @param dataType the data type - * @param freqModel the equlibrium frequencies - * @param hiddenClassRates the relative rates of the hidden categories - * (first hidden category has rate 1.0 so this parameter - * has dimension one less than number of hidden categories. - * each hidden category. - * @param switchingRates rate of switching between hidden categories - */ - public AbstractCovarionDNAModel(String name, - OldHiddenNucleotides dataType, - Parameter hiddenClassRates, - Parameter switchingRates, - FrequencyModel freqModel) { - - super(name, dataType, freqModel); - - hiddenClassCount = dataType.getHiddenClassCount(); - - this.hiddenClassRates = hiddenClassRates; - this.switchingRates = switchingRates; - - assert hiddenClassRates.getDimension() == hiddenClassCount - 1; - - int hiddenClassCount = getHiddenClassCount(); - - int switchingClassCount = hiddenClassCount * (hiddenClassCount - 1) / 2; - - if (switchingRates.getDimension() != switchingClassCount) { - throw new IllegalArgumentException("switching rate parameter must have " + - switchingClassCount + " rates for " + hiddenClassCount + " classes"); - } - addVariable(switchingRates); - addVariable(hiddenClassRates); - constructRateMatrixMap(); - } - - /** - * @return the relative rates of A<->C, A<->G, A<->T, C<->G, C<->T and G<->T substitutions - */ - abstract double[] getRelativeDNARates(); - - /** - * @return the number of hidden classes in this covarion model. - */ - public final int getHiddenClassCount() { - return hiddenClassCount; - } - - public void frequenciesChanged() { - // DO NOTHING - } - - public void ratesChanged() { - setupRelativeRates(); - } - - protected void setupRelativeRates() { - - double[] phi = switchingRates.getParameterValues(); - double[] rr = getRelativeDNARates(); - double[] hiddenRates = hiddenClassRates.getParameterValues(); - - for (int i = 0; i < rateCount; i++) { - if (rateMatrixMap[i] == 0) { - relativeRates[i] = 0.0; - } else if (rateMatrixMap[i] < 7) { - if (hiddenClassMap[i] == 0) { - relativeRates[i] = rr[rateMatrixMap[i] - 1]; - } else { - relativeRates[i] = rr[rateMatrixMap[i] - 1] * hiddenRates[hiddenClassMap[i] - 1]; - } - } else { - relativeRates[i] = phi[rateMatrixMap[i] - 7]; - } - } - } - - /** - * Construct a map of the rate classes in the rate matrix: - * 0: class and nucleotide change - * 1: A <-> C - * 2: A <-> G - * 3: A <-> T - * 4: C <-> G - * 5: C <-> T - * 6: G <-> T - * 7: 0 <-> 1 class change - * 8: 0 <-> 2 class change - * et cetera - */ - private void constructRateMatrixMap() { - - byte rateClass; - int fromNuc, toNuc; - int fromRate, toRate; - int count = 0; - - rateMatrixMap = new byte[rateCount]; - hiddenClassMap = new byte[rateCount]; - - for (int i = 0; i < stateCount; i++) { - - for (int j = i + 1; j < stateCount; j++) { - - fromNuc = i % 4; - toNuc = j % 4; - fromRate = i / 4; - toRate = j / 4; - - if (fromNuc == toNuc) { - // rate transition - if (fromRate == toRate) { - throw new RuntimeException("Shouldn't be possible"); - } - - rateClass = (byte) (7 + getIndex(fromRate, toRate, hiddenClassCount)); - } else if (fromRate != toRate) { - rateClass = 0; - } else { - rateClass = (byte) (1 + getIndex(fromNuc, toNuc, 4)); - } - - rateMatrixMap[count] = rateClass; - hiddenClassMap[count] = (byte) fromRate; - count++; - } - } - } - - private int getIndex(int from, int to, int size) { - int index = 0; - - int f = from; - while (f > 0) { - index += size - 1; - f -= 1; - size -= 1; - } - index += to - from - 1; - - return index; - } - - /** - * Normalize rate matrix to one expected substitution per unit time - * - * @param matrix the matrix to normalize to one expected substitution - * @param pi the equilibrium distribution of states - */ - void normalize(double[][] matrix, double[] pi) { - double subst = 0.0; - int dimension = pi.length; - - for (int i = 0; i < dimension; i++) { - subst += -matrix[i][i] * pi[i]; - } - - // normalize, including switches - for (int i = 0; i < dimension; i++) { - for (int j = 0; j < dimension; j++) { - matrix[i][j] = matrix[i][j] / subst; - } - } - - double switchingProportion = 0.0; - for (int i = 0; i < hiddenClassCount; i++) { - for (int j = i + 1; j < hiddenClassCount; j++) { - for (int l = 0; l < 4; l++) { - - int x = i * 4 + l; - int y = j * 4 + l; - - switchingProportion += matrix[x][y] * pi[y]; - switchingProportion += matrix[y][x] * pi[x]; - } - } - } - // normalize, removing switches - for (int i = 0; i < dimension; i++) { - for (int j = 0; j < dimension; j++) { - matrix[i][j] = matrix[i][j] / (1.0 - switchingProportion); - } - } - } - - Parameter switchingRates; - Parameter hiddenClassRates; - - byte[] rateMatrixMap; - byte[] hiddenClassMap; - - private int hiddenClassCount; -} diff --git a/src/dr/oldevomodel/substmodel/AbstractCovarionModel.java b/src/dr/oldevomodel/substmodel/AbstractCovarionModel.java deleted file mode 100644 index 15d79bf3ad..0000000000 --- a/src/dr/oldevomodel/substmodel/AbstractCovarionModel.java +++ /dev/null @@ -1,923 +0,0 @@ -/* - * AbstractCovarionModel.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.substmodel; - -import dr.evolution.datatype.DataType; -import dr.inference.model.AbstractModel; -import dr.inference.model.Model; -import dr.inference.model.Parameter; -import dr.inference.model.Variable; -import dr.math.MachineAccuracy; - -import java.util.LinkedList; -import java.util.List; - -/** - * An abstract base class for substitution models. - * - * @author Alexei Drummond - */ - -public abstract class AbstractCovarionModel extends AbstractModel implements SubstitutionModel { - - public static final String MODEL = "model"; - - protected DataType dataType = null; - - protected double[][] unnormalizedQ; - protected double[][] storedUnnormalizedQ; - - private FrequencyModel freqModel; - - protected int stateCount; - - private boolean eigenInitialised = false; - protected boolean updateMatrix = true; - private boolean storedUpdateMatrix = true; - - AbstractCovarionModel(String name, DataType dataType, Parameter frequencies, Parameter hiddenFrequencies) { - super(name); - - this.dataType = dataType; - - setStateCount(dataType.getStateCount()); - - updateMatrix = true; - - freqModel = new CovarionFrequencyModel(dataType, frequencies, hiddenFrequencies); - addModel(freqModel); - } - - private void setStateCount(int stateCount) { - eigenInitialised = false; - - this.stateCount = stateCount; - - unnormalizedQ = new double[stateCount][stateCount]; - storedUnnormalizedQ = new double[stateCount][stateCount]; - } - - // ***************************************************************** - // Interface Model - // ***************************************************************** - - protected void handleModelChangedEvent(Model model, Object object, int index) { - // frequencyModel changed! - updateMatrix = true; - frequenciesChanged(); - } - - protected final void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) { - // relativeRates changed - updateMatrix = true; - ratesChanged(); - } - - protected void storeState() { - - storedUpdateMatrix = updateMatrix; - - System.arraycopy(Eval, 0, storedEval, 0, stateCount); - for (int i = 0; i < stateCount; i++) { - System.arraycopy(unnormalizedQ[i], 0, storedUnnormalizedQ[i], 0, stateCount); - System.arraycopy(Ievc[i], 0, storedIevc[i], 0, stateCount); - System.arraycopy(Evec[i], 0, storedEvec[i], 0, stateCount); - } - - } - - /** - * Restore the additional stored state - */ - protected void restoreState() { - - updateMatrix = storedUpdateMatrix; - - double[][] tmp2 = storedIevc; - storedIevc = Ievc; - Ievc = tmp2; - - tmp2 = storedEvec; - storedEvec = Evec; - Evec = tmp2; - - tmp2 = storedUnnormalizedQ; - storedUnnormalizedQ = unnormalizedQ; - unnormalizedQ = tmp2; - } - - protected void acceptState() { - } // nothing to do - - abstract protected void frequenciesChanged(); - - abstract protected void ratesChanged(); - - abstract protected void setupUnnormalizedQMatrix(); - - public double[][] getEigenVectors() { - throw new UnsupportedOperationException("Not yet implemented."); - } - - public double[][] getInverseEigenVectors() { - throw new UnsupportedOperationException("Not yet implemented."); - } - - public double[] getEigenValues() { - throw new UnsupportedOperationException("Not yet implemented."); - } - - public FrequencyModel getFrequencyModel() { - - return freqModel; - } - - /** - * @return the data type - */ - public DataType getDataType() { - return dataType; - } - - /** - * get the complete transition probability matrix for the given distance - * - * @param distance the expected number of substitutions - * @param matrix an array to store the matrix - */ - public void getTransitionProbabilities(double distance, double[] matrix) { - int i, j, k; - double temp; - - // this must be synchronized to avoid being called simultaneously by - // two different likelihood threads - AJD - synchronized (this) { - //if (updateMatrix) { - setupMatrix(); - //} - } - - // implemented a pool of iexp matrices to support multiple threads - // without creating a new matrix each call. - AJD - double[][] iexp = popiexp(); - for (i = 0; i < stateCount; i++) { - temp = Math.exp(distance * Eval[i]); - for (j = 0; j < stateCount; j++) { - iexp[i][j] = Ievc[i][j] * temp; - } - } - - int u = 0; - for (i = 0; i < stateCount; i++) { - for (j = 0; j < stateCount; j++) { - temp = 0.0; - for (k = 0; k < stateCount; k++) { - temp += Evec[i][k] * iexp[k][j]; - } - - matrix[u] = Math.abs(temp); - u++; - } - } - pushiexp(iexp); - } - - /** - * setup substitution matrix - */ - public void setupMatrix() { - setupUnnormalizedQMatrix(); - - if (!eigenInitialised) - initialiseEigen(); - - int i, j; - - // Set the instantaneous rate matrix - for (i = 0; i < stateCount; i++) { - for (j = 0; j < stateCount; j++) { - amat[i][j] = unnormalizedQ[i][j]; - } - } - makeValid(amat, stateCount); - normalize(amat, freqModel.getFrequencies()); - - // copy q matrix for unit testing - for (i = 0; i < amat.length; i++) { - System.arraycopy(amat[i], 0, q[i], 0, amat[i].length); - } - - // compute eigenvalues and eigenvectors - elmhes(amat, ordr, stateCount); - eltran(amat, Evec, ordr, stateCount); - hqr2(stateCount, 1, stateCount, amat, Evec, Eval, evali); - luinverse(Evec, Ievc, stateCount); - - updateMatrix = false; - } - - // Make it a valid rate matrix (make sum of rows = 0) - void makeValid(double[][] matrix, int dimension) { - for (int i = 0; i < dimension; i++) { - double sum = 0.0; - for (int j = 0; j < dimension; j++) { - if (i != j) - sum += matrix[i][j]; - } - matrix[i][i] = -sum; - } - } - - /** - * Normalize rate matrix to one expected substitution per unit time - * - * @param matrix the matrix to normalize to one expected substitution - * @param pi the equilibrium distribution of states - */ - void normalize(double[][] matrix, double[] pi) { - double subst = 0.0; - int dimension = pi.length; - - for (int i = 0; i < dimension; i++) - subst += -matrix[i][i] * pi[i]; - - for (int i = 0; i < dimension; i++) { - for (int j = 0; j < dimension; j++) { - matrix[i][j] = matrix[i][j] / subst; - } - } - } - - /** - * allocate memory for the Eigen routines - */ - private void initialiseEigen() { - - Eval = new double[stateCount]; - Evec = new double[stateCount][stateCount]; - Ievc = new double[stateCount][stateCount]; - - storedEval = new double[stateCount]; - storedEvec = new double[stateCount][stateCount]; - storedIevc = new double[stateCount][stateCount]; - - amat = new double[stateCount][stateCount]; - q = new double[stateCount][stateCount]; - - ordr = new int[stateCount]; - evali = new double[stateCount]; - - eigenInitialised = true; - updateMatrix = true; - } - - // Eigenvalues, eigenvectors, and inverse eigenvectors - private double[] Eval; - private double[] storedEval; - private double[][] Evec; - private double[][] storedEvec; - private double[][] Ievc; - private double[][] storedIevc; - - List iexpPool = new LinkedList(); - - private int[] ordr; - private double[] evali; - double amat[][]; - private double q[][]; - - public double[][] getQ() { - return q; - } - - private synchronized double[][] popiexp() { - - if (iexpPool.size() == 0) { - iexpPool.add(new double[stateCount][stateCount]); - } - return iexpPool.remove(0); - } - - private synchronized void pushiexp(double[][] iexp) { - iexpPool.add(0, iexp); - } - - private void elmhes(double[][] a, int[] ordr, int n) { - int m, j, i; - double y, x; - - for (i = 0; i < n; i++) { - ordr[i] = 0; - } - for (m = 2; m < n; m++) { - x = 0.0; - i = m; - for (j = m; j <= n; j++) { - if (Math.abs(a[j - 1][m - 2]) > Math.abs(x)) { - x = a[j - 1][m - 2]; - i = j; - } - } - ordr[m - 1] = i; - if (i != m) { - for (j = m - 2; j < n; j++) { - y = a[i - 1][j]; - a[i - 1][j] = a[m - 1][j]; - a[m - 1][j] = y; - } - for (j = 0; j < n; j++) { - y = a[j][i - 1]; - a[j][i - 1] = a[j][m - 1]; - a[j][m - 1] = y; - } - } - if (x != 0.0) { - for (i = m; i < n; i++) { - y = a[i][m - 2]; - if (y != 0.0) { - y /= x; - a[i][m - 2] = y; - for (j = m - 1; j < n; j++) { - a[i][j] -= y * a[m - 1][j]; - } - for (j = 0; j < n; j++) { - a[j][m - 1] += y * a[j][i]; - } - } - } - } - } - } - - // Helper variables for mcdiv - private double cr, ci; - - private void mcdiv(double ar, double ai, double br, double bi) { - double s, ars, ais, brs, bis; - - s = Math.abs(br) + Math.abs(bi); - ars = ar / s; - ais = ai / s; - brs = br / s; - bis = bi / s; - s = brs * brs + bis * bis; - cr = (ars * brs + ais * bis) / s; - ci = (ais * brs - ars * bis) / s; - } - - void hqr2(int n, int low, int hgh, double[][] h, double[][] zz, - double[] wr, double[] wi) throws ArithmeticException { - int i, j, k, l = 0, m, en, na, itn, its; - double p = 0, q = 0, r = 0, s = 0, t, w, x = 0, y, ra, sa, vi, vr, z = 0, norm, tst1, tst2; - boolean notLast; - - - norm = 0.0; - k = 1; - /* store isolated roots and compute matrix norm */ - for (i = 0; i < n; i++) { - for (j = k - 1; j < n; j++) { - norm += Math.abs(h[i][j]); - } - k = i + 1; - if (i + 1 < low || i + 1 > hgh) { - wr[i] = h[i][i]; - wi[i] = 0.0; - } - } - en = hgh; - t = 0.0; - itn = n * 30; - while (en >= low) { /* search for next eigenvalues */ - its = 0; - na = en - 1; - while (en >= 1) { - /* look for single small sub-diagonal element */ - boolean fullLoop = true; - for (l = en; l > low; l--) { - s = Math.abs(h[l - 2][l - 2]) + Math.abs(h[l - 1][l - 1]); - if (s == 0.0) { - s = norm; - } - tst1 = s; - tst2 = tst1 + Math.abs(h[l - 1][l - 2]); - if (tst2 == tst1) { - fullLoop = false; - break; - } - } - if (fullLoop) { - l = low; - } - - x = h[en - 1][en - 1]; /* form shift */ - if (l == en || l == na) { - break; - } - if (itn == 0) { - /* eigenvalues have not converged */ - System.out.println("Eigenvalues not converged"); - throw new ArithmeticException(); - } - y = h[na - 1][na - 1]; - w = h[en - 1][na - 1] * h[na - 1][en - 1]; - /* form exceptional shift */ - if (its == 10 || its == 20) { - t += x; - for (i = low - 1; i < en; i++) { - h[i][i] -= x; - } - s = Math.abs(h[en - 1][na - 1]) + Math.abs(h[na - 1][en - 3]); - x = 0.75 * s; - y = x; - w = -0.4375 * s * s; - } - its++; - itn--; - /* look for two consecutive small sub-diagonal elements */ - for (m = en - 2; m >= l; m--) { - z = h[m - 1][m - 1]; - r = x - z; - s = y - z; - p = (r * s - w) / h[m][m - 1] + h[m - 1][m]; - q = h[m][m] - z - r - s; - r = h[m + 1][m]; - s = Math.abs(p) + Math.abs(q) + Math.abs(r); - p /= s; - q /= s; - r /= s; - if (m == l) { - break; - } - tst1 = Math.abs(p) * (Math.abs(h[m - 2][m - 2]) + Math.abs(z) + Math.abs(h[m][m])); - tst2 = tst1 + Math.abs(h[m - 1][m - 2]) * (Math.abs(q) + Math.abs(r)); - if (tst2 == tst1) { - break; - } - } - for (i = m + 2; i <= en; i++) { - h[i - 1][i - 3] = 0.0; - if (i != m + 2) { - h[i - 1][i - 4] = 0.0; - } - } - for (k = m; k <= na; k++) { - notLast = k != na; - if (k != m) { - p = h[k - 1][k - 2]; - q = h[k][k - 2]; - r = 0.0; - if (notLast) { - r = h[k + 1][k - 2]; - } - x = Math.abs(p) + Math.abs(q) + Math.abs(r); - if (x != 0.0) { - p /= x; - q /= x; - r /= x; - } - } - if (x != 0.0) { - if (p < 0.0) { /* sign */ - s = -Math.sqrt(p * p + q * q + r * r); - } else { - s = Math.sqrt(p * p + q * q + r * r); - } - if (k != m) { - h[k - 1][k - 2] = -s * x; - } else if (l != m) { - h[k - 1][k - 2] = -h[k - 1][k - 2]; - } - p += s; - x = p / s; - y = q / s; - z = r / s; - q /= p; - r /= p; - if (!notLast) { - for (j = k - 1; j < n; j++) { /* row modification */ - p = h[k - 1][j] + q * h[k][j]; - h[k - 1][j] -= p * x; - h[k][j] -= p * y; - } - j = (en < (k + 3)) ? en : (k + 3); /* min */ - for (i = 0; i < j; i++) { /* column modification */ - p = x * h[i][k - 1] + y * h[i][k]; - h[i][k - 1] -= p; - h[i][k] -= p * q; - } - /* accumulate transformations */ - for (i = low - 1; i < hgh; i++) { - p = x * zz[i][k - 1] + y * zz[i][k]; - zz[i][k - 1] -= p; - zz[i][k] -= p * q; - } - } else { - for (j = k - 1; j < n; j++) { /* row modification */ - p = h[k - 1][j] + q * h[k][j] + r * h[k + 1][j]; - h[k - 1][j] -= p * x; - h[k][j] -= p * y; - h[k + 1][j] -= p * z; - } - j = (en < (k + 3)) ? en : (k + 3); /* min */ - for (i = 0; i < j; i++) { /* column modification */ - p = x * h[i][k - 1] + y * h[i][k] + z * h[i][k + 1]; - h[i][k - 1] -= p; - h[i][k] -= p * q; - h[i][k + 1] -= p * r; - } - /* accumulate transformations */ - for (i = low - 1; i < hgh; i++) { - p = x * zz[i][k - 1] + y * zz[i][k] + - z * zz[i][k + 1]; - zz[i][k - 1] -= p; - zz[i][k] -= p * q; - zz[i][k + 1] -= p * r; - } - } - } - } /* for k */ - } /* while infinite loop */ - if (l == en) { /* one root found */ - h[en - 1][en - 1] = x + t; - wr[en - 1] = h[en - 1][en - 1]; - wi[en - 1] = 0.0; - en = na; - continue; - } - y = h[na - 1][na - 1]; - w = h[en - 1][na - 1] * h[na - 1][en - 1]; - p = (y - x) / 2.0; - q = p * p + w; - z = Math.sqrt(Math.abs(q)); - h[en - 1][en - 1] = x + t; - x = h[en - 1][en - 1]; - h[na - 1][na - 1] = y + t; - if (q >= 0.0) { /* real pair */ - if (p < 0.0) { /* sign */ - z = p - Math.abs(z); - } else { - z = p + Math.abs(z); - } - wr[na - 1] = x + z; - wr[en - 1] = wr[na - 1]; - if (z != 0.0) { - wr[en - 1] = x - w / z; - } - wi[na - 1] = 0.0; - wi[en - 1] = 0.0; - x = h[en - 1][na - 1]; - s = Math.abs(x) + Math.abs(z); - p = x / s; - q = z / s; - r = Math.sqrt(p * p + q * q); - p /= r; - q /= r; - for (j = na - 1; j < n; j++) { /* row modification */ - z = h[na - 1][j]; - h[na - 1][j] = q * z + p * h[en - 1][j]; - h[en - 1][j] = q * h[en - 1][j] - p * z; - } - for (i = 0; i < en; i++) { /* column modification */ - z = h[i][na - 1]; - h[i][na - 1] = q * z + p * h[i][en - 1]; - h[i][en - 1] = q * h[i][en - 1] - p * z; - } - /* accumulate transformations */ - for (i = low - 1; i < hgh; i++) { - z = zz[i][na - 1]; - zz[i][na - 1] = q * z + p * zz[i][en - 1]; - zz[i][en - 1] = q * zz[i][en - 1] - p * z; - } - } else { /* complex pair */ - wr[na - 1] = x + p; - wr[en - 1] = x + p; - wi[na - 1] = z; - wi[en - 1] = -z; - } - en -= 2; - } /* while en >= low */ - /* backsubstitute to find vectors of upper triangular form */ - if (norm != 0.0) { - for (en = n; en >= 1; en--) { - p = wr[en - 1]; - q = wi[en - 1]; - na = en - 1; - if (q == 0.0) {/* real vector */ - m = en; - h[en - 1][en - 1] = 1.0; - if (na != 0) { - for (i = en - 2; i >= 0; i--) { - w = h[i][i] - p; - r = 0.0; - for (j = m - 1; j < en; j++) { - r += h[i][j] * h[j][en - 1]; - } - if (wi[i] < 0.0) { - z = w; - s = r; - } else { - m = i + 1; - if (wi[i] == 0.0) { - t = w; - if (t == 0.0) { - tst1 = norm; - t = tst1; - do { - t = 0.01 * t; - tst2 = norm + t; - } - while (tst2 > tst1); - } - h[i][en - 1] = -(r / t); - } else { /* solve real equations */ - x = h[i][i + 1]; - y = h[i + 1][i]; - q = (wr[i] - p) * (wr[i] - p) + wi[i] * wi[i]; - t = (x * s - z * r) / q; - h[i][en - 1] = t; - if (Math.abs(x) > Math.abs(z)) - h[i + 1][en - 1] = (-r - w * t) / x; - else - h[i + 1][en - 1] = (-s - y * t) / z; - } - /* overflow control */ - t = Math.abs(h[i][en - 1]); - if (t != 0.0) { - tst1 = t; - tst2 = tst1 + 1.0 / tst1; - if (tst2 <= tst1) { - for (j = i; j < en; j++) { - h[j][en - 1] /= t; - } - } - } - } - } - } - } else if (q > 0.0) { - m = na; - if (Math.abs(h[en - 1][na - 1]) > Math.abs(h[na - 1][en - 1])) { - h[na - 1][na - 1] = q / h[en - 1][na - 1]; - h[na - 1][en - 1] = (p - h[en - 1][en - 1]) / h[en - 1][na - 1]; - } else { - mcdiv(0.0, -h[na - 1][en - 1], h[na - 1][na - 1] - p, q); - h[na - 1][na - 1] = cr; - h[na - 1][en - 1] = ci; - } - h[en - 1][na - 1] = 0.0; - h[en - 1][en - 1] = 1.0; - if (en != 2) { - for (i = en - 3; i >= 0; i--) { - w = h[i][i] - p; - ra = 0.0; - sa = 0.0; - for (j = m - 1; j < en; j++) { - ra += h[i][j] * h[j][na - 1]; - sa += h[i][j] * h[j][en - 1]; - } - if (wi[i] < 0.0) { - z = w; - r = ra; - s = sa; - } else { - m = i + 1; - if (wi[i] == 0.0) { - mcdiv(-ra, -sa, w, q); - h[i][na - 1] = cr; - h[i][en - 1] = ci; - } else { /* solve complex equations */ - x = h[i][i + 1]; - y = h[i + 1][i]; - vr = (wr[i] - p) * (wr[i] - p); - vr = vr + wi[i] * wi[i] - q * q; - vi = (wr[i] - p) * 2.0 * q; - if (vr == 0.0 && vi == 0.0) { - tst1 = norm * (Math.abs(w) + Math.abs(q) + Math.abs(x) + - Math.abs(y) + Math.abs(z)); - vr = tst1; - do { - vr = 0.01 * vr; - tst2 = tst1 + vr; - } - while (tst2 > tst1); - } - mcdiv(x * r - z * ra + q * sa, x * s - z * sa - q * ra, vr, vi); - h[i][na - 1] = cr; - h[i][en - 1] = ci; - if (Math.abs(x) > Math.abs(z) + Math.abs(q)) { - h[i + 1] - [na - 1] = (q * h[i][en - 1] - - w * h[i][na - 1] - ra) / x; - h[i + 1][en - 1] = (-sa - w * h[i][en - 1] - - q * h[i][na - 1]) / x; - } else { - mcdiv(-r - y * h[i][na - 1], -s - y * h[i][en - 1], z, q); - h[i + 1][na - 1] = cr; - h[i + 1][en - 1] = ci; - } - } - /* overflow control */ - t = (Math.abs(h[i][na - 1]) > Math.abs(h[i][en - 1])) ? - Math.abs(h[i][na - 1]) : Math.abs(h[i][en - 1]); - if (t != 0.0) { - tst1 = t; - tst2 = tst1 + 1.0 / tst1; - if (tst2 <= tst1) { - for (j = i; j < en; j++) { - h[j][na - 1] /= t; - h[j][en - 1] /= t; - } - } - } - } - } - } - } - } - /* end back substitution. vectors of isolated roots */ - for (i = 0; i < n; i++) { - if (i + 1 < low || i + 1 > hgh) { - for (j = i; j < n; j++) { - zz[i][j] = h[i][j]; - } - } - } - /* multiply by transformation matrix to give vectors of - * original full matrix. */ - for (j = n - 1; j >= low - 1; j--) { - m = ((j + 1) < hgh) ? (j + 1) : hgh; /* min */ - for (i = low - 1; i < hgh; i++) { - z = 0.0; - for (k = low - 1; k < m; k++) { - z += zz[i][k] * h[k][j]; - } - zz[i][j] = z; - } - } - } - } - - private void eltran(double[][] a, double[][] zz, int[] ordr, int n) { - int i, j, m; - - for (i = 0; i < n; i++) { - for (j = i + 1; j < n; j++) { - zz[i][j] = 0.0; - zz[j][i] = 0.0; - } - zz[i][i] = 1.0; - } - if (n <= 2) { - return; - } - for (m = n - 1; m >= 2; m--) { - for (i = m; i < n; i++) { - zz[i][m - 1] = a[i][m - 2]; - } - i = ordr[m - 1]; - if (i != m) { - for (j = m - 1; j < n; j++) { - zz[m - 1][j] = zz[i - 1][j]; - zz[i - 1][j] = 0.0; - } - zz[i - 1][m - 1] = 1.0; - } - } - } - - void luinverse(double[][] inmat, double[][] imtrx, int size) throws IllegalArgumentException { - int i, j, k, l, maxi = 0, idx, ix, jx; - double sum, tmp, maxb, aw; - int[] index; - double[] wk; - double[][] omtrx; - - - index = new int[size]; - omtrx = new double[size][size]; - - /* copy inmat to omtrx */ - for (i = 0; i < size; i++) { - for (j = 0; j < size; j++) { - omtrx[i][j] = inmat[i][j]; - } - } - - wk = new double[size]; - aw = 1.0; - for (i = 0; i < size; i++) { - maxb = 0.0; - for (j = 0; j < size; j++) { - if (Math.abs(omtrx[i][j]) > maxb) { - maxb = Math.abs(omtrx[i][j]); - } - } - if (maxb == 0.0) { - /* Singular matrix */ - System.out.println("Singular matrix encountered"); - throw new IllegalArgumentException("Singular matrix"); - } - wk[i] = 1.0 / maxb; - } - for (j = 0; j < size; j++) { - for (i = 0; i < j; i++) { - sum = omtrx[i][j]; - for (k = 0; k < i; k++) { - sum -= omtrx[i][k] * omtrx[k][j]; - } - omtrx[i][j] = sum; - } - maxb = 0.0; - for (i = j; i < size; i++) { - sum = omtrx[i][j]; - for (k = 0; k < j; k++) { - sum -= omtrx[i][k] * omtrx[k][j]; - } - omtrx[i][j] = sum; - tmp = wk[i] * Math.abs(sum); - if (tmp >= maxb) { - maxb = tmp; - maxi = i; - } - } - if (j != maxi) { - for (k = 0; k < size; k++) { - tmp = omtrx[maxi][k]; - omtrx[maxi][k] = omtrx[j][k]; - omtrx[j][k] = tmp; - } - aw = -aw; - wk[maxi] = wk[j]; - } - index[j] = maxi; - if (omtrx[j][j] == 0.0) { - omtrx[j][j] = MachineAccuracy.EPSILON; - } - if (j != size - 1) { - tmp = 1.0 / omtrx[j][j]; - for (i = j + 1; i < size; i++) { - omtrx[i][j] *= tmp; - } - } - } - for (jx = 0; jx < size; jx++) { - for (ix = 0; ix < size; ix++) { - wk[ix] = 0.0; - } - wk[jx] = 1.0; - l = -1; - for (i = 0; i < size; i++) { - idx = index[i]; - sum = wk[idx]; - wk[idx] = wk[i]; - if (l != -1) { - for (j = l; j < i; j++) { - sum -= omtrx[i][j] * wk[j]; - } - } else if (sum != 0.0) { - l = i; - } - wk[i] = sum; - } - for (i = size - 1; i >= 0; i--) { - sum = wk[i]; - for (j = i + 1; j < size; j++) { - sum -= omtrx[i][j] * wk[j]; - } - wk[i] = sum / omtrx[i][i]; - } - for (ix = 0; ix < size; ix++) { - imtrx[ix][jx] = wk[ix]; - } - } - wk = null; - index = null; - omtrx = null; - } -} diff --git a/src/dr/oldevomodel/substmodel/AbstractNucleotideModel.java b/src/dr/oldevomodel/substmodel/AbstractNucleotideModel.java deleted file mode 100644 index cf4031b8d1..0000000000 --- a/src/dr/oldevomodel/substmodel/AbstractNucleotideModel.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * AbstractNucleotideModel.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.substmodel; - -import dr.evolution.datatype.Nucleotides; - -/** - * base class for nucleotide rate matrices - * - * - * @author Alexei Drummond - * @author Andrew Rambaut - * @author Korbinian Strimmer - */ -abstract public class AbstractNucleotideModel extends AbstractSubstitutionModel { - - double freqA, freqC, freqG, freqT, - // A+G - freqR, - // C+T - freqY; - - // Constructor - public AbstractNucleotideModel(String name, FrequencyModel freqModel) - { - super(name, Nucleotides.INSTANCE, freqModel); - - } - - protected void frequenciesChanged() { - // Nothing to precalculate - } - - protected void ratesChanged() { - // Nothing to precalculate - } - - protected void calculateFreqRY() { - freqA = freqModel.getFrequency(0); - freqC = freqModel.getFrequency(1); - freqG = freqModel.getFrequency(2); - freqT = freqModel.getFrequency(3); - freqR = freqA + freqG; - freqY = freqC + freqT; - } - - // ***************************************************************** - // Interface Model - // ***************************************************************** - - - protected void storeState() { } // nothing to do - - /** - * Restore the additional stored state - */ - protected void restoreState() { - updateMatrix = true; - } - - protected void acceptState() { } // nothing to do -} \ No newline at end of file diff --git a/src/dr/oldevomodel/substmodel/AbstractPCARateMatrix.java b/src/dr/oldevomodel/substmodel/AbstractPCARateMatrix.java deleted file mode 100644 index dec1bde4fc..0000000000 --- a/src/dr/oldevomodel/substmodel/AbstractPCARateMatrix.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * AbstractPCARateMatrix.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.substmodel; - -import dr.evolution.datatype.DataType; - -/** - * Abstract baseclass for PCA rate matrix - * - * @author Stefan Zoller - * - */ -public abstract class AbstractPCARateMatrix { - - /** - * constructor - * - * @param name Name of matrix - * @param dataType Data type as Codons.UNIVERSAL - * @param dir Directory which includes the rate matrix csv files - */ - public AbstractPCARateMatrix(String name, DataType dataType, String dir) { - this.name = name; - this.dataType = dataType; - this.dataDir = dir; - } - - public static final String getName() { return name; } - public final DataType getDataType() { return dataType; } - - public double[] getPCAt(int i) { return pcs[i]; } - public double[] getFrequencies() { return frequencies; } - public double[] getMeans() { return means; } - public double[] getScales() { return scales; } - public double[] getStartFacs() { return startFacs; } - - public void setFrequencies(double[] f) { - this.frequencies = f; - } - - public void setMeans(double[] m) { - this.means = m; - } - - public void setScales(double[] s) { - this.scales = s; - } - - public void setPCs(double[][] p) { - this.pcs = p; - } - - public void setStartFacs(double[] sf) { - this.startFacs = sf; - } - - protected double[][] pcs; - protected double[] means; - protected double[] frequencies; - protected double[] scales; - protected double[] startFacs; - - private static String name; - protected static String dataDir; - protected DataType dataType; -} diff --git a/src/dr/oldevomodel/substmodel/AbstractSubstitutionModel.java b/src/dr/oldevomodel/substmodel/AbstractSubstitutionModel.java deleted file mode 100644 index 1c95338cc8..0000000000 --- a/src/dr/oldevomodel/substmodel/AbstractSubstitutionModel.java +++ /dev/null @@ -1,1029 +0,0 @@ -/* - * AbstractSubstitutionModel.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.substmodel; - -import dr.evolution.datatype.DataType; -import dr.inference.model.AbstractModel; -import dr.inference.model.Model; -import dr.inference.model.Parameter; -import dr.inference.model.Variable; -import dr.math.MachineAccuracy; - -import java.util.LinkedList; -import java.util.List; - -/** - * An abstract base class for substitution models. - * - * This class needs serious documentation about the expectations from deriving classes. - * - * - * @author Andrew Rambaut - * @author Alexei Drummond - */ - -public abstract class AbstractSubstitutionModel extends AbstractModel implements SubstitutionModel { - - public static final String MODEL = "model"; - - protected DataType dataType = null; - - protected FrequencyModel freqModel; - protected double[] relativeRates; - - public double[] getRelativeRates() { - return relativeRates; - } - - protected double[] storedRelativeRates; - - protected int stateCount; - protected int rateCount; - - protected boolean eigenInitialised = false; - protected boolean updateMatrix = true; - protected boolean storedUpdateMatrix = true; - - AbstractSubstitutionModel(String name, DataType dataType, FrequencyModel freqModel) { - super(name); - - this.dataType = dataType; - - setStateCount(dataType.getStateCount()); - - if (freqModel != null) { - // freqModel can be null at this point but must be - // in place by the time setupMatrix is called. - - if (freqModel.getDataType() != dataType) { - throw new IllegalArgumentException("Datatypes do not match!"); - } - - this.freqModel = freqModel; - addModel(freqModel); - - checkFrequencies(); - } - - updateMatrix = true; - } - - public int getStateCount() { - return stateCount; - } - - private void setStateCount(int stateCount) { - eigenInitialised = false; - - this.stateCount = stateCount; - rateCount = ((stateCount - 1) * stateCount) / 2; - - relativeRates = new double[rateCount]; - storedRelativeRates = new double[rateCount]; - for (int i = 0; i < rateCount; i++) { - relativeRates[i] = 1.0; - } - } - - // ***************************************************************** - // Interface Model - // ***************************************************************** - - protected void handleModelChangedEvent(Model model, Object object, int index) { - // frequencyModel changed! - updateMatrix = true; - // if below is not true then the derived model registered more models - then it needs to override - // this method - assert( model == freqModel ) ; - frequenciesChanged(); - } - - protected void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) { - // relativeRates changed - updateMatrix = true; - ratesChanged(); - } - - protected void storeState() { - - storedUpdateMatrix = updateMatrix; - - System.arraycopy(relativeRates, 0, storedRelativeRates, 0, rateCount); - - System.arraycopy(Eval, 0, storedEval, 0, stateCount); - for (int i = 0; i < stateCount; i++) { - System.arraycopy(Ievc[i], 0, storedIevc[i], 0, stateCount); - System.arraycopy(Evec[i], 0, storedEvec[i], 0, stateCount); - } - - } - - /** - * Restore the additional stored state - */ - protected void restoreState() { - - updateMatrix = storedUpdateMatrix; - - // To restore all this stuff just swap the pointers... - double[] tmp1 = storedRelativeRates; - storedRelativeRates = relativeRates; - relativeRates = tmp1; - - tmp1 = storedEval; - storedEval = Eval; - Eval = tmp1; - - double[][] tmp2 = storedIevc; - storedIevc = Ievc; - Ievc = tmp2; - - tmp2 = storedEvec; - storedEvec = Evec; - Evec = tmp2; - - } - - protected void acceptState() { - } // nothing to do - - // called when any registered model changes - abstract protected void frequenciesChanged(); - - // called when any registered variable changes - abstract protected void ratesChanged(); - - abstract protected void setupRelativeRates(); - - public FrequencyModel getFrequencyModel() { - return freqModel; - } - - /** - * @return the data type - */ - public DataType getDataType() { - return dataType; - } - - /** - * get the complete transition probability matrix for the given distance - * - * @param distance the expected number of substitutions - * @param matrix an array to store the matrix - */ - public void getTransitionProbabilities(double distance, double[] matrix) { - int i, j, k; - double temp; - - // this must be synchronized to avoid being called simultaneously by - // two different likelihood threads - AJD - synchronized (this) { - if (updateMatrix) { - setupMatrix(); - } - } - - // implemented a pool of iexp matrices to support multiple threads - // without creating a new matrix each call. - AJD - double[][] iexp = popiexp(); - for (i = 0; i < stateCount; i++) { - temp = Math.exp(distance * Eval[i]); - for (j = 0; j < stateCount; j++) { - iexp[i][j] = Ievc[i][j] * temp; - } - } - - int u = 0; - for (i = 0; i < stateCount; i++) { - for (j = 0; j < stateCount; j++) { - temp = 0.0; - for (k = 0; k < stateCount; k++) { - temp += Evec[i][k] * iexp[k][j]; - } - - matrix[u] = Math.abs(temp); - u++; - } - } - pushiexp(iexp); - } - - /** - * This function returns the Eigen vectors. - * - * @return the array - */ - public double[][] getEigenVectors() { - synchronized (this) { - if (updateMatrix) { - setupMatrix(); - } - } - return Evec; - } - - /** - * This function returns the inverse Eigen vectors. - * - * @return the array - */ - public double[][] getInverseEigenVectors() { - synchronized (this) { - if (updateMatrix) { - setupMatrix(); - } - } - return Ievc; - } - - /** - * This function returns the Eigen values. - */ - public double[] getEigenValues() { - synchronized (this) { - if (updateMatrix) { - setupMatrix(); - } - } - return Eval; - } - - /** - * setup substitution matrix - */ - public void setupMatrix() { - setupRelativeRates(); - - if (!eigenInitialised) - initialiseEigen(); - - int i, j, k = 0; - - // Set the instantaneous rate matrix - for (i = 0; i < stateCount; i++) { - for (j = i + 1; j < stateCount; j++) { - amat[i][j] = relativeRates[k] * freqModel.getFrequency(j); - amat[j][i] = relativeRates[k] * freqModel.getFrequency(i); - k += 1; - } - } - makeValid(amat, stateCount); - normalize(amat, freqModel.getFrequencies()); - - // copy q matrix for unit testing - for (i = 0; i < amat.length; i++) { - System.arraycopy(amat[i], 0, q[i], 0, amat[i].length); - } - - // compute eigenvalues and eigenvectors - elmhes(amat, ordr, stateCount); - eltran(amat, Evec, ordr, stateCount); - hqr2(stateCount, 1, stateCount, amat, Evec, Eval, evali); - luinverse(Evec, Ievc, stateCount); - - updateMatrix = false; - } - - // Make it a valid rate matrix (make sum of rows = 0) - void makeValid(double[][] matrix, int dimension) { - for (int i = 0; i < dimension; i++) { - double sum = 0.0; - for (int j = 0; j < dimension; j++) { - if (i != j) - sum += matrix[i][j]; - } - matrix[i][i] = -sum; - } - } - - /** - * Normalize rate matrix to one expected substitution per unit time - * - * @param matrix the matrix to normalize to one expected substitution - * @param pi the equilibrium distribution of states - */ - void normalize(double[][] matrix, double[] pi) { - double subst = 0.0; - int dimension = pi.length; - - for (int i = 0; i < dimension; i++) - subst += -matrix[i][i] * pi[i]; - - for (int i = 0; i < dimension; i++) { - for (int j = 0; j < dimension; j++) { - matrix[i][j] = matrix[i][j] / subst; - } - } - } - - /** - * Ensures that frequencies are not smaller than MINFREQ and - * that two frequencies differ by at least 2*MINFDIFF. - * This avoids potential problems later when eigenvalues - * are computed. - */ - private void checkFrequencies() { - // required frequency difference - double MINFDIFF = 1.0E-10; - - // lower limit on frequency - double MINFREQ = 1.0E-10; - - int maxi = 0; - double sum = 0.0; - double maxfreq = 0.0; - for (int i = 0; i < stateCount; i++) { - double freq = freqModel.getFrequency(i); - if (freq < MINFREQ) freqModel.setFrequency(i, MINFREQ); - if (freq > maxfreq) { - maxfreq = freq; - maxi = i; - } - sum += freqModel.getFrequency(i); - } - double diff = 1.0 - sum; - freqModel.setFrequency(maxi, freqModel.getFrequency(maxi) + diff); - - for (int i = 0; i < stateCount - 1; i++) { - for (int j = i + 1; j < stateCount; j++) { - if (freqModel.getFrequency(i) == freqModel.getFrequency(j)) { - freqModel.setFrequency(i, freqModel.getFrequency(i) + MINFDIFF); - freqModel.setFrequency(j, freqModel.getFrequency(j) - MINFDIFF); - } - } - } - } - - /** - * allocate memory for the Eigen routines - */ - protected void initialiseEigen() { - - Eval = new double[stateCount]; - Evec = new double[stateCount][stateCount]; - Ievc = new double[stateCount][stateCount]; - - storedEval = new double[stateCount]; - storedEvec = new double[stateCount][stateCount]; - storedIevc = new double[stateCount][stateCount]; - - amat = new double[stateCount][stateCount]; - q = new double[stateCount][stateCount]; - - ordr = new int[stateCount]; - evali = new double[stateCount]; - - eigenInitialised = true; - updateMatrix = true; - } - - // Eigenvalues, eigenvectors, and inverse eigenvectors - protected double[] Eval; - protected double[] storedEval; - protected double[][] Evec; - protected double[][] storedEvec; - protected double[][] Ievc; - protected double[][] storedIevc; - - List iexpPool = new LinkedList(); - - private int[] ordr; - private double[] evali; - double amat[][]; - private double q[][]; - - public double[][] getQ() { - return q; - } - - protected synchronized double[][] popiexp() { - - if (iexpPool.size() == 0) { - iexpPool.add(new double[stateCount][stateCount]); - } - return iexpPool.remove(0); - } - - protected synchronized void pushiexp(double[][] iexp) { - iexpPool.add(0, iexp); - } - - private void elmhes(double[][] a, int[] ordr, int n) { - int m, j, i; - double y, x; - - for (i = 0; i < n; i++) { - ordr[i] = 0; - } - for (m = 2; m < n; m++) { - x = 0.0; - i = m; - for (j = m; j <= n; j++) { - if (Math.abs(a[j - 1][m - 2]) > Math.abs(x)) { - x = a[j - 1][m - 2]; - i = j; - } - } - ordr[m - 1] = i; - if (i != m) { - for (j = m - 2; j < n; j++) { - y = a[i - 1][j]; - a[i - 1][j] = a[m - 1][j]; - a[m - 1][j] = y; - } - for (j = 0; j < n; j++) { - y = a[j][i - 1]; - a[j][i - 1] = a[j][m - 1]; - a[j][m - 1] = y; - } - } - if (x != 0.0) { - for (i = m; i < n; i++) { - y = a[i][m - 2]; - if (y != 0.0) { - y /= x; - a[i][m - 2] = y; - for (j = m - 1; j < n; j++) { - a[i][j] -= y * a[m - 1][j]; - } - for (j = 0; j < n; j++) { - a[j][m - 1] += y * a[j][i]; - } - } - } - } - } - } - - // Helper variables for mcdiv - private double cr, ci; - - private void mcdiv(double ar, double ai, double br, double bi) { - double s, ars, ais, brs, bis; - - s = Math.abs(br) + Math.abs(bi); - ars = ar / s; - ais = ai / s; - brs = br / s; - bis = bi / s; - s = brs * brs + bis * bis; - cr = (ars * brs + ais * bis) / s; - ci = (ais * brs - ars * bis) / s; - } - - void hqr2(int n, int low, int hgh, double[][] h, double[][] zz, - double[] wr, double[] wi) throws ArithmeticException { - int i, j, k, l = 0, m, en, na, itn, its; - double p = 0, q = 0, r = 0, s = 0, t, w, x = 0, y, ra, sa, vi, vr, z = 0, norm, tst1, tst2; - boolean notLast; - - - norm = 0.0; - k = 1; - /* store isolated roots and compute matrix norm */ - for (i = 0; i < n; i++) { - for (j = k - 1; j < n; j++) { - norm += Math.abs(h[i][j]); - } - k = i + 1; - if (i + 1 < low || i + 1 > hgh) { - wr[i] = h[i][i]; - wi[i] = 0.0; - } - } - en = hgh; - t = 0.0; - itn = n * 30; - while (en >= low) { /* search for next eigenvalues */ - its = 0; - na = en - 1; - while (en >= 1) { - /* look for single small sub-diagonal element */ - boolean fullLoop = true; - for (l = en; l > low; l--) { - s = Math.abs(h[l - 2][l - 2]) + Math.abs(h[l - 1][l - 1]); - if (s == 0.0) { - s = norm; - } - tst1 = s; - tst2 = tst1 + Math.abs(h[l - 1][l - 2]); - if (tst2 == tst1) { - fullLoop = false; - break; - } - } - if (fullLoop) { - l = low; - } - - x = h[en - 1][en - 1]; /* form shift */ - if (l == en || l == na) { - break; - } - if (itn == 0) { - /* eigenvalues have not converged */ - throw new ArithmeticException(); - } - y = h[na - 1][na - 1]; - w = h[en - 1][na - 1] * h[na - 1][en - 1]; - /* form exceptional shift */ - if (its == 10 || its == 20) { - t += x; - for (i = low - 1; i < en; i++) { - h[i][i] -= x; - } - s = Math.abs(h[en - 1][na - 1]) + Math.abs(h[na - 1][en - 3]); - x = 0.75 * s; - y = x; - w = -0.4375 * s * s; - } - its++; - itn--; - /* look for two consecutive small sub-diagonal elements */ - for (m = en - 2; m >= l; m--) { - z = h[m - 1][m - 1]; - r = x - z; - s = y - z; - p = (r * s - w) / h[m][m - 1] + h[m - 1][m]; - q = h[m][m] - z - r - s; - r = h[m + 1][m]; - s = Math.abs(p) + Math.abs(q) + Math.abs(r); - p /= s; - q /= s; - r /= s; - if (m == l) { - break; - } - tst1 = Math.abs(p) * (Math.abs(h[m - 2][m - 2]) + Math.abs(z) + Math.abs(h[m][m])); - tst2 = tst1 + Math.abs(h[m - 1][m - 2]) * (Math.abs(q) + Math.abs(r)); - if (tst2 == tst1) { - break; - } - } - for (i = m + 2; i <= en; i++) { - h[i - 1][i - 3] = 0.0; - if (i != m + 2) { - h[i - 1][i - 4] = 0.0; - } - } - for (k = m; k <= na; k++) { - notLast = k != na; - if (k != m) { - p = h[k - 1][k - 2]; - q = h[k][k - 2]; - r = 0.0; - if (notLast) { - r = h[k + 1][k - 2]; - } - x = Math.abs(p) + Math.abs(q) + Math.abs(r); - if (x != 0.0) { - p /= x; - q /= x; - r /= x; - } - } - if (x != 0.0) { - if (p < 0.0) { /* sign */ - s = -Math.sqrt(p * p + q * q + r * r); - } else { - s = Math.sqrt(p * p + q * q + r * r); - } - if (k != m) { - h[k - 1][k - 2] = -s * x; - } else if (l != m) { - h[k - 1][k - 2] = -h[k - 1][k - 2]; - } - p += s; - x = p / s; - y = q / s; - z = r / s; - q /= p; - r /= p; - if (!notLast) { - for (j = k - 1; j < n; j++) { /* row modification */ - p = h[k - 1][j] + q * h[k][j]; - h[k - 1][j] -= p * x; - h[k][j] -= p * y; - } - j = (en < (k + 3)) ? en : (k + 3); /* min */ - for (i = 0; i < j; i++) { /* column modification */ - p = x * h[i][k - 1] + y * h[i][k]; - h[i][k - 1] -= p; - h[i][k] -= p * q; - } - /* accumulate transformations */ - for (i = low - 1; i < hgh; i++) { - p = x * zz[i][k - 1] + y * zz[i][k]; - zz[i][k - 1] -= p; - zz[i][k] -= p * q; - } - } else { - for (j = k - 1; j < n; j++) { /* row modification */ - p = h[k - 1][j] + q * h[k][j] + r * h[k + 1][j]; - h[k - 1][j] -= p * x; - h[k][j] -= p * y; - h[k + 1][j] -= p * z; - } - j = (en < (k + 3)) ? en : (k + 3); /* min */ - for (i = 0; i < j; i++) { /* column modification */ - p = x * h[i][k - 1] + y * h[i][k] + z * h[i][k + 1]; - h[i][k - 1] -= p; - h[i][k] -= p * q; - h[i][k + 1] -= p * r; - } - /* accumulate transformations */ - for (i = low - 1; i < hgh; i++) { - p = x * zz[i][k - 1] + y * zz[i][k] + - z * zz[i][k + 1]; - zz[i][k - 1] -= p; - zz[i][k] -= p * q; - zz[i][k + 1] -= p * r; - } - } - } - } /* for k */ - } /* while infinite loop */ - if (l == en) { /* one root found */ - h[en - 1][en - 1] = x + t; - wr[en - 1] = h[en - 1][en - 1]; - wi[en - 1] = 0.0; - en = na; - continue; - } - y = h[na - 1][na - 1]; - w = h[en - 1][na - 1] * h[na - 1][en - 1]; - p = (y - x) / 2.0; - q = p * p + w; - z = Math.sqrt(Math.abs(q)); - h[en - 1][en - 1] = x + t; - x = h[en - 1][en - 1]; - h[na - 1][na - 1] = y + t; - if (q >= 0.0) { /* real pair */ - if (p < 0.0) { /* sign */ - z = p - Math.abs(z); - } else { - z = p + Math.abs(z); - } - wr[na - 1] = x + z; - wr[en - 1] = wr[na - 1]; - if (z != 0.0) { - wr[en - 1] = x - w / z; - } - wi[na - 1] = 0.0; - wi[en - 1] = 0.0; - x = h[en - 1][na - 1]; - s = Math.abs(x) + Math.abs(z); - p = x / s; - q = z / s; - r = Math.sqrt(p * p + q * q); - p /= r; - q /= r; - for (j = na - 1; j < n; j++) { /* row modification */ - z = h[na - 1][j]; - h[na - 1][j] = q * z + p * h[en - 1][j]; - h[en - 1][j] = q * h[en - 1][j] - p * z; - } - for (i = 0; i < en; i++) { /* column modification */ - z = h[i][na - 1]; - h[i][na - 1] = q * z + p * h[i][en - 1]; - h[i][en - 1] = q * h[i][en - 1] - p * z; - } - /* accumulate transformations */ - for (i = low - 1; i < hgh; i++) { - z = zz[i][na - 1]; - zz[i][na - 1] = q * z + p * zz[i][en - 1]; - zz[i][en - 1] = q * zz[i][en - 1] - p * z; - } - } else { /* complex pair */ - wr[na - 1] = x + p; - wr[en - 1] = x + p; - wi[na - 1] = z; - wi[en - 1] = -z; - } - en -= 2; - } /* while en >= low */ - /* backsubstitute to find vectors of upper triangular form */ - if (norm != 0.0) { - for (en = n; en >= 1; en--) { - p = wr[en - 1]; - q = wi[en - 1]; - na = en - 1; - if (q == 0.0) {/* real vector */ - m = en; - h[en - 1][en - 1] = 1.0; - if (na != 0) { - for (i = en - 2; i >= 0; i--) { - w = h[i][i] - p; - r = 0.0; - for (j = m - 1; j < en; j++) { - r += h[i][j] * h[j][en - 1]; - } - if (wi[i] < 0.0) { - z = w; - s = r; - } else { - m = i + 1; - if (wi[i] == 0.0) { - t = w; - if (t == 0.0) { - tst1 = norm; - t = tst1; - do { - t = 0.01 * t; - tst2 = norm + t; - } - while (tst2 > tst1); - } - h[i][en - 1] = -(r / t); - } else { /* solve real equations */ - x = h[i][i + 1]; - y = h[i + 1][i]; - q = (wr[i] - p) * (wr[i] - p) + wi[i] * wi[i]; - t = (x * s - z * r) / q; - h[i][en - 1] = t; - if (Math.abs(x) > Math.abs(z)) - h[i + 1][en - 1] = (-r - w * t) / x; - else - h[i + 1][en - 1] = (-s - y * t) / z; - } - /* overflow control */ - t = Math.abs(h[i][en - 1]); - if (t != 0.0) { - tst1 = t; - tst2 = tst1 + 1.0 / tst1; - if (tst2 <= tst1) { - for (j = i; j < en; j++) { - h[j][en - 1] /= t; - } - } - } - } - } - } - } else if (q > 0.0) { - m = na; - if (Math.abs(h[en - 1][na - 1]) > Math.abs(h[na - 1][en - 1])) { - h[na - 1][na - 1] = q / h[en - 1][na - 1]; - h[na - 1][en - 1] = (p - h[en - 1][en - 1]) / h[en - 1][na - 1]; - } else { - mcdiv(0.0, -h[na - 1][en - 1], h[na - 1][na - 1] - p, q); - h[na - 1][na - 1] = cr; - h[na - 1][en - 1] = ci; - } - h[en - 1][na - 1] = 0.0; - h[en - 1][en - 1] = 1.0; - if (en != 2) { - for (i = en - 3; i >= 0; i--) { - w = h[i][i] - p; - ra = 0.0; - sa = 0.0; - for (j = m - 1; j < en; j++) { - ra += h[i][j] * h[j][na - 1]; - sa += h[i][j] * h[j][en - 1]; - } - if (wi[i] < 0.0) { - z = w; - r = ra; - s = sa; - } else { - m = i + 1; - if (wi[i] == 0.0) { - mcdiv(-ra, -sa, w, q); - h[i][na - 1] = cr; - h[i][en - 1] = ci; - } else { /* solve complex equations */ - x = h[i][i + 1]; - y = h[i + 1][i]; - vr = (wr[i] - p) * (wr[i] - p); - vr = vr + wi[i] * wi[i] - q * q; - vi = (wr[i] - p) * 2.0 * q; - if (vr == 0.0 && vi == 0.0) { - tst1 = norm * (Math.abs(w) + Math.abs(q) + Math.abs(x) + - Math.abs(y) + Math.abs(z)); - vr = tst1; - do { - vr = 0.01 * vr; - tst2 = tst1 + vr; - } - while (tst2 > tst1); - } - mcdiv(x * r - z * ra + q * sa, x * s - z * sa - q * ra, vr, vi); - h[i][na - 1] = cr; - h[i][en - 1] = ci; - if (Math.abs(x) > Math.abs(z) + Math.abs(q)) { - h[i + 1] - [na - 1] = (q * h[i][en - 1] - - w * h[i][na - 1] - ra) / x; - h[i + 1][en - 1] = (-sa - w * h[i][en - 1] - - q * h[i][na - 1]) / x; - } else { - mcdiv(-r - y * h[i][na - 1], -s - y * h[i][en - 1], z, q); - h[i + 1][na - 1] = cr; - h[i + 1][en - 1] = ci; - } - } - /* overflow control */ - t = (Math.abs(h[i][na - 1]) > Math.abs(h[i][en - 1])) ? - Math.abs(h[i][na - 1]) : Math.abs(h[i][en - 1]); - if (t != 0.0) { - tst1 = t; - tst2 = tst1 + 1.0 / tst1; - if (tst2 <= tst1) { - for (j = i; j < en; j++) { - h[j][na - 1] /= t; - h[j][en - 1] /= t; - } - } - } - } - } - } - } - } - /* end back substitution. vectors of isolated roots */ - for (i = 0; i < n; i++) { - if (i + 1 < low || i + 1 > hgh) { - for (j = i; j < n; j++) { - zz[i][j] = h[i][j]; - } - } - } - /* multiply by transformation matrix to give vectors of - * original full matrix. */ - for (j = n - 1; j >= low - 1; j--) { - m = ((j + 1) < hgh) ? (j + 1) : hgh; /* min */ - for (i = low - 1; i < hgh; i++) { - z = 0.0; - for (k = low - 1; k < m; k++) { - z += zz[i][k] * h[k][j]; - } - zz[i][j] = z; - } - } - } - } - - private void eltran(double[][] a, double[][] zz, int[] ordr, int n) { - int i, j, m; - - for (i = 0; i < n; i++) { - for (j = i + 1; j < n; j++) { - zz[i][j] = 0.0; - zz[j][i] = 0.0; - } - zz[i][i] = 1.0; - } - if (n <= 2) { - return; - } - for (m = n - 1; m >= 2; m--) { - for (i = m; i < n; i++) { - zz[i][m - 1] = a[i][m - 2]; - } - i = ordr[m - 1]; - if (i != m) { - for (j = m - 1; j < n; j++) { - zz[m - 1][j] = zz[i - 1][j]; - zz[i - 1][j] = 0.0; - } - zz[i - 1][m - 1] = 1.0; - } - } - } - - void luinverse(double[][] inmat, double[][] imtrx, int size) throws IllegalArgumentException { - int i, j, k, l, maxi = 0, idx, ix, jx; - double sum, tmp, maxb, aw; - int[] index; - double[] wk; - double[][] omtrx; - - - index = new int[size]; - omtrx = new double[size][size]; - - /* copy inmat to omtrx */ - for (i = 0; i < size; i++) { - for (j = 0; j < size; j++) { - omtrx[i][j] = inmat[i][j]; - } - } - - wk = new double[size]; - aw = 1.0; - for (i = 0; i < size; i++) { - maxb = 0.0; - for (j = 0; j < size; j++) { - if (Math.abs(omtrx[i][j]) > maxb) { - maxb = Math.abs(omtrx[i][j]); - } - } - if (maxb == 0.0) { - /* Singular matrix */ - System.out.println("Singular matrix encountered"); - throw new IllegalArgumentException("Singular matrix"); - } - wk[i] = 1.0 / maxb; - } - for (j = 0; j < size; j++) { - for (i = 0; i < j; i++) { - sum = omtrx[i][j]; - for (k = 0; k < i; k++) { - sum -= omtrx[i][k] * omtrx[k][j]; - } - omtrx[i][j] = sum; - } - maxb = 0.0; - for (i = j; i < size; i++) { - sum = omtrx[i][j]; - for (k = 0; k < j; k++) { - sum -= omtrx[i][k] * omtrx[k][j]; - } - omtrx[i][j] = sum; - tmp = wk[i] * Math.abs(sum); - if (tmp >= maxb) { - maxb = tmp; - maxi = i; - } - } - if (j != maxi) { - for (k = 0; k < size; k++) { - tmp = omtrx[maxi][k]; - omtrx[maxi][k] = omtrx[j][k]; - omtrx[j][k] = tmp; - } - aw = -aw; - wk[maxi] = wk[j]; - } - index[j] = maxi; - if (omtrx[j][j] == 0.0) { - omtrx[j][j] = MachineAccuracy.EPSILON; - } - if (j != size - 1) { - tmp = 1.0 / omtrx[j][j]; - for (i = j + 1; i < size; i++) { - omtrx[i][j] *= tmp; - } - } - } - for (jx = 0; jx < size; jx++) { - for (ix = 0; ix < size; ix++) { - wk[ix] = 0.0; - } - wk[jx] = 1.0; - l = -1; - for (i = 0; i < size; i++) { - idx = index[i]; - sum = wk[idx]; - wk[idx] = wk[i]; - if (l != -1) { - for (j = l; j < i; j++) { - sum -= omtrx[i][j] * wk[j]; - } - } else if (sum != 0.0) { - l = i; - } - wk[i] = sum; - } - for (i = size - 1; i >= 0; i--) { - sum = wk[i]; - for (j = i + 1; j < size; j++) { - sum -= omtrx[i][j] * wk[j]; - } - wk[i] = sum / omtrx[i][i]; - } - for (ix = 0; ix < size; ix++) { - imtrx[ix][jx] = wk[ix]; - } - } - wk = null; - index = null; - omtrx = null; - } -} diff --git a/src/dr/oldevomodel/substmodel/AminoAcidModelType.java b/src/dr/oldevomodel/substmodel/AminoAcidModelType.java deleted file mode 100644 index 32a90feb4e..0000000000 --- a/src/dr/oldevomodel/substmodel/AminoAcidModelType.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * AminoAcidModelType.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.substmodel; - -import dr.util.Citation; - -/** - * @author Alexei Drummond - */ -public enum AminoAcidModelType { - - BLOSUM_62("Blosum62", "blosum62", Blosum62.INSTANCE), - DAYHOFF("Dayhoff", "dayhoff", Dayhoff.INSTANCE), - JTT("JTT", dr.oldevomodel.substmodel.JTT.INSTANCE), - MT_REV_24("mtREV", MTREV.INSTANCE), - CP_REV_45("cpREV", CPREV.INSTANCE), - WAG("WAG", dr.oldevomodel.substmodel.WAG.INSTANCE), - LG("LG", dr.oldevomodel.substmodel.LG.INSTANCE), - FLU("FLU", dr.oldevomodel.substmodel.FLU.INSTANCE); - - AminoAcidModelType(String displayName, EmpiricalRateMatrix matrix) { - this(displayName, displayName, matrix); - } - - AminoAcidModelType(String displayName, String xmlName, EmpiricalRateMatrix matrix) { - this.displayName = displayName; - this.xmlName = xmlName; - this.matrix = matrix; - } - - public String toString() { - return displayName; - } - - - public String getXMLName() { - return xmlName; - } - - public EmpiricalRateMatrix getRateMatrixInstance() { - return matrix; - } - - public Citation getCitation() { - return matrix.getCitations().get(0); - } - - public static String[] xmlNames() { - - AminoAcidModelType[] values = values(); - - String[] xmlNames = new String[values.length]; - for (int i = 0; i < values.length; i++) { - xmlNames[i] = values[i].getXMLName(); - } - return xmlNames; - } - - private final String displayName, xmlName; - private final EmpiricalRateMatrix matrix; -} diff --git a/src/dr/oldevomodel/substmodel/AsymmetricQuadraticModel.java b/src/dr/oldevomodel/substmodel/AsymmetricQuadraticModel.java deleted file mode 100644 index bdcaeb8c98..0000000000 --- a/src/dr/oldevomodel/substmodel/AsymmetricQuadraticModel.java +++ /dev/null @@ -1,240 +0,0 @@ -/* - * AsymmetricQuadraticModel.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.substmodel; - - -import dr.evolution.datatype.Microsatellite; -import dr.inference.model.Parameter; -import dr.inference.model.Variable; - -/** - * @author Chieh-Hsi Wu - * - * Implements the Asymmetric Quadratic Model - */ -public class AsymmetricQuadraticModel extends OnePhaseModel{ - - public static final String ASYMQUAD_MODEL = "ASYMQUADModel"; - - /* - *Parameters for setting up the infinitesimal rate matrix. - */ - private Variable expanConst; - private Variable expanLin; - private Variable expanQuad; - private Variable contractConst; - private Variable contractLin; - private Variable contractQuad; - - - /** - * Constructor - * - * @param microsatellite Mirosatellite data type - * @param freqModel Frequency model - */ - public AsymmetricQuadraticModel(Microsatellite microsatellite, FrequencyModel freqModel){ - this( - microsatellite, - freqModel, - null, null, null, null, null, null, - false); - - } - - - public AsymmetricQuadraticModel(Microsatellite microsatellite, FrequencyModel freqModel, boolean isNested){ - this( - microsatellite, - freqModel, - null, null, null, null, null, null, - isNested - ); - - } - - - /** - * Constructor - * - * @param microsatellite Mirosatellite data type - * @param freqModel Frequency model - * @param expanConst Expansion constant - * @param expanLin Expansion linear coefficient - * @param expanQuad Expansion quadratic coefficient - * @param contractConst Contraction constant - * @param contractLin Contraction linear coefficient - * @param contractQuad Contraction quadratic coefficient - * @param isNested boolean indicating whether this object is a submodel of another microsatellite model - */ - public AsymmetricQuadraticModel( - Microsatellite microsatellite, - FrequencyModel freqModel, - Variable expanConst, - Variable expanLin, - Variable expanQuad, - Variable contractConst, - Variable contractLin, - Variable contractQuad, - boolean isNested){ - - super(ASYMQUAD_MODEL, microsatellite, freqModel,null); - - - //The default setting of the parameters gives the same infinitesimal rates - // as the StepwiseMutaionalModel class. - this.expanConst = overrideDefault(new Parameter.Default(1.0), expanConst); - this.expanLin = overrideDefault(new Parameter.Default(0.0), expanLin); - this.expanQuad = overrideDefault(new Parameter.Default(0.0), expanQuad); - this.contractConst = overrideDefault(this.expanConst, contractConst); - this.contractLin = overrideDefault(this.expanLin, contractLin); - this.contractQuad = overrideDefault(this.expanQuad, contractQuad); - this.isNested = isNested; - addParameters(); - - //printDetails(); - - setupInfinitesimalRates(); - - //calculate the default frequencies when not provieded by the user. - if(freqModel == null){ - useStationaryFreqs = true; - computeStationaryDistribution(); - }else{ - this.freqModel = freqModel; - } - - addModel(this.freqModel); - - } - - private void addParameters(){ - addParam(this.expanConst); - addParam(this.expanLin); - addParam(this.expanQuad); - if(this.contractConst != this.expanConst) - addParam(this.contractConst); - if(this.contractLin != this.expanLin) - addParam(this.contractLin); - if(this.contractQuad != this.expanQuad) - addParam(this.contractQuad); - } - - - - - /* - * This method will override the default value of the parameter using the value specified by the user. - */ - private Variable overrideDefault(Variable defaultParam, Variable providedParam){ - if(providedParam != null && providedParam != defaultParam) - return providedParam; - return defaultParam; - } - - - /* - * Setting up the infinitesimal Rates - * The rates are defined by the following equations: - * X -> X + 1 at rate u0 + u1(X - k) + u2(X - k)^2 - * X -> X - 1 at rate d0 + d1(X - k) + d2(X - k)^2 - */ - public void setupInfinitesimalRates(){ - - - double u0 = expanConst.getValue(0); - double u1 = expanLin.getValue(0); - double u2 = expanQuad.getValue(0); - - double d0 = contractConst.getValue(0); - double d1 = contractLin.getValue(0); - double d2 = contractQuad.getValue(0); - - double rowSum; - for(int i = 0; i < stateCount;i++){ - rowSum = 0.0; - if(i - 1 > -1){ - infinitesimalRateMatrix[i][i - 1] =d0+d1*i+d2*i*i; - rowSum = rowSum + infinitesimalRateMatrix[i][i - 1]; - - } - - if(i + 1 < stateCount){ - infinitesimalRateMatrix[i][i + 1] = u0+u1*i+u2*i*i; - rowSum = rowSum + infinitesimalRateMatrix[i][i + 1]; - - } - - infinitesimalRateMatrix[i][i] = rowSum*-1; - - } - - - } - - - public Variable getExpansionConstant(){ - return expanConst; - } - - public Variable getExpansionLinear(){ - return expanLin; - } - - public Variable getExpansionQuad(){ - return expanQuad; - } - - public Variable getContractionConstant(){ - return contractConst; - } - - public Variable getContractionLinear(){ - return contractLin; - } - - public Variable getContractionQuad(){ - return contractQuad; - } - - - - public void printDetails(){ - System.out.println("\n"); - System.out.println("Details of the asymmetric quadratic model and its parameters:"); - System.out.println("expansion constant: "+expanConst.getValue(0)); - System.out.println("expansion linear: "+ expanLin.getValue(0)); - System.out.println("expansion quadratic: "+expanQuad.getValue(0)); - System.out.println("contraction constant: "+contractConst.getValue(0)); - System.out.println("contraction linear: "+contractLin.getValue(0)); - System.out.println("contraction quadratc: "+contractQuad.getValue(0)); - System.out.println("a submodel: "+isNested); - System.out.println("\n"); - } - -} diff --git a/src/dr/oldevomodel/substmodel/BinaryCovarionModel.java b/src/dr/oldevomodel/substmodel/BinaryCovarionModel.java deleted file mode 100644 index b8a7459ee2..0000000000 --- a/src/dr/oldevomodel/substmodel/BinaryCovarionModel.java +++ /dev/null @@ -1,217 +0,0 @@ -/* - * BinaryCovarionModel.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.substmodel; - -import dr.evolution.datatype.TwoStateCovarion; -import dr.oldevomodelxml.substmodel.BinaryCovarionModelParser; -import dr.inference.model.Parameter; - -/** - * @author Alexei Drummond - *

- * a the rate of the slow rate class - * 1 the rate of the fast rate class - * p0 the equilibrium frequency of zero states - * p1 1 - p0, the equilibrium frequency of one states - * f0 the equilibrium frequency of slow rate class - * f1 1 - f0, the equilibrium frequency of fast rate class - * s the rate of switching - *

- * then the (unnormalized) instantaneous rate matrix (unnormalized Q) should be - *

- * [ -(a*p1)-s , a*p1 , s , 0 ] - * [ a*p0 , -(a*p0)-s , 0 , s ] - * [ s , 0 , -p1-s , p1 ] - * [ 0 , s , p0 , -p0-s ] - */ -public class BinaryCovarionModel extends AbstractCovarionModel { - - /** - * @param dataType the data type - * @param frequencies the frequencies of the visible states - * @param hiddenFrequencies the frequencies of the hidden rates - * @param alphaParameter the rate of evolution in slow mode - * @param switchingParameter the rate of flipping between slow and fast modes - */ - public BinaryCovarionModel(TwoStateCovarion dataType, - Parameter frequencies, - Parameter hiddenFrequencies, - Parameter alphaParameter, - Parameter switchingParameter, - Version version) { - - super(BinaryCovarionModelParser.COVARION_MODEL, dataType, frequencies, hiddenFrequencies); - - alpha = alphaParameter; - this.switchRate = switchingParameter; - this.frequencies = frequencies; - this.hiddenFrequencies = hiddenFrequencies; - this.version = version; - - addVariable(alpha); - addVariable(switchRate); - addVariable(frequencies); - addVariable(hiddenFrequencies); - setupUnnormalizedQMatrix(); - } - - public enum Version { - VERSION1("1") { - public double getF0(double iF0) { - return 1.0; - } - - public double getF1(double iF1) { - return 1.0; - } - }, - VERSION2("2") { - public double getF0(double iF0) { - return iF0; - } - - public double getF1(double iF1) { - return iF1; - } - }; - - Version(String text) { - this.text = text; - } - - public String getText() { - return text; - } - - private final String text; - - public static Version parseFromString(String text) { - for (Version version : Version.values()) { - if (version.getText().compareToIgnoreCase(text) == 0) - return version; - } - throw new IllegalArgumentException("Unknown version type: " + text); - } - - public String toString() { - return getText(); - } - - abstract public double getF0(double iF0); - - abstract public double getF1(double iF1); - } - - protected void setupUnnormalizedQMatrix() { - - double a = alpha.getParameterValue(0); - double s = switchRate.getParameterValue(0); - double f0 = hiddenFrequencies.getParameterValue(0); - double f1 = hiddenFrequencies.getParameterValue(1); - double p0 = frequencies.getParameterValue(0); - double p1 = frequencies.getParameterValue(1); - - assert Math.abs(1.0 - f0 - f1) < 1e-8; - assert Math.abs(1.0 - p0 - p1) < 1e-8; - - f0 = version.getF0(f0); - f1 = version.getF1(f1); - - unnormalizedQ[0][1] = a * p1; - unnormalizedQ[0][2] = s * f0; - unnormalizedQ[0][3] = 0.0; - - unnormalizedQ[1][0] = a * p0; - unnormalizedQ[1][2] = 0.0; - unnormalizedQ[1][3] = s * f0; - - unnormalizedQ[2][0] = s * f1; - unnormalizedQ[2][1] = 0.0; - unnormalizedQ[2][3] = p1; - - unnormalizedQ[3][0] = 0.0; - unnormalizedQ[3][1] = s * f1; - unnormalizedQ[3][2] = p0; - } - - protected void frequenciesChanged() { - } - - protected void ratesChanged() { - } - - public String toString() { - - return SubstitutionModelUtils.toString(unnormalizedQ, dataType, 2); - } - - /** - * Normalize rate matrix to one expected substitution per unit time - * - * @param matrix the matrix to normalize to one expected substitution - * @param pi the equilibrium distribution of states - */ - void normalize(double[][] matrix, double[] pi) { - - double subst = 0.0; - int dimension = pi.length; - - for (int i = 0; i < dimension; i++) { - subst += -matrix[i][i] * pi[i]; - } - - // normalize, including switches - for (int i = 0; i < dimension; i++) { - for (int j = 0; j < dimension; j++) { - matrix[i][j] = matrix[i][j] / subst; - } - } - - double switchingProportion = 0.0; - switchingProportion += matrix[0][2] * pi[2]; - switchingProportion += matrix[2][0] * pi[0]; - switchingProportion += matrix[1][3] * pi[3]; - switchingProportion += matrix[3][1] * pi[1]; - - //System.out.println("switchingProportion=" + switchingProportion); - - // normalize, removing switches - for (int i = 0; i < dimension; i++) { - for (int j = 0; j < dimension; j++) { - matrix[i][j] = matrix[i][j] / (1.0 - switchingProportion); - } - } - } - - private Parameter alpha; - private Parameter switchRate; - private Parameter frequencies; - private Parameter hiddenFrequencies; - private final Version version; - -} \ No newline at end of file diff --git a/src/dr/oldevomodel/substmodel/Blosum62.java b/src/dr/oldevomodel/substmodel/Blosum62.java deleted file mode 100644 index fcf4d9b840..0000000000 --- a/src/dr/oldevomodel/substmodel/Blosum62.java +++ /dev/null @@ -1,218 +0,0 @@ -/* - * Blosum62.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.substmodel; - -import dr.evolution.datatype.AminoAcids; -import dr.util.Author; -import dr.util.Citation; - -import java.util.*; - -/** - * BLOSUM62 model of amino acid evolution - * Henikoff, S., and J. G. Henikoff. 1992. PNAS USA 89:10915-10919. - * - * - * @author Andrew Rambaut - * @author Alexei Drummond - */ -public class Blosum62 extends EmpiricalRateMatrix.AbstractAminoAcid { - - public static final Blosum62 INSTANCE = new Blosum62(); - - // The rates below are specified assuming that the amino acids are in this order: - // ARNDCQEGHILKMFPSTWYV - // but the AminoAcids dataType wants them in this order: - // ACDEFGHIKLMNPQRSTVWY - // This is solved by calling the setEmpiricalRates and setEmpiricalFrequencies methods - private Blosum62() { super("blosum62"); - - int n = AminoAcids.INSTANCE.getStateCount(); - - double[][] rate = new double[n][n]; - - // Q matrix - rate[0][1]=7.3579038969751e-01; rate[0][2]=4.8539105546575e-01; - rate[0][3]=5.4316182089867e-01; rate[0][4]=1.4599953104700e+00; - rate[0][5]=1.1997057046020e+00; rate[0][6]=1.1709490427999e+00; - rate[0][7]=1.9558835749595e+00; rate[0][8]=7.1624144499779e-01; - rate[0][9]=6.0589900368677e-01; rate[0][10]=8.0001653051838e-01; - rate[0][11]=1.2952012667833e+00; rate[0][12]=1.2537582666635e+00; - rate[0][13]=4.9296467974759e-01; rate[0][14]=1.1732759009239e+00; - rate[0][15]=4.3250926870566e+00; rate[0][16]=1.7291780194850e+00; - rate[0][17]=4.6583936772479e-01; rate[0][18]=7.1820669758623e-01; - rate[0][19]=2.1877745220045e+00; - - rate[1][2]=1.2974467051337e+00; rate[1][3]=5.0096440855513e-01; - rate[1][4]=2.2782657420895e-01; rate[1][5]=3.0208336100636e+00; - rate[1][6]=1.3605741904203e+00; rate[1][7]=4.1876330851753e-01; - rate[1][8]=1.4561411663360e+00; rate[1][9]=2.3203644514174e-01; - rate[1][10]=6.2271166969249e-01; rate[1][11]=5.4111151414889e+00; - rate[1][12]=9.8369298745695e-01; rate[1][13]=3.7164469320875e-01; - rate[1][14]=4.4813366171831e-01; rate[1][15]=1.1227831042096e+00; - rate[1][16]=9.1466595456337e-01; rate[1][17]=4.2638231012175e-01; - rate[1][18]=7.2051744121611e-01; rate[1][19]=4.3838834377202e-01; - - rate[2][3]=3.1801000482161e+00; rate[2][4]=3.9735894989702e-01; - rate[2][5]=1.8392161469920e+00; rate[2][6]=1.2404885086396e+00; - rate[2][7]=1.3558723444845e+00; rate[2][8]=2.4145014342081e+00; - rate[2][9]=2.8301732627800e-01; rate[2][10]=2.1188815961519e-01; - rate[2][11]=1.5931370434574e+00; rate[2][12]=6.4844127878707e-01; - rate[2][13]=3.5486124922252e-01; rate[2][14]=4.9488704370192e-01; - rate[2][15]=2.9041016564560e+00; rate[2][16]=1.8981736345332e+00; - rate[2][17]=1.9148204624678e-01; rate[2][18]=5.3822251903674e-01; - rate[2][19]=3.1285879799342e-01; - - rate[3][4]=2.4083661480204e-01; rate[3][5]=1.1909457033960e+00; - rate[3][6]=3.7616252083685e+00; rate[3][7]=7.9847324896839e-01; - rate[3][8]=7.7814266402188e-01; rate[3][9]=4.1855573246161e-01; - rate[3][10]=2.1813157759360e-01; rate[3][11]=1.0324479249521e+00; - rate[3][12]=2.2262189795786e-01; rate[3][13]=2.8173069420651e-01; - rate[3][14]=7.3062827299842e-01; rate[3][15]=1.5827541420653e+00; - rate[3][16]=9.3418750943056e-01; rate[3][17]=1.4534504627853e-01; - rate[3][18]=2.6142220896504e-01; rate[3][19]=2.5812928941763e-01; - - rate[4][5]=3.2980150463028e-01; rate[4][6]=1.4074889181440e-01; - rate[4][7]=4.1820319228376e-01; rate[4][8]=3.5405810983129e-01; - rate[4][9]=7.7489402279418e-01; rate[4][10]=8.3184264014158e-01; - rate[4][11]=2.8507880090648e-01; rate[4][12]=7.6768882347954e-01; - rate[4][13]=4.4133747118660e-01; rate[4][14]=3.5600849876863e-01; - rate[4][15]=1.1971884150942e+00; rate[4][16]=1.1198313585160e+00; - rate[4][17]=5.2766441887169e-01; rate[4][18]=4.7023773369610e-01; - rate[4][19]=1.1163524786062e+00; - - rate[5][6]=5.5289191779282e+00; rate[5][7]=6.0984630538281e-01; - rate[5][8]=2.4353411311401e+00; rate[5][9]=2.3620245120365e-01; - rate[5][10]=5.8073709318144e-01; rate[5][11]=3.9452776745146e+00; - rate[5][12]=2.4948960771127e+00; rate[5][13]=1.4435695975031e-01; - rate[5][14]=8.5857057567418e-01; rate[5][15]=1.9348709245965e+00; - rate[5][16]=1.2774802945956e+00; rate[5][17]=7.5865380864172e-01; - rate[5][18]=9.5898974285014e-01; rate[5][19]=5.3078579012486e-01; - - rate[6][7]=4.2357999217628e-01; rate[6][8]=1.6268910569817e+00; - rate[6][9]=1.8684804693170e-01; rate[6][10]=3.7262517508685e-01; - rate[6][11]=2.8024271516787e+00; rate[6][12]=5.5541539747043e-01; - rate[6][13]=2.9140908416530e-01; rate[6][14]=9.2656393484598e-01; - rate[6][15]=1.7698932389373e+00; rate[6][16]=1.0710972360073e+00; - rate[6][17]=4.0763564893830e-01; rate[6][18]=5.9671930034577e-01; - rate[6][19]=5.2425384633796e-01; - - rate[7][8]=5.3985912495418e-01; rate[7][9]=1.8929629237636e-01; - rate[7][10]=2.1772115923623e-01; rate[7][11]=7.5204244030271e-01; - rate[7][12]=4.5943617357855e-01; rate[7][13]=3.6816646445253e-01; - rate[7][14]=5.0408659952683e-01; rate[7][15]=1.5093262532236e+00; - rate[7][16]=6.4143601140497e-01; rate[7][17]=5.0835892463812e-01; - rate[7][18]=3.0805573703500e-01; rate[7][19]=2.5334079019018e-01; - - rate[8][9]=2.5271844788492e-01; rate[8][10]=3.4807220979697e-01; - rate[8][11]=1.0225070358890e+00; rate[8][12]=9.8431152535870e-01; - rate[8][13]=7.1453370392764e-01; rate[8][14]=5.2700733915060e-01; - rate[8][15]=1.1170297629105e+00; rate[8][16]=5.8540709022472e-01; - rate[8][17]=3.0124860078016e-01; rate[8][18]=4.2189539693890e+00; - rate[8][19]=2.0155597175031e-01; - - rate[9][10]=3.8909637733035e+00; rate[9][11]=4.0619358664202e-01; - rate[9][12]=3.3647977631042e+00; rate[9][13]=1.5173593259539e+00; - rate[9][14]=3.8835540920564e-01; rate[9][15]=3.5754441245967e-01; - rate[9][16]=1.1790911972601e+00; rate[9][17]=3.4198578754023e-01; - rate[9][18]=6.7461709322842e-01; rate[9][19]=8.3118394054582e+00; - - rate[10][11]=4.4557027426059e-01; rate[10][12]=6.0305593795716e+00; - rate[10][13]=2.0648397032375e+00; rate[10][14]=3.7455568747097e-01; - rate[10][15]=3.5296918452729e-01; rate[10][16]=9.1525985769421e-01; - rate[10][17]=6.9147463459998e-01; rate[10][18]=8.1124585632307e-01; - rate[10][19]=2.2314056889131e+00; - - rate[11][12]=1.0730611843319e+00; rate[11][13]=2.6692475051102e-01; - rate[11][14]=1.0473834507215e+00; rate[11][15]=1.7521659178195e+00; - rate[11][16]=1.3038752007987e+00; rate[11][17]=3.3224304063396e-01; - rate[11][18]=7.1799348690032e-01; rate[11][19]=4.9813847530407e-01; - - rate[12][13]=1.7738551688305e+00; rate[12][14]=4.5412362510273e-01; - rate[12][15]=9.1872341574605e-01; rate[12][16]=1.4885480537218e+00; - rate[12][17]=8.8810109815193e-01; rate[12][18]=9.5168216224591e-01; - rate[12][19]=2.5758507553153e+00; - - rate[13][14]=2.3359790962888e-01; rate[13][15]=5.4002764482413e-01; - rate[13][16]=4.8820611879305e-01; rate[13][17]=2.0743248934965e+00; - rate[13][18]=6.7472604308008e+00; rate[13][19]=8.3811961017754e-01; - - rate[14][15]=1.1691295777157e+00; rate[14][16]=1.0054516831488e+00; - rate[14][17]=2.5221483002727e-01; rate[14][18]=3.6940531935451e-01; - rate[14][19]=4.9690841067567e-01; - - rate[15][16]=5.1515562922704e+00; rate[15][17]=3.8792562209837e-01; - rate[15][18]=7.9675152076106e-01; rate[15][19]=5.6192545744165e-01; - - rate[16][17]=5.1312812689059e-01; rate[16][18]=8.0101024319939e-01; - rate[16][19]=2.2530740511763e+00; - - rate[17][18]=4.0544190065580e+00; rate[17][19]=2.6650873142646e-01; - - rate[18][19]=1.0000000000000e+00; - - setEmpiricalRates(rate, "ARNDCQEGHILKMFPSTWYV"); - - double[] f = new double[n]; - f[0]=0.074; f[1]=0.052; f[2]=0.045; f[3]=0.054; - f[4]=0.025; f[5]=0.034; f[6]=0.054; f[7]=0.074; - f[8]=0.026; f[9]=0.068; f[10]=0.099; f[11]=0.058; - f[12]=0.025; f[13]=0.047; f[14]=0.039; f[15]=0.057; - f[16]=0.051; f[17]=0.013; f[18]=0.032; f[19]=0.073; - - setEmpiricalFrequencies(f, "ARNDCQEGHILKMFPSTWYV"); - } - - @Override - public Citation.Category getCategory() { - return Citation.Category.SUBSTITUTION_MODELS; - } - - @Override - public String getDescription() { - return "Blosum62 amino acid substitution model"; - } - - @Override - public List getCitations() { - return Collections.singletonList(CITATION); - } - - public static Citation CITATION = new Citation( - new Author[]{ - new Author("S", "Henikoff"), - new Author("JG", "Henikoff") - }, - "Amino acid substitution matrices from protein blocks", - 1992, - "Proc Natl Acad Sci, USA", - 89, - 10915, 10919, - Citation.Status.PUBLISHED - ); -} diff --git a/src/dr/oldevomodel/substmodel/CPREV.java b/src/dr/oldevomodel/substmodel/CPREV.java deleted file mode 100644 index e45510a305..0000000000 --- a/src/dr/oldevomodel/substmodel/CPREV.java +++ /dev/null @@ -1,234 +0,0 @@ -/* - * CPREV.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.substmodel; - -import dr.evolution.datatype.AminoAcids; -import dr.util.Author; -import dr.util.Citation; - -import java.util.*; - -/** - * CPREV 45 model of amino acid evolution - * Adachi, J., P.J. Waddell, W. Martin, and M. Hasegawa. 2000. JME 50:348-358 - * - * - * @author Andrew Rambaut - * @author Alexei Drummond - */ -public class CPREV extends EmpiricalRateMatrix.AbstractAminoAcid { - - public static final CPREV INSTANCE = new CPREV(); - - // The rates below are specified assuming that the amino acids are in this order: - // ARNDCQEGHILKMFPSTWYV - // but the AminoAcids dataType wants them in this order: - // ACDEFGHIKLMNPQRSTVWY - // This is solved by calling the setEmpiricalRates and setEmpiricalFrequencies methods - private CPREV() { super("cpREV45"); - - int n = AminoAcids.INSTANCE.getStateCount(); - - double[][] rate = new double[n][n]; - - // Q matrix - rate[0][1] = 105; rate[0][2] = 227; - rate[0][3] = 175; rate[0][4] = 669; - rate[0][5] = 157; rate[0][6] = 499; - rate[0][7] = 665; rate[0][8] = 66; - rate[0][9] = 145; rate[0][10] = 197; - rate[0][11] = 236; rate[0][12] = 185; - rate[0][13] = 68; rate[0][14] = 490; - rate[0][15] = 2440; rate[0][16] = 1340; - rate[0][17] = 14; rate[0][18] = 56; - rate[0][19] = 968; - - rate[1][2] = 357; rate[1][3] = 43; - rate[1][4] = 823; rate[1][5] = 1745; - rate[1][6] = 152; rate[1][7] = 243; - rate[1][8] = 715; rate[1][9] = 136; - rate[1][10] = 203; rate[1][11] = 4482; - rate[1][12] = 125; rate[1][13] = 53; - rate[1][14] = 87; rate[1][15] = 385; - rate[1][16] = 314; rate[1][17] = 230; - rate[1][18] = 323; rate[1][19] = 92; - - rate[2][3] = 4435; rate[2][4] = 538; - rate[2][5] = 768; rate[2][6] = 1055; - rate[2][7] = 653; rate[2][8] = 1405; - rate[2][9] = 168; rate[2][10] = 113; - rate[2][11] = 2430; rate[2][12] = 61; - rate[2][13] = 97; rate[2][14] = 173; - rate[2][15] = 2085; rate[2][16] = 1393; - rate[2][17] = 40; rate[2][18] = 754; - rate[2][19] = 83; - - rate[3][4] = 10; rate[3][5] = 400; - rate[3][6] = 3691; rate[3][7] = 431; - rate[3][8] = 331; rate[3][9] = 10; - rate[3][10] = 10; rate[3][11] = 412; - rate[3][12] = 47; rate[3][13] = 22; - rate[3][14] = 170; rate[3][15] = 590; - rate[3][16] = 266; rate[3][17] = 18; - rate[3][18] = 281; rate[3][19] = 75; - - rate[4][5] = 10; rate[4][6] = 10; - rate[4][7] = 303; rate[4][8] = 441; - rate[4][9] = 280; rate[4][10] = 396; - rate[4][11] = 48; rate[4][12] = 159; - rate[4][13] = 726; rate[4][14] = 285; - rate[4][15] = 2331; rate[4][16] = 576; - rate[4][17] = 435; rate[4][18] = 1466; - rate[4][19] = 592; - - rate[5][6] = 3122; rate[5][7] = 133; - rate[5][8] = 1269; rate[5][9] = 92; - rate[5][10] = 286; rate[5][11] = 3313; - rate[5][12] = 202; rate[5][13] = 10; - rate[5][14] = 323; rate[5][15] = 396; - rate[5][16] = 241; rate[5][17] = 53; - rate[5][18] = 391; rate[5][19] = 54; - - rate[6][7] = 379; rate[6][8] = 162; - rate[6][9] = 148; rate[6][10] = 82; - rate[6][11] = 2629; rate[6][12] = 113; - rate[6][13] = 145; rate[6][14] = 185; - rate[6][15] = 568; rate[6][16] = 369; - rate[6][17] = 63; rate[6][18] = 142; - rate[6][19] = 200; - - rate[7][8] = 19; rate[7][9] = 40; - rate[7][10] = 20; rate[7][11] = 263; - rate[7][12] = 21; rate[7][13] = 25; - rate[7][14] = 28; rate[7][15] = 691; - rate[7][16] = 92; rate[7][17] = 82; - rate[7][18] = 10; rate[7][19] = 91; - - rate[8][9] = 29; rate[8][10] = 66; - rate[8][11] = 305; rate[8][12] = 10; - rate[8][13] = 127; rate[8][14] = 152; - rate[8][15] = 303; rate[8][16] = 32; - rate[8][17] = 69; rate[8][18] = 1971; - rate[8][19] = 25; - - rate[9][10] = 1745; rate[9][11] = 345; - rate[9][12] = 1772; rate[9][13] = 454; - rate[9][14] = 117; rate[9][15] = 216; - rate[9][16] = 1040; rate[9][17] = 42; - rate[9][18] = 89; rate[9][19] = 4797; - - rate[10][11] = 218; rate[10][12] = 1351; - rate[10][13] = 1268; rate[10][14] = 219; - rate[10][15] = 516; rate[10][16] = 156; - rate[10][17] = 159; rate[10][18] = 189; - rate[10][19] = 865; - - rate[11][12] = 193; rate[11][13] = 72; - rate[11][14] = 302; rate[11][15] = 868; - rate[11][16] = 918; rate[11][17] = 10; - rate[11][18] = 247; rate[11][19] = 249; - - rate[12][13] = 327; rate[12][14] = 100; - rate[12][15] = 93; rate[12][16] = 645; - rate[12][17] = 86; rate[12][18] = 215; - rate[12][19] = 475; - - rate[13][14] = 43; rate[13][15] = 487; - rate[13][16] = 148; rate[13][17] = 468; - rate[13][18] = 2370; rate[13][19] = 317; - - rate[14][15] = 1202; rate[14][16] = 260; - rate[14][17] = 49; rate[14][18] = 97; - rate[14][19] = 122; - - rate[15][16] = 2151; rate[15][17] = 73; - rate[15][18] = 522; rate[15][19] = 167; - - rate[16][17] = 29; rate[16][18] = 71; - rate[16][19] = 760; - - rate[17][18] = 346; rate[17][19] = 10; - - rate[18][19] = 119; - - setEmpiricalRates(rate, "ARNDCQEGHILKMFPSTWYV"); - - double[] f = new double[n]; - f[0] = 0.076; - f[1] = 0.062; - f[2] = 0.041; - f[3] = 0.037; - f[4] = 0.009; - f[5] = 0.038; - f[6] = 0.049; - f[7] = 0.084; - f[8] = 0.025; - f[9] = 0.081; - f[10] = 0.101; - f[11] = 0.050; - f[12] = 0.022; - f[13] = 0.051; - f[14] = 0.043; - f[15] = 0.062; - f[16] = 0.054; - f[17] = 0.018; - f[18] = 0.031; - f[19] = 0.066; - setEmpiricalFrequencies(f, "ARNDCQEGHILKMFPSTWYV"); - } - - @Override - public Citation.Category getCategory() { - return Citation.Category.SUBSTITUTION_MODELS; - } - - @Override - public String getDescription() { - return "CPREV amino acid substitution model"; - } - - @Override - public List getCitations() { - return Collections.singletonList(CITATION); - } - - public static Citation CITATION = new Citation( - new Author[]{ - new Author("J", "Adachi"), - new Author("PJ", "Waddell"), - new Author("W", "Martin"), - new Author("M", "Hasegawa") - }, - "Plastid Genome Phylogeny and a Model of Amino Acid Substitution for Proteins Encoded by Chloroplast DNA", - 2000, - "J Mol Evol", - 50, - 348, 358, - Citation.Status.PUBLISHED - ); -} diff --git a/src/dr/oldevomodel/substmodel/ComplexSubstitutionModel.java b/src/dr/oldevomodel/substmodel/ComplexSubstitutionModel.java deleted file mode 100644 index c20453d1c8..0000000000 --- a/src/dr/oldevomodel/substmodel/ComplexSubstitutionModel.java +++ /dev/null @@ -1,603 +0,0 @@ -/* - * ComplexSubstitutionModel.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.substmodel; - -import cern.colt.matrix.DoubleMatrix1D; -import cern.colt.matrix.DoubleMatrix2D; -import cern.colt.matrix.impl.DenseDoubleMatrix2D; -import cern.colt.matrix.linalg.Algebra; -import cern.colt.matrix.linalg.EigenvalueDecomposition; -import cern.colt.matrix.linalg.Property; -import dr.evolution.datatype.DataType; -import dr.inference.loggers.LogColumn; -import dr.inference.loggers.NumberColumn; -import dr.inference.model.*; -import dr.math.matrixAlgebra.Matrix; -import dr.math.matrixAlgebra.RobustEigenDecomposition; -import dr.math.matrixAlgebra.RobustSingularValueDecomposition; -import dr.util.Citable; -import dr.util.Citation; -import dr.util.CommonCitations; - -import java.util.*; - -/** - * A general irreversible class for any - * data type; allows complex eigenstructures. - * - * @author Marc Suchard - */ - -public class ComplexSubstitutionModel extends AbstractSubstitutionModel implements Likelihood, Citable { - - public ComplexSubstitutionModel(String name, DataType dataType, - FrequencyModel rootFreqModel, Parameter parameter) { - - super(name, dataType, rootFreqModel); - this.infinitesimalRates = parameter; - - rateCount = stateCount * (stateCount - 1); - - if (parameter != null) { - if (rateCount != infinitesimalRates.getDimension()) { - throw new RuntimeException("Dimension of '" + infinitesimalRates.getId() + "' (" - + infinitesimalRates.getDimension() + ") must equal " + rateCount); - } - addVariable(infinitesimalRates); - } - - - stationaryDistribution = new double[stateCount]; - storedStationaryDistribution = new double[stateCount]; - - } - - protected void handleModelChangedEvent(Model model, Object object, int index) { - if (model == freqModel) - return; // freqModel only affects the likelihood calculation at the tree root - super.handleModelChangedEvent(model, object, index); - } - - protected void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) { -// if (!updateMatrix) { - updateMatrix = true; -// fireModelChanged(); -// } - } - - protected void restoreState() { - - // To restore all this stuff just swap the pointers... - - double[] tmp3 = storedEvalImag; - storedEvalImag = EvalImag; - EvalImag = tmp3; - - tmp3 = storedStationaryDistribution; - storedStationaryDistribution = stationaryDistribution; - stationaryDistribution = tmp3; - -// normalization = storedNormalization; - - // Inherited - updateMatrix = storedUpdateMatrix; - wellConditioned = storedWellConditioned; - - double[] tmp1 = storedEval; - storedEval = Eval; - Eval = tmp1; - - double[][] tmp2 = storedIevc; - storedIevc = Ievc; - Ievc = tmp2; - - tmp2 = storedEvec; - storedEvec = Evec; - Evec = tmp2; - - } - - protected void storeState() { - - storedUpdateMatrix = updateMatrix; - -// if(updateMatrix) -// System.err.println("Storing updatable state!"); - - storedWellConditioned = wellConditioned; - - System.arraycopy(stationaryDistribution, 0, storedStationaryDistribution, 0, stateCount); - System.arraycopy(EvalImag, 0, storedEvalImag, 0, stateCount); -// storedNormalization = normalization; - - // Inherited - System.arraycopy(Eval, 0, storedEval, 0, stateCount); - for (int i = 0; i < stateCount; i++) { - System.arraycopy(Ievc[i], 0, storedIevc[i], 0, stateCount); - System.arraycopy(Evec[i], 0, storedEvec[i], 0, stateCount); - } - } - - public void getTransitionProbabilities(double distance, double[] matrix) { - - double temp; - - int i, j, k; - - synchronized (this) { - if (updateMatrix) { - setupMatrix(); - } - } - - if (!wellConditioned) { - Arrays.fill(matrix, 0.0); - return; - } - - -// Eigenvalues and eigenvectors of a real matrix A. -// -// If A is symmetric, then A = V*D*V' where the eigenvalue matrix D is diagonal -// and the eigenvector matrix V is orthogonal. I.e. A = V D V^t and V V^t equals -// the identity matrix. -// -// If A is not symmetric, then the eigenvalue matrix D is block diagonal with -// the real eigenvalues in 1-by-1 blocks and any complex eigenvalues, -// lambda + i*mu, in 2-by-2 blocks, [lambda, mu; -mu, lambda]. The columns -// of V represent the eigenvectors in the sense that A*V = V*D. The matrix -// V may be badly conditioned, or even singular, so the validity of the -// equation A = V D V^{-1} depends on the conditioning of V. - - double[][] iexp = popiexp(); - - for (i = 0; i < stateCount; i++) { - - if (EvalImag[i] == 0) { - // 1x1 block - temp = Math.exp(distance * Eval[i]); - for (j = 0; j < stateCount; j++) { - iexp[i][j] = Ievc[i][j] * temp; - } - } else { - // 2x2 conjugate block - // If A is 2x2 with complex conjugate pair eigenvalues a +/- bi, then - // exp(At) = exp(at)*( cos(bt)I + \frac{sin(bt)}{b}(A - aI)). - int i2 = i + 1; - double b = EvalImag[i]; - double expat = Math.exp(distance * Eval[i]); - double expatcosbt = expat * Math.cos(distance * b); - double expatsinbt = expat * Math.sin(distance * b); - - for (j = 0; j < stateCount; j++) { - iexp[i][j] = expatcosbt * Ievc[i][j] + expatsinbt * Ievc[i2][j]; - iexp[i2][j] = expatcosbt * Ievc[i2][j] - expatsinbt * Ievc[i][j]; - } - i++; // processed two conjugate rows - } - } - - int u = 0; - for (i = 0; i < stateCount; i++) { - for (j = 0; j < stateCount; j++) { - temp = 0.0; - for (k = 0; k < stateCount; k++) { - temp += Evec[i][k] * iexp[k][j]; - } - if (temp < 0.0) - matrix[u] = minProb; - else - matrix[u] = temp; - u++; - } - } - pushiexp(iexp); - } - - public double[] getStationaryDistribution() { - return stationaryDistribution; - } - - protected void computeStationaryDistribution() { - stationaryDistribution = freqModel.getFrequencies(); - } - - - protected double[] getRates() { - return infinitesimalRates.getParameterValues(); - } - - protected double[] getPi() { - return freqModel.getFrequencies(); - } - - public void setupMatrix() { - - if (!eigenInitialised) { - initialiseEigen(); - storedEvalImag = new double[stateCount]; - } - - int i = 0; - - storeIntoAmat(); - - - makeValid(amat, stateCount); - - // compute eigenvalues and eigenvectors -// EigenvalueDecomposition eigenDecomp = new EigenvalueDecomposition(new DenseDoubleMatrix2D(amat)); - - RobustEigenDecomposition eigenDecomp; - try { - eigenDecomp = new RobustEigenDecomposition(new DenseDoubleMatrix2D(amat), maxIterations); - } catch (ArithmeticException ae) { - System.err.println(ae.getMessage()); - wellConditioned = false; - System.err.println("amat = \n" + new Matrix(amat)); - return; - } - - DoubleMatrix2D eigenV = eigenDecomp.getV(); - DoubleMatrix1D eigenVReal = eigenDecomp.getRealEigenvalues(); - DoubleMatrix1D eigenVImag = eigenDecomp.getImagEigenvalues(); - DoubleMatrix2D eigenVInv; - - // A better (?) approach to checking diagonalizability comes from: - // - // J. Gentle (2007) Matrix Algebra - // - // Diagonalizbility Theorem: A matrix A is (complex) diagonalizable iff all distinct eigenvalues \lambda_l - // with algebraic multiplicity m_l are semi-simple, i.e. - // - // rank(A - \lambda_l I) = n - m_l - // - // Equivalently (?), eigenV must be non-singular. - // - // SVD is needed to numerically approximate the rank of a matrix, so we can check Algrebra.rank() - // or Algebra.cond() with almost equal amounts of work. I don't know which is more reliable. -- MAS - - if (checkConditioning) { - RobustSingularValueDecomposition svd; - try { - svd = new RobustSingularValueDecomposition(eigenV, maxIterations); - } catch (ArithmeticException ae) { - System.err.println(ae.getMessage()); - wellConditioned = false; - return; - } - if (svd.cond() > maxConditionNumber) { - wellConditioned = false; - return; - } - } - - try { - eigenVInv = alegbra.inverse(eigenV); - } catch (IllegalArgumentException e) { - wellConditioned = false; - return; - } - - Ievc = eigenVInv.toArray(); - Evec = eigenV.toArray(); - Eval = eigenVReal.toArray(); - EvalImag = eigenVImag.toArray(); - - // Check for valid decomposition - for (i = 0; i < stateCount; i++) { - if (Double.isNaN(Eval[i]) || Double.isNaN(EvalImag[i]) || - Double.isInfinite(Eval[i]) || Double.isInfinite(EvalImag[i])) { - wellConditioned = false; - return; - } else if (Math.abs(Eval[i]) < 1e-10) { - Eval[i] = 0.0; - } - } - - updateMatrix = false; - wellConditioned = true; - // compute normalization and rescale eigenvalues - - computeStationaryDistribution(); - - if (doNormalization) { - double subst = 0.0; - - for (i = 0; i < stateCount; i++) - subst += -amat[i][i] * stationaryDistribution[i]; - -// normalization = subst; - - for (i = 0; i < stateCount; i++) { - Eval[i] /= subst; - EvalImag[i] /= subst; - } - } - } - - //store the infinitesimal rates in the vector to a matrix called amat - //store the infinitesimal rates in the vector to a matrix called amat - public void storeIntoAmat(){ - double[] rates = getRates(); - double[] pi = getPi(); - int i, j, k = 0; - for (i = 0; i < stateCount; i++) { - for (j = i+1; j < stateCount; j++) { - amat[i][j] = rates[k++] * pi[j]; - } - } - // Copy lower triangle in column-order form (transposed) - for (j = 0; j< stateCount; j++) { - for (i = j+1; i < stateCount; i++) { - amat[i][j] = rates[k++] * pi[j]; - } - } - } - - private void printDebugSetupMatrix() { - System.out.println("Normalized infinitesimal rate matrix:"); - System.out.println(new Matrix(amat)); - System.out.println(new Matrix(amat).toStringOctave()); -// System.out.println("Normalization = " + normalization); - System.out.println("Values in setupMatrix():"); -// System.out.println(eigenV); -// System.out.println(eigenVInv); -// System.out.println(eigenVReal); - } - - protected void checkComplexSolutions() { - boolean complex = false; - for (int i = 0; i < stateCount && !complex; i++) { - if (EvalImag[i] != 0) - complex = true; - } - isComplex = complex; - } - - public boolean getIsComplex() { - return isComplex; - } - - protected void frequenciesChanged() { - } - - protected void ratesChanged() { - } - - protected void setupRelativeRates() { - } - - protected Parameter infinitesimalRates; - -// public LogColumn[] getColumns() { -// -// LogColumn[] columnList = new LogColumn[stateCount * stateCount]; -// int index = 0; -// for (int i = 0; i < stateCount; i++) { -// for (int j = 0; j < stateCount; j++) -// columnList[index++] = new MatrixEntryColumn(getId(), i, j, amat); -// } -// return columnList; -// } - - public LogColumn[] getColumns() { - return new LogColumn[]{ - new LikelihoodColumn(getId()) - }; - } - - protected class LikelihoodColumn extends NumberColumn { - public LikelihoodColumn(String label) { - super(label); - } - - public double getDoubleValue() { - return getLogLikelihood(); - } - } - - - public static void main(String[] arg) { - -// Parameter rates = new Parameter.Default(new double[]{5.0, 1.0, 1.0, 0.1, 5.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0}); -// Parameter rates = new Parameter.Default(new double[] {5.0, 1.0, 1.0, 1.0, 5.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0}); -// Parameter rates = new Parameter.Default(new double[] {1.0, 1.0}); - - - Parameter rates = new Parameter.Default(159600, 1.0); - - - DataType dataType = new DataType() { - - public String getDescription() { - return null; - } - - public int getType() { - return 0; - } - - @Override - public char[] getValidChars() { - return null; - } - - public int getStateCount() { - return 400; - } - }; - - FrequencyModel freqModel = new FrequencyModel(dataType, new Parameter.Default(400, 1.0 / 400.0)); - - ComplexSubstitutionModel substModel = new ComplexSubstitutionModel("test", -// TwoStates.INSTANCE, - dataType, - freqModel, - rates); - - long start = System.currentTimeMillis(); - double[] finiteTimeProbs = new double[substModel.getDataType().getStateCount() * substModel.getDataType().getStateCount()]; - double time = 1.0; - substModel.getTransitionProbabilities(time, finiteTimeProbs); - long end = System.currentTimeMillis(); - System.out.println("Time: " + (end - start)); -// System.out.println("Results:"); -// System.out.println(new Vector(finiteTimeProbs)); - -// System.out.println("COLT value:"); -// This should work, matches 'octave' results -// DoubleMatrix2D result = alegbra.mult(substModel.eigenV, alegbra.mult(blockDiagonalExponential(1.0, substModel.eigenD), substModel.eigenVInv)); -// -// System.out.println(result); - - } - - public void setMaxIterations(int max) { - maxIterations = max; - } - - public void setMaxConditionNumber(double max) { - maxConditionNumber = max; - } - - public void setCheckConditioning(boolean check) { - checkConditioning = check; - } - - private static DoubleMatrix2D blockDiagonalExponential(double distance, DoubleMatrix2D mat) { - for (int i = 0; i < mat.rows(); i++) { - if ((i + 1) < mat.rows() && mat.getQuick(i, i + 1) != 0) { - double a = mat.getQuick(i, i); - double b = mat.getQuick(i, i + 1); - double expat = Math.exp(distance * a); - double cosbt = Math.cos(distance * b); - double sinbt = Math.sin(distance * b); - mat.setQuick(i, i, expat * cosbt); - mat.setQuick(i + 1, i + 1, expat * cosbt); - mat.setQuick(i, i + 1, expat * sinbt); - mat.setQuick(i + 1, i, -expat * sinbt); - i++; // processed two entries in loop - } else - mat.setQuick(i, i, Math.exp(distance * mat.getQuick(i, i))); // 1x1 block - } - return mat; - } - - private boolean isComplex = false; - private double[] stationaryDistribution = null; - private double[] storedStationaryDistribution; - - protected boolean doNormalization = true; -// private Double normalization; -// private Double storedNormalization; - - protected double[] EvalImag; - protected double[] storedEvalImag; - - protected boolean wellConditioned = true; - private boolean storedWellConditioned; -// private double[] illConditionedProbabilities; - - protected static final double minProb = Property.DEFAULT.tolerance(); - // private static final double minProb = 1E-20; - // private static final double minProb = Property.ZERO.tolerance(); - private static final Algebra alegbra = new Algebra(minProb); - EigenvalueDecomposition eigenDecomp; - EigenvalueDecomposition storedEigenDecomp; - - private double maxConditionNumber = 1000; - - private int maxIterations = 1000; - - private boolean checkConditioning = true; - - public Model getModel() { - return this; - } - - public double getLogLikelihood() { - if (BayesianStochasticSearchVariableSelection.Utils.connectedAndWellConditioned(probability,this)) - return 0; - return Double.NEGATIVE_INFINITY; - } - - /** - * Needs to be evaluated before the corresponding data likelihood. - * @return - */ - public boolean evaluateEarly() { - return true; - } - - public String prettyName() { - return Abstract.getPrettyName(this); - } - - public void setNormalization(boolean doNormalization) { - this.doNormalization = doNormalization; - } - - public void makeDirty() { - - } - - @Override - public Set getLikelihoodSet() { - return new HashSet(Arrays.asList(this)); - } - - @Override - public boolean isUsed() { - return super.isUsed() && isUsed; - } - - public void setUsed() { - isUsed = true; - } - - private boolean isUsed = false; - - private double[] probability = null; - - @Override - public Citation.Category getCategory() { - return Citation.Category.SUBSTITUTION_MODELS; - } - - @Override - public String getDescription() { - return "Complex-diagonalizable, irreversible substitution model"; - } - - @Override - public List getCitations() { - return Collections.singletonList(CommonCitations.EDWARDS_2011_ANCIENT); - } - -} \ No newline at end of file diff --git a/src/dr/oldevomodel/substmodel/CovarionFrequencyModel.java b/src/dr/oldevomodel/substmodel/CovarionFrequencyModel.java deleted file mode 100644 index cd5d029cf4..0000000000 --- a/src/dr/oldevomodel/substmodel/CovarionFrequencyModel.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * CovarionFrequencyModel.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.substmodel; - -import dr.evolution.datatype.DataType; -import dr.inference.model.Parameter; - -/** - * @author Alexei Drummond - */ -public class CovarionFrequencyModel extends FrequencyModel { - - public CovarionFrequencyModel(DataType dataType, Parameter frequencyParameter, Parameter hiddenFrequencies) { - super(dataType, frequencyParameter); - - this.hiddenFrequencies = hiddenFrequencies; - addVariable(hiddenFrequencies); - } - - public double[] getFrequencies() { - - int k = 0; - - int numStates = frequencyParameter.getDimension(); - int numHiddenStates = hiddenFrequencies.getDimension(); - - double[] freqs = new double[numStates * numHiddenStates]; - for (int i = 0; i < numHiddenStates; i++) { - for (int j = 0; j < numStates; j++) { - freqs[k] = frequencyParameter.getParameterValue(j) * - hiddenFrequencies.getParameterValue(i); - k += 1; - } - } - - return freqs; - } - - public void setFrequency(int i, double value) { - throw new UnsupportedOperationException(); - } - - public double getFrequency(int i) { - - int numStates = frequencyParameter.getDimension(); - - return frequencyParameter.getParameterValue(i % numStates) * - hiddenFrequencies.getParameterValue(i / numStates); - } - - public int getFrequencyCount() { - return frequencyParameter.getDimension() * hiddenFrequencies.getDimension(); - } - - Parameter hiddenFrequencies; -} diff --git a/src/dr/oldevomodel/substmodel/CovarionGTR.java b/src/dr/oldevomodel/substmodel/CovarionGTR.java deleted file mode 100644 index 84a65b75b7..0000000000 --- a/src/dr/oldevomodel/substmodel/CovarionGTR.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * CovarionGTR.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.substmodel; - -import dr.evolution.datatype.OldHiddenNucleotides; -import dr.oldevomodelxml.substmodel.CovarionGTRParser; -import dr.inference.model.Parameter; - -/** - * A general time reversible model of nucleotide evolution with - * covarion hidden rate categories. - * - * @author Alexei Drummond - */ -public class CovarionGTR extends AbstractCovarionDNAModel { - /** - * constructor - * - * @param dataType the data type - * @param freqModel the equlibrium frequencies - * @param hiddenRates the relative rates of the hidden categories - * (first hidden category has rate 1.0 so this parameter - * has dimension one less than number of hidden categories. - * @param rateACParameter the relative rate of A<->C substitutions - * @param rateAGParameter the relative rate of A<->G substitutions - * @param rateATParameter the relative rate of A<->T substitutions - * @param rateCGParameter the relative rate of C<->G substitutions - * @param rateCTParameter the relative rate of C<->T substitutions - * @param rateGTParameter the relative rate of G<->T substitutions - * each hidden category. - * @param switchingRates rates of switching between hidden rate classes - */ - public CovarionGTR( - OldHiddenNucleotides dataType, - Parameter hiddenRates, - Parameter switchingRates, - Parameter rateACParameter, - Parameter rateAGParameter, - Parameter rateATParameter, - Parameter rateCGParameter, - Parameter rateCTParameter, - Parameter rateGTParameter, - FrequencyModel freqModel) { - - super(CovarionGTRParser.GTR_COVARION_MODEL, dataType, hiddenRates, switchingRates, freqModel); - if (rateACParameter != null) { - addVariable(rateACParameter); - rateACParameter.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, 0.0, 1)); - this.rateACParameter = rateACParameter; - } - - if (rateAGParameter != null) { - addVariable(rateAGParameter); - rateAGParameter.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, 0.0, 1)); - this.rateAGParameter = rateAGParameter; - } - - if (rateATParameter != null) { - addVariable(rateATParameter); - rateATParameter.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, 0.0, 1)); - this.rateATParameter = rateATParameter; - } - - if (rateCGParameter != null) { - addVariable(rateCGParameter); - rateCGParameter.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, 0.0, 1)); - this.rateCGParameter = rateCGParameter; - } - - if (rateCTParameter != null) { - addVariable(rateCTParameter); - rateCTParameter.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, 0.0, 1)); - this.rateCTParameter = rateCTParameter; - } - - if (rateGTParameter != null) { - addVariable(rateGTParameter); - rateGTParameter.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, 0.0, 1)); - this.rateGTParameter = rateGTParameter; - } - } - - double[] getRelativeDNARates() { - double[] rr = new double[6]; - for (int i = 0; i < rr.length; i++) { - rr[i] = 1.0; - } - - if (rateACParameter != null) { - rr[0] = rateACParameter.getParameterValue(0); - } - if (rateAGParameter != null) { - rr[1] = rateAGParameter.getParameterValue(0); - } - if (rateATParameter != null) { - rr[2] = rateATParameter.getParameterValue(0); - } - if (rateCGParameter != null) { - rr[3] = rateCGParameter.getParameterValue(0); - } - if (rateCTParameter != null) { - rr[4] = rateCTParameter.getParameterValue(0); - } - if (rateGTParameter != null) { - rr[5] = rateGTParameter.getParameterValue(0); - } - return rr; - } - - private Parameter rateACParameter = null; - private Parameter rateAGParameter = null; - private Parameter rateATParameter = null; - private Parameter rateCGParameter = null; - private Parameter rateCTParameter = null; - private Parameter rateGTParameter = null; -} diff --git a/src/dr/oldevomodel/substmodel/CovarionHKY.java b/src/dr/oldevomodel/substmodel/CovarionHKY.java deleted file mode 100644 index acfbf2c7ee..0000000000 --- a/src/dr/oldevomodel/substmodel/CovarionHKY.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * CovarionHKY.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.substmodel; - -import dr.evolution.datatype.OldHiddenNucleotides; -import dr.oldevomodelxml.substmodel.CovarionHKYParser; -import dr.inference.model.Parameter; - -/** - * A model with hidden states that represent different rates. - * - * @author Alexei Drummond - */ -public class CovarionHKY extends AbstractCovarionDNAModel { - - /** - * kappa - */ - private Parameter kappaParameter; - - /** - * @param dataType the datatype to be used - * @param kappaParameter the rate of transitions versus transversions - * @param hiddenClassRates the relative rates of the hidden categories - * (first hidden category has rate 1.0 so this parameter - * has dimension one less than number of hidden categories. - * each hidden category. - * @param switchingRates rate of switching between hidden categories - * @param freqModel the frequencies - */ - public CovarionHKY(OldHiddenNucleotides dataType, Parameter kappaParameter, Parameter hiddenClassRates, Parameter switchingRates, FrequencyModel freqModel) { - - super(CovarionHKYParser.COVARION_HKY, dataType, hiddenClassRates, switchingRates, freqModel); - - this.kappaParameter = kappaParameter; - addVariable(kappaParameter); - setupRelativeRates(); - } - - double[] getRelativeDNARates() { - double kappa = kappaParameter.getParameterValue(0); - return new double[]{1.0, kappa, 1.0, 1.0, kappa, 1.0}; - } - - /** - * set kappa - * - * @param kappa the new value of kappa to set - */ - public void setKappa(double kappa) { - kappaParameter.setParameterValue(0, kappa); - } - - /** - * @return kappa - */ - public double getKappa() { - return kappaParameter.getParameterValue(0); - } - - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("Covarion HKY model with "); - builder.append(getHiddenClassCount()).append(" rate classes.\n"); - builder.append("Relative rates: \n"); - builder.append(SubstitutionModelUtils.toString(relativeRates, dataType, true, 2)); - return builder.toString(); - - } - -} \ No newline at end of file diff --git a/src/dr/oldevomodel/substmodel/Dayhoff.java b/src/dr/oldevomodel/substmodel/Dayhoff.java deleted file mode 100644 index 85c17f1173..0000000000 --- a/src/dr/oldevomodel/substmodel/Dayhoff.java +++ /dev/null @@ -1,223 +0,0 @@ -/* - * Dayhoff.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.substmodel; - -import dr.evolution.datatype.AminoAcids; -import dr.util.Author; -import dr.util.Citation; - -import java.util.*; - -/** - * Dayhoff model for amino acid evolution - * Dayhoff, M.O., Schwartz, R.M., Orcutt, B.C. (1978) - * A model of evolutionary change in proteins. - * Dayhoff, M.O. (ed.) Atlas of Protein Sequence Structur., Vol5, Suppl. 3, - * National Biomedical Research Foundation, Washington DC, pp. 345-352. - * - * - * @author Andrew Rambaut - * @author Alexei Drummond - */ -public class Dayhoff extends EmpiricalRateMatrix.AbstractAminoAcid { - - public static final Dayhoff INSTANCE = new Dayhoff(); - - // The rates below are specified assuming that the amino acids are in this order: - // ARNDCQEGHILKMFPSTWYV - // but the AminoAcids dataType wants them in this order: - // ACDEFGHIKLMNPQRSTVWY - // This is solved by calling the setEmpiricalRates and setEmpiricalFrequencies methods - private Dayhoff() { super("dayhoff"); - - int n = AminoAcids.INSTANCE.getStateCount(); - - double[][] rate = new double[n][n]; - - // Q matrix - rate[0][1]=9.6472567159749e-01; rate[0][2]=3.5927991886410e+00; - rate[0][3]=4.3200552414656e+00; rate[0][4]=1.3184584178499e+00; - rate[0][5]=3.2267534963169e+00; rate[0][6]=7.0141987829615e+00; - rate[0][7]=8.5773867857875e+00; rate[0][8]=8.1434196396611e-01; - rate[0][9]=2.3518447453539e+00; rate[0][10]=1.4735711728911e+00; - rate[0][11]=9.3940162271805e-01; rate[0][12]=2.5490196078431e+00; - rate[0][13]=6.5922920892495e-01; rate[0][14]=8.9189834148670e+00; - rate[0][15]=1.4540712836859e+01; rate[0][16]=1.3411904595370e+01; - rate[0][17]=3.8517964118027e-02; rate[0][18]=8.7897227856660e-01; - rate[0][19]=7.4036511156187e+00; - - rate[1][2]=1.1890243902439e+00; rate[1][3]=5.9525626545377e-02; - rate[1][4]=8.4778922655537e-01; rate[1][5]=8.8348561504191e+00; - rate[1][6]=5.5954088952654e-02; rate[1][7]=3.1434881434075e-01; - rate[1][8]=8.4753987678285e+00; rate[1][9]=2.2684090115941e+00; - rate[1][10]=5.5954088952654e-01; rate[1][11]=1.6681312769010e+01; - rate[1][12]=3.1707317073171e+00; rate[1][13]=4.8959827833572e-01; - rate[1][14]=3.6754156468900e+00; rate[1][15]=5.4755072760812e+00; - rate[1][16]=9.6472567159749e-01; rate[1][17]=7.5538020086083e+00; - rate[1][18]=2.7977044476327e-01; rate[1][19]=8.6083213773314e-01; - - rate[2][3]=3.2459324155194e+01; rate[2][4]=7.3852625416383e-02; - rate[2][5]=3.7732198142415e+00; rate[2][6]=5.3911764705882e+00; - rate[2][7]=5.0264375413087e+00; rate[2][8]=1.9061418685121e+01; - rate[2][9]=2.7901430842607e+00; rate[2][10]=1.2482698961938e+00; - rate[2][11]=1.1542279411765e+01; rate[2][12]=1.9117647058824e-01; - rate[2][13]=5.0183823529412e-01; rate[2][14]=1.5181660899654e+00; - rate[2][15]=1.7697478991597e+01; rate[2][16]=8.3557302231237e+00; - rate[2][17]=8.6029411764706e-01; rate[2][18]=3.4411764705882e+00; - rate[2][19]=5.7352941176471e-01; - - rate[3][4]=2.5534152404601e-02; rate[3][5]=4.8811013767209e+00; - rate[3][6]=4.0561952440551e+01; rate[3][7]=4.4423506911730e+00; - rate[3][8]=3.0865788117500e+00; rate[3][9]=8.5749078239692e-01; - rate[3][10]=2.5926985518518e-02; rate[3][11]=2.5930851063830e+00; - rate[3][12]=1.1667143483333e-01; rate[3][13]=1.2963492759259e-02; - rate[3][14]=4.7853935065891e-01; rate[3][15]=3.4167709637046e+00; - rate[3][16]=2.3984722282163e+00; rate[3][17]=3.2408731898147e-02; - rate[3][18]=8.1351689612015e-02; rate[3][19]=6.3829787234043e-01; - - rate[4][5]=2.1864264103535e-02; rate[4][6]=1.4770525083277e-02; - rate[4][7]=3.9055458751427e-01; rate[4][8]=1.0223340673168e+00; - rate[4][9]=1.5970515970516e+00; rate[4][10]=3.9098448749850e-02; - rate[4][11]=8.0776309049169e-03; rate[4][12]=1.4155086538140e-01; - rate[4][13]=8.6898395721925e-02; rate[4][14]=6.8155604487784e-01; - rate[4][15]=5.8097784568373e+00; rate[4][16]=5.9929928084086e-01; - rate[4][17]=3.4759358288770e-01; rate[4][18]=3.4759358288770e+00; - rate[4][19]=1.7647058823529e+00; - - rate[5][6]=2.5476780185759e+01; rate[5][7]=1.0174974779977e+00; - rate[5][8]=2.1573939173192e+01; rate[5][9]=6.5266504894988e-01; - rate[5][10]=2.6634492806410e+00; rate[5][11]=5.5466331269350e+00; - rate[5][12]=4.0247678018576e+00; rate[5][13]=1.8038017885416e-02; - rate[5][14]=5.5044618466582e+00; rate[5][15]=2.0267580716497e+00; - rate[5][16]=1.9256432155439e+00; rate[5][17]=9.6202762055552e-02; - rate[5][18]=1.0061919504644e-01; rate[5][19]=1.2538699690402e+00; - - rate[6][7]=2.8869795109055e+00; rate[6][8]=1.5519031141869e+00; - rate[6][9]=2.1701112877583e+00; rate[6][10]=4.0484429065744e-01; - rate[6][11]=2.9823529411765e+00; rate[6][12]=1.0705882352941e+00; - rate[6][13]=1.9801735189768e-02; rate[6][14]=1.7993079584775e+00; - rate[6][15]=2.8184873949580e+00; rate[6][16]=1.2261663286004e+00; - rate[6][17]=7.3114099162219e-02; rate[6][18]=7.6470588235294e-01; - rate[6][19]=1.3058823529412e+00; - - rate[7][8]=3.7906768788150e-01; rate[7][9]=2.3128004846840e-02; - rate[7][10]=2.5776602775942e-01; rate[7][11]=9.6662260409782e-01; - rate[7][12]=6.0145406477198e-01; rate[7][13]=5.4775280898876e-01; - rate[7][14]=1.2382877804129e+00; rate[7][15]=8.2853366065527e+00; - rate[7][16]=1.1110604644803e+00; rate[7][17]=1.2888301387971e-01; - rate[7][18]=1.7114723586662e-02; rate[7][19]=1.9233311302049e+00; - - rate[8][9]=2.7354343963341e-01; rate[8][10]=1.5876246692449e+00; - rate[8][11]=9.6993944636678e-01; rate[8][12]=1.2544085640577e-01; - rate[8][13]=1.6868512110727e+00; rate[8][14]=3.3075513942601e+00; - rate[8][15]=1.2530894710826e+00; rate[8][16]=8.1434196396611e-01; - rate[8][17]=1.0121107266436e+00; rate[8][18]=4.4982698961938e+00; - rate[8][19]=1.5570934256055e+00; - - rate[9][10]=9.2275320303002e+00; rate[9][11]=1.6663354531002e+00; - rate[9][12]=1.1780604133545e+01; rate[9][13]=6.9753577106518e+00; - rate[9][14]=4.2551201720752e-01; rate[9][15]=8.8575970928912e-01; - rate[9][16]=6.8951811852420e+00; rate[9][17]=9.8802836705702e-02; - rate[9][18]=1.3434022257552e+00; rate[9][19]=3.1526232114467e+01; - - rate[10][11]=6.5787197231834e-01; rate[10][12]=1.8622837370242e+01; - rate[10][13]=5.6340830449827e+00; rate[10][14]=1.1377976796255e+00; - rate[10][15]=6.1690558576372e-01; rate[10][16]=1.2098794893211e+00; - rate[10][17]=1.7543252595156e+00; rate[10][18]=1.0346020761246e+00; - rate[10][19]=6.2906574394464e+00; - - rate[11][12]=8.6029411764706e+00; rate[11][13]=6.6640454965565e-03; - rate[11][14]=1.2089100346021e+00; rate[11][15]=3.4411764705882e+00; - rate[11][16]=4.9442190669371e+00; rate[11][17]=3.4272233982290e-02; - rate[11][18]=4.7794117647059e-01; rate[11][19]=3.7500000000000e-01; - - rate[12][13]=3.2500000000000e+00; rate[12][14]=5.9976931949250e-01; - rate[12][15]=2.1848739495798e+00; rate[12][16]=3.6916835699797e+00; - rate[12][17]=1.6247577591604e-01; rate[12][18]=1.1508700794053e-01; - rate[12][19]=9.0588235294118e+00; - - rate[13][14]=3.9359861591695e-01; rate[13][15]=1.6386554621849e+00; - rate[13][16]=4.9442190669371e-01; rate[13][17]=2.8676470588235e+00; - rate[13][18]=2.4852941176471e+01; rate[13][19]=4.4117647058824e-01; - - rate[14][15]=8.6431043005437e+00; rate[14][16]=2.8308077795013e+00; - rate[14][17]=3.5840244687362e-02; rate[14][18]=4.3804743506776e-02; - rate[14][19]=1.7301038062284e+00; - - rate[15][16]=1.9663865546218e+01; rate[15][17]=2.7857142857143e+00; - rate[15][18]=1.2016806722689e+00; rate[15][19]=1.0840336134454e+00; - - rate[16][17]=4.2019597219666e-02; rate[16][18]=1.5162271805274e+00; - rate[16][19]=5.6592292089249e+00; - - rate[17][18]=2.2941176470588e+00; rate[17][19]=1.2654363316538e-01; - - rate[18][19]=1.0000000000000e+00; - - setEmpiricalRates(rate, "ARNDCQEGHILKMFPSTWYV"); - - double[] f = new double[n]; - f[0] = 0.087; f[1] = 0.041; f[2] = 0.040; f[3] = 0.047; - f[4] = 0.033; f[5] = 0.038; f[6] = 0.05; f[7] = 0.089; - f[8] = 0.034; f[9] = 0.037; f[10] = 0.085; f[11] = 0.08; - f[12] = 0.015; f[13] = 0.04; f[14] = 0.051; f[15] = 0.07; - f[16] = 0.058; f[17] = 0.01; f[18] = 0.03; f[19] = 0.065; - - setEmpiricalFrequencies(f, "ARNDCQEGHILKMFPSTWYV"); - } - - @Override - public Citation.Category getCategory() { - return Citation.Category.SUBSTITUTION_MODELS; - } - - @Override - public String getDescription() { - return "Dayhoff amino acid substitution model"; - } - - @Override - public List getCitations() { - return Collections.singletonList(CITATION); - } - - public static Citation CITATION = new Citation( - new Author[]{ - new Author("MO", "Dayhoff"), - new Author("RM", "Schwartz"), - new Author("BC", "Orcutt") - }, - "A model of evolutionary change in proteins", - 1972, - "in Dayhoff, M.O. (ed.) Atlas of Protein Sequence Structur., Vol 5, Suppl. 3", - 5, - 345, 352, - Citation.Status.PUBLISHED - ); - -} diff --git a/src/dr/oldevomodel/substmodel/EmpiricalAminoAcidModel.java b/src/dr/oldevomodel/substmodel/EmpiricalAminoAcidModel.java deleted file mode 100644 index 27fd4d2468..0000000000 --- a/src/dr/oldevomodel/substmodel/EmpiricalAminoAcidModel.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * EmpiricalAminoAcidModel.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.substmodel; - -import dr.evolution.datatype.AminoAcids; -import dr.inference.model.Parameter; - -/** - * A general model of sequence substitution. A general reversible class for any - * data type. - * - * @author Andrew Rambaut - * @author Alexei Drummond - */ -public class EmpiricalAminoAcidModel extends AbstractAminoAcidModel { - /** - * constructor - * - * @param rateMatrix EmpiricalRateMatrix - * @param freqModel the frequency model - */ - public EmpiricalAminoAcidModel(EmpiricalRateMatrix rateMatrix, FrequencyModel freqModel) { - - super(rateMatrix.getName(), freqModel); - - if (freqModel == null) { - areFrequenciesConstant = true; - - double[] freqs = rateMatrix.getEmpiricalFrequencies(); - this.freqModel = new FrequencyModel(AminoAcids.INSTANCE, new Parameter.Default(freqs)); - } - - this.rateMatrix = rateMatrix; - } - - protected void frequenciesChanged() { - // Nothing to precalculate - } - - protected void ratesChanged() { - // Nothing to precalculate - } - - protected void setupRelativeRates() { - double[] rates = rateMatrix.getEmpiricalRates(); - System.arraycopy(rates, 0, relativeRates, 0, relativeRates.length); - } - - // ***************************************************************** - // Interface Model - // ***************************************************************** - - - protected void storeState() { - } // nothing to do - - protected void restoreState() { - updateMatrix = !areFrequenciesConstant; - } - - protected void acceptState() { - } // nothing to do - - private EmpiricalRateMatrix rateMatrix; - private boolean areFrequenciesConstant = false; -} diff --git a/src/dr/oldevomodel/substmodel/EmpiricalCodonModel.java b/src/dr/oldevomodel/substmodel/EmpiricalCodonModel.java deleted file mode 100644 index c04ab7543c..0000000000 --- a/src/dr/oldevomodel/substmodel/EmpiricalCodonModel.java +++ /dev/null @@ -1,628 +0,0 @@ -/* - * EmpiricalCodonModel.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.substmodel; - -import dr.evolution.datatype.AminoAcids; -import dr.evolution.datatype.Codons; -import dr.evolution.datatype.Nucleotides; -import dr.oldevomodelxml.substmodel.EmpiricalCodonModelParser; -import dr.inference.model.Parameter; -import java.util.logging.Logger; - -/** - * Empirical model of codon evolution - * - * @author Stefan Zoller - */ -public class EmpiricalCodonModel extends AbstractCodonModel { - - protected byte[] rateMap; - - private Parameter omegaParameter; - private Parameter kappaParameter; // 2d (kappats and kappatv) or 9d - private Parameter multintParameter; - private EmpiricalCodonRateMatrix rateMat; - - private int modelType; - private final int ECM_OMEGA_2K = 2; - private final int ECM_OMEGA_9K = 3; - private final int ECM_OMEGA_NU = 4; - private final int ECM_OMEGA = 1; - - - /** - * constructor - * - * @param codonDataType Data type as Codons.UNIVERSAL - * @param omegaParam Parameter: Omega - * @param kappaParam Parameter: Kappa (multidimensional) - * @param mntParam Parameter: Multi-nt - * @param rMat Initial rate matrix and frequencies - * @param freqModel Frequency model - */ - public EmpiricalCodonModel(Codons codonDataType, - Parameter omegaParam, - Parameter kappaParam, - Parameter mntParam, - EmpiricalCodonRateMatrix rMat, - FrequencyModel freqModel) - { - super(EmpiricalCodonModelParser.EMPIRICAL_CODON_MODEL, codonDataType, freqModel); - - // setup parameters - this.omegaParameter = omegaParam; - addVariable(omegaParameter); - omegaParameter.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, 0.0, - omegaParameter.getDimension())); - - if(kappaParam != null) { - this.kappaParameter = kappaParam; - addVariable(kappaParameter); - kappaParameter.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, 0.0, - kappaParameter.getDimension())); - } - if(mntParam != null) { - this.multintParameter = mntParam; - addVariable(multintParameter); - multintParameter.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, 0.0, - multintParameter.getDimension())); - } - - this.rateMat = rMat; - - constructRateMap(); - - checkForModelType(); - } - - // decide which model to use: ECM_OMEGA_2K, ECM_OMEGA_9K, ECM_OMEGA_NU or ECM_OMEGA - private void checkForModelType() { - this.modelType = 0; - if(kappaParameter != null) { - if(kappaParameter.getDimension() == 2) { - this.modelType = ECM_OMEGA_2K; - Logger.getLogger("dr.evomodel").info("Using model ECM+omega+2k"); - } else { - this.modelType = ECM_OMEGA_9K; - Logger.getLogger("dr.evomodel").info("Using model ECM+omega+9k"); - } - } - if(multintParameter != null){ - this.modelType = ECM_OMEGA_NU; - Logger.getLogger("dr.evomodel").info("Using model ECM+omega+nu"); - } - if(kappaParameter == null && multintParameter == null) { - this.modelType = ECM_OMEGA; - Logger.getLogger("dr.evomodel").info("Using model ECM+omega"); - } - } - - - // setup substitution matrix depending on model type - public void setupRelativeRates() { - switch(modelType) { - case ECM_OMEGA: - setupRelativeRatesECMOmega(); - break; - case ECM_OMEGA_2K: - setupRelativeRatesECMOmega2k(); - break; - case ECM_OMEGA_9K: - setupRelativeRatesECMOmega9k(); - break; - case ECM_OMEGA_NU: - setupRelativeRatesECMOmegaNu(); - break; - } - } - - // actual setup routines for different models - private void setupRelativeRatesECMOmega() { - double[] initRateMatrix = rateMat.getRates(); - double omega = getOmega(); - for (int i = 0; i < rateCount; i++) { - switch (rateMap[i]) { - case 1: // 1ts, 0tv, syn - case 3: // 0ts, 1tv, syn - case 5: // 2ts, 0tv, syn - case 7: // 1ts, 1tv, syn - case 9: // 0ts, 2tv, syn - case 11: // 3ts, 0tv, syn - case 13: // 2ts, 1tv, syn - case 15: // 1ts, 2tv, syn - case 17: relativeRates[i] = initRateMatrix[i]; break; // 0ts, 3tv, syn - - case 2: // 1ts, 0tv, nonsyn - case 4: // 0ts, 1tv, nonsyn - case 6: // 2ts, 0tv, nonsyn - case 8: // 1ts, 1tv, nonsyn - case 10: // 0ts, 2tv, nonsyn - case 12: // 3ts, 0tv, nonsyn - case 14: // 2ts, 1tv, nonsyn - case 16: // 1ts, 2tv, nonsyn - case 18: relativeRates[i] = initRateMatrix[i] * omega; break; // 0ts, 3tv, nonsyn - } - } - } - - private void setupRelativeRatesECMOmega2k() { - double[] initRateMatrix = rateMat.getRates(); - double omega = getOmega(); - double kts = getKappaTs(); - double ktv = getKappaTv(); - for (int i = 0; i < rateCount; i++) { - switch (rateMap[i]) { - case 1: relativeRates[i] = initRateMatrix[i] * kts; break; // 1ts, 0tv, syn - case 2: relativeRates[i] = initRateMatrix[i] * kts * omega; break; // 1ts, 0tv, nonsyn - case 3: relativeRates[i] = initRateMatrix[i] * ktv; break; // 0ts, 1tv, syn - case 4: relativeRates[i] = initRateMatrix[i] * ktv * omega; break; // 0ts, 1tv, nonsyn - case 5: relativeRates[i] = initRateMatrix[i] * kts * kts; break; // 2ts, 0tv, syn - case 6: relativeRates[i] = initRateMatrix[i] * kts * kts * omega; break; // 2ts, 0tv, nonsyn - case 7: relativeRates[i] = initRateMatrix[i] * kts * ktv; break; // 1ts, 1tv, syn - case 8: relativeRates[i] = initRateMatrix[i] * kts * ktv * omega; break; // 1ts, 1tv, nonsyn - case 9: relativeRates[i] = initRateMatrix[i] * ktv * ktv; break; // 0ts, 2tv, syn - case 10: relativeRates[i] = initRateMatrix[i] * ktv * ktv * omega; break; // 0ts, 2tv, nonsyn - case 11: relativeRates[i] = initRateMatrix[i] * kts * kts * kts; break; // 3ts, 0tv, syn - case 12: relativeRates[i] = initRateMatrix[i] * kts * kts * kts * omega; break; // 3ts, 0tv, nonsyn - case 13: relativeRates[i] = initRateMatrix[i] * kts * kts * ktv; break; // 2ts, 1tv, syn - case 14: relativeRates[i] = initRateMatrix[i] * kts * kts * ktv * omega; break; // 2ts, 1tv, nonsyn - case 15: relativeRates[i] = initRateMatrix[i] * kts * ktv * ktv; break; // 1ts, 2tv, syn - case 16: relativeRates[i] = initRateMatrix[i] * kts * ktv * ktv * omega; break; // 1ts, 2tv, nonsyn - case 17: relativeRates[i] = initRateMatrix[i] * ktv * ktv * ktv; break; // 0ts, 3tv, syn - case 18: relativeRates[i] = initRateMatrix[i] * ktv * ktv * ktv * omega; break; // 0ts, 3tv, nonsyn - } - } - } - - private void setupRelativeRatesECMOmega9k() { - double[] initRateMatrix = rateMat.getRates(); - double omega = getOmega(); - double[] kappa = getKappa(); - for (int i = 0; i < rateCount; i++) { - switch (rateMap[i]) { - case 1: relativeRates[i] = initRateMatrix[i] * kappa[0]; break; // 1ts, 0tv, syn - case 2: relativeRates[i] = initRateMatrix[i] * kappa[0] * omega; break; // 1ts, 0tv, nonsyn - case 3: relativeRates[i] = initRateMatrix[i] * kappa[1]; break; // 0ts, 1tv, syn - case 4: relativeRates[i] = initRateMatrix[i] * kappa[1] * omega; break; // 0ts, 1tv, nonsyn - case 5: relativeRates[i] = initRateMatrix[i] * kappa[2]; break; // 2ts, 0tv, syn - case 6: relativeRates[i] = initRateMatrix[i] * kappa[2] * omega; break; // 2ts, 0tv, nonsyn - case 7: relativeRates[i] = initRateMatrix[i] * kappa[3]; break; // 1ts, 1tv, syn - case 8: relativeRates[i] = initRateMatrix[i] * kappa[3] * omega; break; // 1ts, 1tv, nonsyn - case 9: relativeRates[i] = initRateMatrix[i] * kappa[4]; break; // 0ts, 2tv, syn - case 10: relativeRates[i] = initRateMatrix[i] * kappa[4] * omega; break; // 0ts, 2tv, nonsyn - case 11: relativeRates[i] = initRateMatrix[i] * kappa[5]; break; // 3ts, 0tv, syn - case 12: relativeRates[i] = initRateMatrix[i] * kappa[5] * omega; break; // 3ts, 0tv, nonsyn - case 13: relativeRates[i] = initRateMatrix[i] * kappa[6]; break; // 2ts, 1tv, syn - case 14: relativeRates[i] = initRateMatrix[i] * kappa[6] * omega; break; // 2ts, 1tv, nonsyn - case 15: relativeRates[i] = initRateMatrix[i] * kappa[7]; break; // 1ts, 2tv, syn - case 16: relativeRates[i] = initRateMatrix[i] * kappa[7] * omega; break; // 1ts, 2tv, nonsyn - case 17: relativeRates[i] = initRateMatrix[i] * kappa[8]; break; // 0ts, 3tv, syn - case 18: relativeRates[i] = initRateMatrix[i] * kappa[8] * omega; break; // 0ts, 3tv, nonsyn - } - } - } - - private void setupRelativeRatesECMOmegaNu() { - double[] initRateMatrix = rateMat.getRates(); - double omega = getOmega(); - double mnt = getMultiNt(); - for (int i = 0; i < rateCount; i++) { - switch (rateMap[i]) { - case 1: // 1ts, 0tv, syn - case 3: relativeRates[i] = initRateMatrix[i]; break; // 0ts, 1tv, syn - case 2: // 1ts, 0tv, nonsyn - case 4: relativeRates[i] = initRateMatrix[i] * omega; break; // 0ts, 1tv, nonsyn - - case 5: // 2ts, 0tv, syn - case 7: // 1ts, 1tv, syn - case 9: // 0ts, 2tv, syn - case 11: // 3ts, 0tv, syn - case 13: // 2ts, 1tv, syn - case 15: // 1ts, 2tv, syn - case 17: relativeRates[i] = initRateMatrix[i] * mnt; break; // 0ts, 3tv, syn - - case 6: // 2ts, 0tv, nonsyn - case 8: // 1ts, 1tv, nonsyn - case 10: // 0ts, 2tv, nonsyn - case 12: // 3ts, 0tv, nonsyn - case 14: // 2ts, 1tv, nonsyn - case 16: // 1ts, 2tv, nonsyn - case 18: relativeRates[i] = initRateMatrix[i] * mnt * omega; break; // 0ts, 3tv, nonsyn - } - } - } - - protected void ratesChanged() { - } - - protected void frequenciesChanged() { - } - - // getter and setter for parameters - - public void setOmega(double omega) { - omegaParameter.setParameterValue(0, omega); - updateMatrix = true; - } - - public double getOmega() { return omegaParameter.getParameterValue(0); } - - - public void setKappa(double kts, double ktv) { - if(kappaParameter != null) { - kappaParameter.setParameterValue(0, kts); - kappaParameter.setParameterValue(1, ktv); - updateMatrix = true; - } - } - - public double getKappaTs() { - if(kappaParameter != null) { - return kappaParameter.getParameterValue(0); - } else { - return 0.0; - } - } - - public double getKappaTv() { - if(kappaParameter != null) { - return kappaParameter.getParameterValue(1); - } else { - return 0.0; - } - } - - public double[] getKappa() { - if(kappaParameter != null) { - return kappaParameter.getParameterValues(); - } else { - return new double[9]; - } - } - - - public void setMultiNt(double mnt) { - if(multintParameter != null) { - multintParameter.setParameterValue(0, mnt); - updateMatrix = true; - } - } - - public double getMultiNt() { - if(multintParameter != null) { - return multintParameter.getParameterValue(0); - } else { - return 0.0; - } - } - - - /** - * Construct a map of the rate classes in the rate matrix using the current - * genetic code. Classes are: - * 1-2: 1ts, 0tv (syn/nonsyn) - * 3-4: 0ts, 1tv - * 5-6: 2ts, 0tv - * 7-8: 1ts, 1tv - * 9-10: 0ts, 2tv - * 11-12: 3ts, 0tv - * 13-14: 2ts, 1tv - * 15-16: 1ts, 2tv - * 17-18: 0ts, 3tv - */ - protected void constructRateMap() - { - int u, v, i1, j1, k1, i2, j2, k2, ts, tv, non; - byte rateClass; - int[] codon; - int cs1, cs2, aa1, aa2; - - int i = 0; - - rateMap = new byte[rateCount]; - - for (u = 0; u < stateCount; u++) { - - codon = codonDataType.getTripletStates(u); - i1 = codon[0]; - j1 = codon[1]; - k1 = codon[2]; - - cs1 = codonDataType.getState(i1, j1, k1); - aa1 = geneticCode.getAminoAcidState(codonDataType.getCanonicalState(cs1)); - - for (v = u + 1; v < stateCount; v++) { - - ts = 0; - tv = 0; - non = 0; - rateClass = -1; - - codon = codonDataType.getTripletStates(v); - i2 = codon[0]; - j2 = codon[1]; - k2 = codon[2]; - - cs2 = codonDataType.getState(i2, j2, k2); - aa2 = geneticCode.getAminoAcidState(codonDataType.getCanonicalState(cs2)); - - if (i1 != i2) { - if ( (i1 == 0 && i2 == 2) || (i1 == 2 && i2 == 0) || // A <-> G - (i1 == 1 && i2 == 3) || (i1 == 3 && i2 == 1) ) { // C <-> T - ts++; // Transition at position 1 - } else { - tv++; // Transversion at position 1 - } - } - if (j1 != j2) { - if ( (j1 == 0 && j2 == 2) || (j1 == 2 && j2 == 0) || // A <-> G - (j1 == 1 && j2 == 3) || (j1 == 3 && j2 == 1) ) { // C <-> T - ts++; // Transition - } else { - tv++; // Transversion - } - } - if (k1 != k2) { - if ( (k1 == 0 && k2 == 2) || (k1 == 2 && k2 == 0) || // A <-> G - (k1 == 1 && k2 == 3) || (k1 == 3 && k2 == 1) ) { // C <-> T - ts++; // Transition - } else { - tv++; // Transversion - } - } - - if (aa1 != aa2) { - non = 1; // Is a non-synonymous change - } - - // decide for rateClass - switch(ts) { - case 0: - switch(tv) { - case 1: rateClass = 3; break; // 0ts, 1tv - case 2: rateClass = 9; break; // 0ts, 2tv - case 3: rateClass = 17; break; // 0ts, 3tv - default: break; - } - break; - case 1: - switch(tv) { - case 0: rateClass = 1; break; // 1ts, 0tv - case 1: rateClass = 7; break; // 1ts, 1tv - case 2: rateClass = 15; break; // 1ts, 2tv - default: break; - } - break; - case 2: - switch(tv) { - case 0: rateClass = 5; break; // 2ts, 0tv - case 1: rateClass = 13; break; // 2ts, 1tv - default: break; - } - break; - case 3: - rateClass = 11; break; // 3ts, 0tv - default: break; - } - - if(non == 1) { - rateClass += 1; - } - rateMap[i] = rateClass; - i++; - } - - } - } - - public void printRateMap() - { - int u, v, i1, j1, k1, i2, j2, k2, ts, tv, non; - byte rateClass; - int[] codon; - int cs1, cs2, aa1, aa2; - - System.out.print("\t"); - for (v = 0; v < stateCount; v++) { - codon = codonDataType.getTripletStates(v); - i2 = codon[0]; - j2 = codon[1]; - k2 = codon[2]; - - System.out.print("\t" + Nucleotides.INSTANCE.getChar(i2)); - System.out.print(Nucleotides.INSTANCE.getChar(j2)); - System.out.print(Nucleotides.INSTANCE.getChar(k2)); - } - System.out.println(); - - System.out.print("\t"); - for (v = 0; v < stateCount; v++) { - codon = codonDataType.getTripletStates(v); - i2 = codon[0]; - j2 = codon[1]; - k2 = codon[2]; - - cs2 = codonDataType.getState(i2, j2, k2); - aa2 = geneticCode.getAminoAcidState(codonDataType.getCanonicalState(cs2)); - System.out.print("\t" + AminoAcids.INSTANCE.getChar(aa2)); - } - System.out.println(); - - for (u = 0; u < stateCount; u++) { - - codon = codonDataType.getTripletStates(u); - i1 = codon[0]; - j1 = codon[1]; - k1 = codon[2]; - - System.out.print(Nucleotides.INSTANCE.getChar(i1)); - System.out.print(Nucleotides.INSTANCE.getChar(j1)); - System.out.print(Nucleotides.INSTANCE.getChar(k1)); - - cs1 = codonDataType.getState(i1, j1, k1); - aa1 = geneticCode.getAminoAcidState(codonDataType.getCanonicalState(cs1)); - - System.out.print("\t" + AminoAcids.INSTANCE.getChar(aa1)); - - for (v = 0; v < stateCount; v++) { - - ts = 0; - tv = 0; - non = 0; - rateClass = -1; - - codon = codonDataType.getTripletStates(v); - i2 = codon[0]; - j2 = codon[1]; - k2 = codon[2]; - - cs2 = codonDataType.getState(i2, j2, k2); - aa2 = geneticCode.getAminoAcidState(codonDataType.getCanonicalState(cs2)); - - if (i1 != i2) { - if ( (i1 == 0 && i2 == 2) || (i1 == 2 && i2 == 0) || // A <-> G - (i1 == 1 && i2 == 3) || (i1 == 3 && i2 == 1) ) { // C <-> T - ts += 1; // Transition at position 1 - } else { - tv += 1; // Transversion at position 1 - } - } - if (j1 != j2) { - if ( (j1 == 0 && j2 == 2) || (j1 == 2 && j2 == 0) || // A <-> G - (j1 == 1 && j2 == 3) || (j1 == 3 && j2 == 1) ) { // C <-> T - ts += 1; // Transition - } else { - tv += 1; // Transversion - } - } - if (k1 != k2) { - if ( (k1 == 0 && k2 == 2) || (k1 == 2 && k2 == 0) || // A <-> G - (k1 == 1 && k2 == 3) || (k1 == 3 && k2 == 1) ) { // C <-> T - ts += 1; // Transition - } else { - tv += 1; // Transversion - } - } - - if (aa1 != aa2) { - non = 1; // Is a non-synonymous change - } - - // decide for rateClass - switch(ts) { - case 0: - switch(tv) { - case 1: rateClass = 3; break; // 0ts, 1tv - case 2: rateClass = 9; break; // 0ts, 2tv - case 3: rateClass = 17; break; // 0ts, 3tv - default: break; - } - break; - case 1: - switch(tv) { - case 0: rateClass = 1; break; // 1ts, 0tv - case 1: rateClass = 7; break; // 1ts, 1tv - case 2: rateClass = 15; break; // 1ts, 2tv - default: break; - } - break; - case 2: - switch(tv) { - case 0: rateClass = 5; break; // 2ts, 0tv - case 1: rateClass = 13; break; // 2ts, 1tv - default: break; - } - break; - case 3: - rateClass = 11; break; // 3ts, 0tv - default: break; - } - - if(non == 1) { - rateClass += 1; - } - - System.out.print("\t" + rateClass); - - } - System.out.println(); - - } - } - - // ************************************************************** - // XHTMLable IMPLEMENTATION - // ************************************************************** - - public String toXHTML() { - StringBuffer buffer = new StringBuffer(); - - buffer.append("Empirical Codon Model omega = "); - buffer.append(getOmega()); - buffer.append(", kappa_ts = "); - buffer.append(getKappaTs()); - buffer.append(", kappa_tv = "); - buffer.append(getKappaTv()); - buffer.append(", multi_nt = "); - buffer.append(getMultiNt()); - buffer.append(", initial matrix = " + rateMat.getDirName() + "/" + rateMat.getMatName()); - buffer.append(", initial freqs = " + rateMat.getDirName() + "/" + rateMat.getFreqName()); - return buffer.toString(); - } - - - static String format1 = "%2.1e"; - static String format2 = "%2.4e"; - - public String printQ() { - double[][] myQ = getQ(); - if (myQ != null) { - StringBuffer sb = new StringBuffer(); - for (int i = 0; i < myQ.length; i++) { - for(int j = 0; j < myQ[0].length; j++) { - sb.append(String.format(format1, myQ[i][j])); - sb.append("\t"); - } - sb.append("\n"); - } - return sb.toString(); - } else { - return "No Q ready."; - } - } - - public String printRelRates() { - StringBuffer sb = new StringBuffer(); - for (int i = 0; i < relativeRates.length; i++) { - sb.append(String.format(format2, relativeRates[i])); - sb.append("\t"); - } - sb.append("\n"); - return sb.toString(); - } -} diff --git a/src/dr/oldevomodel/substmodel/EmpiricalCodonRateMatrix.java b/src/dr/oldevomodel/substmodel/EmpiricalCodonRateMatrix.java deleted file mode 100644 index 43ee922c6e..0000000000 --- a/src/dr/oldevomodel/substmodel/EmpiricalCodonRateMatrix.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * EmpiricalCodonRateMatrix.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.substmodel; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.IOException; -import java.util.StringTokenizer; -import java.util.logging.Logger; - -import dr.evolution.datatype.DataType; - -/** - * Empirical rate matrix - * - * @author Stefan Zoller - * - */ -public class EmpiricalCodonRateMatrix { - - /** - * constructor - * - * @param name Name of matrix - * @param dataType Data type as Codons.UNIVERSAL - * @param dir Directory that contains csv files with matrices - * @param fName Name of frequency csv file - * @param mName Name of initial matrix csv file - */ - public EmpiricalCodonRateMatrix(String name, DataType dataType, String dir, String fName, String mName) { - this.name = name; - this.dataType = dataType; - this.dataDir = dir; - this.matName = mName; - this.freqName = fName; - - setupRates(); - setupFreqs(); - } - - public final String getName() { return name; } - public final DataType getDataType() { return dataType; } - - public double[] getRates() { return rates; } - public double[] getFrequencies() { return frequencies; } - - public String getFreqName() { return freqName; } - public String getMatName() { return matName; } - public String getDirName() { return dataDir; } - - public void setFrequencies(double[] f) { - this.frequencies = f; - } - - public void setRates(double[] p) { - this.rates = p; - } - - private void setupRates() { - this.rates = new double[1830]; - readFile(this.rates, matName, 1830); - } - - private void setupFreqs() { - this.frequencies = new double[61]; - readFile(this.frequencies, freqName, 61); - } - - // read csv data - private void readFile(double[] r, String f, int nr) { - File file = new File(dataDir, f); - - try { - BufferedReader bufRdr = new BufferedReader(new FileReader(file)); - String line = null; - int col = 0; - - while((line = bufRdr.readLine()) != null) { - StringTokenizer st = new StringTokenizer(line,","); - while (st.hasMoreTokens()) { - r[col] = Double.valueOf(st.nextToken()).doubleValue(); - col++; - } - } - bufRdr.close(); - if(col != nr) { - Logger.getLogger("dr.evomodel").severe("Matrix does not contain " + nr + " values but " + col); - } - } catch (FileNotFoundException e) { - Logger.getLogger("dr.evomodel").severe("Caught FileNotFoundException: " + e.getMessage()); - } catch (IOException e) { - Logger.getLogger("dr.evomodel").severe("Caught IOException: " + e.getMessage()); - } finally { - } - } - - protected double[] rates; - protected double[] frequencies; - - private String name; - protected String dataDir; - protected String matName; - protected String freqName; - protected DataType dataType; -} diff --git a/src/dr/oldevomodel/substmodel/EmpiricalRateMatrix.java b/src/dr/oldevomodel/substmodel/EmpiricalRateMatrix.java deleted file mode 100644 index a34bcd403c..0000000000 --- a/src/dr/oldevomodel/substmodel/EmpiricalRateMatrix.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * EmpiricalRateMatrix.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.substmodel; - -import dr.evolution.datatype.AminoAcids; -import dr.evolution.datatype.DataType; -import dr.util.Citable; - -/** - * An interface for empirical rate matrices. - * - * - * @author Andrew Rambaut - * @author Alexei Drummond - */ -public interface EmpiricalRateMatrix extends Citable { - - String getName(); - DataType getDataType(); - - double[] getEmpiricalRates(); - double[] getEmpiricalFrequencies(); - - public abstract class Abstract implements EmpiricalRateMatrix { - - public Abstract(String name, DataType dataType) { - this.name = name; - this.dataType = dataType; - } - - public final String getName() { return name; } - - public final DataType getDataType() { return dataType; } - - public final double[] getEmpiricalRates() { return rates; } - public final double[] getEmpiricalFrequencies() { return frequencies; } - - protected double[] rates = null; - protected double[] frequencies = null; - - private String name; - protected DataType dataType; - } - - public abstract class AbstractAminoAcid extends Abstract { - - public AbstractAminoAcid(String name) { - super(name, AminoAcids.INSTANCE); - - int n = dataType.getStateCount(); - rates = new double[(n * (n - 1)) / 2]; - frequencies = new double[n]; - } - - public final void setEmpiricalRates(double[][]matrix, String aminoAcidOrder) { - int k = 0; - - for (int i = 0; i < dataType.getStateCount(); i++) { - - int u = aminoAcidOrder.indexOf(dataType.getChar(i)); - - for (int j = i + 1; j < dataType.getStateCount(); j++) { - - int v = aminoAcidOrder.indexOf(dataType.getChar(j)); - - if (u < v) { - rates[k] = matrix[u][v]; - } else { - rates[k] = matrix[v][u]; - } - - k++; - } - } - } - - public final void setEmpiricalFrequencies(double[]freqs, String aminoAcidOrder) { - - double sum = 0.0; - for (int i = 0; i < dataType.getStateCount(); i++) { - int u = aminoAcidOrder.indexOf(dataType.getChar(i)); - frequencies[i] = freqs[u]; - sum += frequencies[i]; - } - - // normalize - we should probably detect large discrepancies but the empirical - // matrices have numerical rounding that cause small discrepancies. - for (int i = 0; i < dataType.getStateCount(); i++) { - frequencies[i] /= sum; - } - } - } -} \ No newline at end of file diff --git a/src/dr/oldevomodel/substmodel/FLU.java b/src/dr/oldevomodel/substmodel/FLU.java deleted file mode 100644 index ea9e8afac1..0000000000 --- a/src/dr/oldevomodel/substmodel/FLU.java +++ /dev/null @@ -1,225 +0,0 @@ -/* - * FLU.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.substmodel; - -import dr.evolution.datatype.AminoAcids; -import dr.util.Author; -import dr.util.Citation; - -import java.util.*; - -/** - * FLU model of amino acid evolution (add reference). - * - * Cuong Cao Dang, Quang Si Le, Olivier Gascuel and Vinh Sy Le (2010) - * FLU, an amino acid substitution model for influenza proteins. BMC Evol Biol 10:99 - * - * - * @author Marc A. Suchard - * @author Yu-Nong Gong - */ - -public class FLU extends EmpiricalRateMatrix.AbstractAminoAcid { - - public static final FLU INSTANCE = new FLU(); - - // The rates below are specified assuming that the amino acids are in this order: - // ARNDCQEGHILKMFPSTWYV - // but the AminoAcids dataType wants them in this order: - // ACDEFGHIKLMNPQRSTVWY - // This is solved by calling the setEmpiricalRates and setEmpiricalFrequencies methods - - private FLU() { super("FLU"); - - int n = AminoAcids.INSTANCE.getStateCount(); - - double[][] rate = new double[n][n]; - - // Q matrix - rate[0][1] = 0.138659; rate[0][2] = 0.053367; - rate[0][3] = 0.584852; rate[0][4] = 0.026447; - rate[0][5] = 0.353754; rate[0][6] = 1.484235; - rate[0][7] = 1.132313; rate[0][8] = 0.214758; - rate[0][9] = 0.149927; rate[0][10] = 0.023117; - rate[0][11] = 0.474334; rate[0][12] = 0.058745; - rate[0][13] = 0.080491; rate[0][14] = 0.659311; - rate[0][15] = 3.011345; rate[0][16] = 5.418298; - rate[0][17] = 0.195966; rate[0][18] = 0.018289; - rate[0][19] = 3.532005; - rate[1][2] = 0.161001; rate[1][3] = 0.006772; - rate[1][4] = 0.167207; rate[1][5] = 3.292717; - rate[1][6] = 0.124898; rate[1][7] = 1.190624; - rate[1][8] = 1.879570; rate[1][9] = 0.246117; - rate[1][10] = 0.296046; rate[1][11] = 15.300097; - rate[1][12] = 0.890162; rate[1][13] = 0.016055; - rate[1][14] = 0.154027; rate[1][15] = 0.950138; - rate[1][16] = 0.183077; rate[1][17] = 1.369429; - rate[1][18] = 0.099855; rate[1][19] = 0.103964; - - rate[2][3] = 7.737393; rate[2][4] = 0.000013; - rate[2][5] = 0.530643; rate[2][6] = 0.061652; - rate[2][7] = 0.322525; rate[2][8] = 1.387096; - rate[2][9] = 0.218572; rate[2][10] = 0.000836; - rate[2][11] = 2.646848; rate[2][12] = 0.005252; - rate[2][13] = 0.000836; rate[2][14] = 0.036442; - rate[2][15] = 3.881311; rate[2][16] = 2.140332; - rate[2][17] = 0.000536; rate[2][18] = 0.373102; - rate[2][19] = 0.010258; - rate[3][4] = 0.014132; rate[3][5] = 0.145469; - rate[3][6] = 5.370511; rate[3][7] = 1.934833; - rate[3][8] = 0.887571; rate[3][9] = 0.014086; - rate[3][10] = 0.005731; rate[3][11] = 0.290043; - rate[3][12] = 0.041763; rate[3][13] = 0.000001; - rate[3][14] = 0.188539; rate[3][15] = 0.338372; - rate[3][16] = 0.135481; rate[3][17] = 0.000015; - rate[3][18] = 0.525399; rate[3][19] = 0.297124; - - rate[4][5] = 0.002547; rate[4][6] = 0.000000; - rate[4][7] = 0.116941; rate[4][8] = 0.021845; - rate[4][9] = 0.001112; rate[4][10] = 0.005614; - rate[4][11] = 0.000004; rate[4][12] = 0.111457; - rate[4][13] = 0.104054; rate[4][14] = 0.000000; - rate[4][15] = 0.336263; rate[4][16] = 0.011975; - rate[4][17] = 0.094107; rate[4][18] = 0.601692; - rate[4][19] = 0.054905; - rate[5][6] = 1.195629; rate[5][7] = 0.108051; - rate[5][8] = 5.330313; rate[5][9] = 0.028840; - rate[5][10] = 1.020367; rate[5][11] = 2.559587; - rate[5][12] = 0.190259; rate[5][13] = 0.032681; - rate[5][14] = 0.712770; rate[5][15] = 0.487822; - rate[5][16] = 0.602341; rate[5][17] = 0.044021; - rate[5][18] = 0.072206; rate[5][19] = 0.406698; - - rate[6][7] = 1.593099; rate[6][8] = 0.256492; - rate[6][9] = 0.014211; rate[6][10] = 0.016500; - rate[6][11] = 3.881489; rate[6][12] = 0.313974; - rate[6][13] = 0.001004; rate[6][14] = 0.319559; - rate[6][15] = 0.307140; rate[6][16] = 0.280125; - rate[6][17] = 0.155245; rate[6][18] = 0.104093; - rate[6][19] = 0.285048; - rate[7][8] = 0.058775; rate[7][9] = 0.000016; - rate[7][10] = 0.006516; rate[7][11] = 0.264149; - rate[7][12] = 0.001500; rate[7][13] = 0.001237; - rate[7][14] = 0.038632; rate[7][15] = 1.585647; - rate[7][16] = 0.018808; rate[7][17] = 0.196486; - rate[7][18] = 0.074815; rate[7][19] = 0.337230; - - rate[8][9] = 0.243190; rate[8][10] = 0.321612; - rate[8][11] = 0.347303; rate[8][12] = 0.001274; - rate[8][13] = 0.119029; rate[8][14] = 0.924467; - rate[8][15] = 0.580704; rate[8][16] = 0.368714; - rate[8][17] = 0.022373; rate[8][18] = 6.448954; - rate[8][19] = 0.098631; - rate[9][10] = 3.512072; rate[9][11] = 0.227708; - rate[9][12] = 9.017954; rate[9][13] = 1.463357; - rate[9][14] = 0.080543; rate[9][15] = 0.290381; - rate[9][16] = 2.904052; rate[9][17] = 0.032132; - rate[9][18] = 0.273934; rate[9][19] = 14.394052; - - rate[10][11] = 0.129224; rate[10][12] = 6.746936; - rate[10][13] = 2.986800; rate[10][14] = 0.634309; - rate[10][15] = 0.570767; rate[10][16] = 0.044926; - rate[10][17] = 0.431278; rate[10][18] = 0.340058; - rate[10][19] = 0.890599; - rate[11][12] = 1.331292; rate[11][13] = 0.319896; - rate[11][14] = 0.195751; rate[11][15] = 0.283808; - rate[11][16] = 1.526964; rate[11][17] = 0.000050; - rate[11][18] = 0.012416; rate[11][19] = 0.073128; - - rate[12][13] = 0.279911; rate[12][14] = 0.056869; - rate[12][15] = 0.007027; rate[12][16] = 2.031511; - rate[12][17] = 0.070460; rate[12][18] = 0.874272; - rate[12][19] = 4.904842; - rate[13][14] = 0.007132; rate[13][15] = 0.996686; - rate[13][16] = 0.000135; rate[13][17] = 0.814753; - rate[13][18] = 5.393924; rate[13][19] = 0.592588; - - rate[14][15] = 2.087385; rate[14][16] = 0.542251; - rate[14][17] = 0.000431; rate[14][18] = 0.000182; - rate[14][19] = 0.058972; - rate[15][16] = 2.206860; rate[15][17] = 0.099836; - rate[15][18] = 0.392552; rate[15][19] = 0.088256; - - rate[16][17] = 0.207066; rate[16][18] = 0.124898; - rate[16][19] = 0.654109; - rate[17][18] = 0.427755; rate[17][19] = 0.256900; - - rate[18][19] = 0.167582; - - setEmpiricalRates(rate, "ARNDCQEGHILKMFPSTWYV"); - - double[] f = new double[n]; - f[0] = 0.0470718; // A - f[1] = 0.0509102; // R - f[2] = 0.0742143; // N - f[3] = 0.0478596; // D - f[4] = 0.0250216; // C - f[5] = 0.0333036; // Q - f[6] = 0.0545874; // E - f[7] = 0.0763734; // G - f[8] = 0.0199642; // H - f[9] = 0.0671336; // I - f[10] = 0.0714981; // L - f[11] = 0.0567845; // K - f[12] = 0.0181507; // M - f[13] = 0.0304961; // F - f[14] = 0.0506561; // P - f[15] = 0.0884091; // S - f[16] = 0.0743386; // T - f[17] = 0.0185237; // W - f[18] = 0.0314741; // Y - f[19] = 0.0632292; // V - setEmpiricalFrequencies(f, "ARNDCQEGHILKMFPSTWYV"); - } - - @Override - public Citation.Category getCategory() { - return Citation.Category.SUBSTITUTION_MODELS; - } - - @Override - public String getDescription() { - return "FLU amino acid substitution model"; - } - - @Override - public List getCitations() { - return Collections.singletonList(CITATION); - } - - public static Citation CITATION = new Citation( - new Author[]{ - new Author("CC", "Dang"), - new Author("QS", "Le"), - new Author("O", "Gascuel"), - new Author("VS", "Le") - }, - "FLU, an amino acid substitution model for influenza proteins", - 2010, "BMC Evolutionary Biology", 10, 99, -1 - ); -} \ No newline at end of file diff --git a/src/dr/oldevomodel/substmodel/FrequencyModel.java b/src/dr/oldevomodel/substmodel/FrequencyModel.java deleted file mode 100644 index 876c464925..0000000000 --- a/src/dr/oldevomodel/substmodel/FrequencyModel.java +++ /dev/null @@ -1,149 +0,0 @@ -/* - * FrequencyModel.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.substmodel; - -import dr.evolution.datatype.DataType; -import dr.oldevomodelxml.substmodel.FrequencyModelParser; -import dr.inference.model.AbstractModel; -import dr.inference.model.Model; -import dr.inference.model.Parameter; -import dr.inference.model.Variable; -import org.w3c.dom.Document; -import org.w3c.dom.Element; - -/** - * A model of equlibrium frequencies - * - * @author Alexei Drummond - * @author Andrew Rambaut - * @author Marc Suchard - */ -public class FrequencyModel extends AbstractModel { - /** - * A constructor which allows a more programmatic approach with - * fixed frequencies. - * @param dataType DataType - * @param frequencyParameter double[] - */ - public FrequencyModel(DataType dataType, double[] frequencyParameter) { - this(dataType, new Parameter.Default(frequencyParameter)); - } - - public FrequencyModel(DataType dataType, Parameter frequencyParameter) { - - super(FrequencyModelParser.FREQUENCY_MODEL); - - double sum = getSumOfFrequencies(frequencyParameter); - - if (Math.abs(sum - 1.0) > 1e-8) { - throw new IllegalArgumentException("Frequencies do not sum to 1, they sum to " + sum); - } - - this.frequencyParameter = frequencyParameter; - addVariable(frequencyParameter); - frequencyParameter.addBounds(new Parameter.DefaultBounds(1.0, 0.0, frequencyParameter.getDimension())); - this.dataType = dataType; - } - - /** - * @param frequencies the frequencies - * @return return the sum of frequencies - */ - private double getSumOfFrequencies(Parameter frequencies) { - double total = 0.0; - for (int i = 0; i < frequencies.getDimension(); i++) { - total += frequencies.getParameterValue(i); - } - return total; - } - - public void setFrequency(int i, double value) { - frequencyParameter.setParameterValue(i, value); - } - - public double getFrequency(int i) { - return frequencyParameter.getParameterValue(i); - } - - public int getFrequencyCount() { - return frequencyParameter.getDimension(); - } - - public Parameter getFrequencyParameter() { - return frequencyParameter; - } - - public double[] getFrequencies() { - double[] frequencies = new double[getFrequencyCount()]; - for (int i = 0; i < frequencies.length; i++) { - frequencies[i] = getFrequency(i); - } - return frequencies; - } - - public double[] getCumulativeFrequencies() { - double[] frequencies = getFrequencies(); - for (int i = 1; i < frequencies.length; i++) { - frequencies[i] += frequencies[i - 1]; - } - return frequencies; - } - - public DataType getDataType() { - return dataType; - } - - // ***************************************************************** - // Interface Model - // ***************************************************************** - - protected void handleModelChangedEvent(Model model, Object object, int index) { - // no intermediates need recalculating.... - } - - protected void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) { - // no intermediates need recalculating.... - } - - protected void storeState() { - } // no state apart from parameters to store - - protected void restoreState() { - } // no state apart from parameters to restore - - protected void acceptState() { - } // no state apart from parameters to accept - - public Element createElement(Document doc) { - throw new RuntimeException("Not implemented!"); - } - - private DataType dataType = null; - Parameter frequencyParameter = null; - -} diff --git a/src/dr/oldevomodel/substmodel/GTR.java b/src/dr/oldevomodel/substmodel/GTR.java deleted file mode 100644 index 058b1b270c..0000000000 --- a/src/dr/oldevomodel/substmodel/GTR.java +++ /dev/null @@ -1,208 +0,0 @@ -/* - * GTR.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.substmodel; - -import dr.oldevomodelxml.substmodel.GTRParser; -import dr.inference.model.Parameter; -import dr.inference.model.Variable; -import dr.util.Author; -import dr.util.Citable; -import dr.util.Citation; - -import java.util.Collections; -import java.util.List; - -/** - * General Time Reversible model of nucleotide evolution - * This is really just a place-holder because all the implementation - * already exists in NucleotideModel and GeneralModel, its base classes. - * - * @author Andrew Rambaut - * @author Alexei Drummond - */ -public class GTR extends AbstractNucleotideModel implements Citable { - - private Variable rateACValue = null; - private Variable rateAGValue = null; - private Variable rateATValue = null; - private Variable rateCGValue = null; - private Variable rateCTValue = null; - private Variable rateGTValue = null; - - /** - * @param rateACValue rate of A<->C substitutions - * @param rateAGValue rate of A<->G substitutions - * @param rateATValue rate of A<->T substitutions - * @param rateCGValue rate of C<->G substitutions - * @param rateCTValue rate of C<->T substitutions - * @param rateGTValue rate of G<->T substitutions - * @param freqModel frequencies - */ - public GTR( - Variable rateACValue, - Variable rateAGValue, - Variable rateATValue, - Variable rateCGValue, - Variable rateCTValue, - Variable rateGTValue, - FrequencyModel freqModel) { - - super(GTRParser.GTR_MODEL, freqModel); - - if (rateACValue != null) { - addVariable(rateACValue); - rateACValue.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, 0.0, 1)); - this.rateACValue = rateACValue; - } - - if (rateAGValue != null) { - addVariable(rateAGValue); - rateAGValue.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, 0.0, 1)); - this.rateAGValue = rateAGValue; - } - - if (rateATValue != null) { - addVariable(rateATValue); - rateATValue.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, 0.0, 1)); - this.rateATValue = rateATValue; - } - - if (rateCGValue != null) { - addVariable(rateCGValue); - rateCGValue.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, 0.0, 1)); - this.rateCGValue = rateCGValue; - } - - if (rateCTValue != null) { - addVariable(rateCTValue); - rateCTValue.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, 0.0, 1)); - this.rateCTValue = rateCTValue; - } - - if (rateGTValue != null) { - addVariable(rateGTValue); - rateGTValue.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, 0.0, 1)); - this.rateGTValue = rateGTValue; - } - - } - - public void setAbsoluteRates(double[] rates, int relativeTo) { - for (int i = 0; i < relativeRates.length; i++) { - relativeRates[i] = rates[i] / rates[relativeTo]; - } - updateMatrix = true; - fireModelChanged(); - } - - public void setRelativeRates(double[] rates) { - System.arraycopy(rates, 0, relativeRates, 0, relativeRates.length); - updateMatrix = true; - fireModelChanged(); - } - - protected void setupRelativeRates() { - - if (rateACValue != null) { - relativeRates[0] = rateACValue.getValue(0); - } - if (rateAGValue != null) { - relativeRates[1] = rateAGValue.getValue(0); - } - if (rateATValue != null) { - relativeRates[2] = rateATValue.getValue(0); - } - if (rateCGValue != null) { - relativeRates[3] = rateCGValue.getValue(0); - } - if (rateCTValue != null) { - relativeRates[4] = rateCTValue.getValue(0); - } - if (rateGTValue != null) { - relativeRates[5] = rateGTValue.getValue(0); - } - } - - // ************************************************************** - // XHTMLable IMPLEMENTATION - // ************************************************************** - - public String toXHTML() { - StringBuffer buffer = new StringBuffer(); - - buffer.append("GTR Model Instantaneous Rate Matrix = "); - buffer.append(""); - - buffer.append(""); - - buffer.append(""); - - buffer.append("
ACGT
A"); - buffer.append(relativeRates[0]); - buffer.append(""); - buffer.append(relativeRates[1]); - buffer.append(""); - buffer.append(relativeRates[2]); - buffer.append("
C"); - buffer.append(relativeRates[3]); - buffer.append(""); - buffer.append(relativeRates[4]); - buffer.append("
G"); - buffer.append(relativeRates[5]); - buffer.append("
G
"); - - return buffer.toString(); - } - - @Override - public Citation.Category getCategory() { - return Citation.Category.SUBSTITUTION_MODELS; - } - - @Override - public String getDescription() { - return "GTR nucleotide substitution model"; - } - - @Override - public List getCitations() { - return Collections.singletonList(CITATION); - } - - - public static Citation CITATION = new Citation( - new Author[]{ - new Author("S", "Tavaré") - }, - "Some probabilistic and statistical problems in the analysis of DNA sequences", - 1985, - "In: Miura R. M., editor. Lectures on mathematics in the life sciences.", - 17, 57, 86 - ); - -} diff --git a/src/dr/oldevomodel/substmodel/GeneralF81Model.java b/src/dr/oldevomodel/substmodel/GeneralF81Model.java deleted file mode 100644 index 4a3549687d..0000000000 --- a/src/dr/oldevomodel/substmodel/GeneralF81Model.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * GeneralF81Model.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.substmodel; - -import dr.evolution.datatype.GeneralDataType; - -/** - * @author Alexei Drummond - */ -public class GeneralF81Model extends AbstractSubstitutionModel { - - /** - * @param freqModel - */ - public GeneralF81Model(FrequencyModel freqModel) { - super("generalF81", freqModel.getDataType(), freqModel); - setupMatrix(); - } - - protected void frequenciesChanged() { - // frequencyModel changed - } - - @Override - protected void ratesChanged() { - //To change body of implemented methods use File | Settings | File Templates. - } - - /** - * get the complete transition probability matrix for the given distance - * - * @param distance the expected number of substitutions - * @param matrix an array to store the matrix - */ - public void getTransitionProbabilities(double distance, double[] matrix) { - - int stateSize = freqModel.getFrequencyCount(); - - double[] pi = freqModel.getFrequencies(); - - double beta = 1; - for (double p : pi) { - beta -= p * p; - } - beta = 1.0 / beta; - - int c = 0; - for (int i = 0; i < stateSize; i++) { - for (int j = 0; j < stateSize; j++) { - - if (i == j) { - matrix[c] = pi[i] + (1 - pi[i]) * Math.exp(-beta * distance); - } else { - matrix[c] = pi[j] * (1 - Math.exp(-beta * distance)); - } - c += 1; - } - } - } - - protected void setupRelativeRates() { - } - - // ***************************************************************** - // Interface Model - // ***************************************************************** - - public void storeState() { - super.storeState(); - } - - /** - * Restore the stored state - */ - public void restoreState() { - super.restoreState(); - } - - // ************************************************************** - // XHTMLable IMPLEMENTATION - // ************************************************************** - - public String toXHTML() { - StringBuffer buffer = new StringBuffer(); - - buffer.append("General F81 Model"); - - return buffer.toString(); - } - - public static void main(String[] args) { - - GeneralDataType general = new GeneralDataType(new String[]{"0", "1", "2"}); - - FrequencyModel freqModel = new FrequencyModel(general, new double[]{0.2, 0.3, 0.5}); - - GeneralF81Model f81 = new GeneralF81Model(freqModel); - - int S = general.getStateCount(); - - double[] P = new double[S * S]; - - f81.getTransitionProbabilities(0.01, P); - - int c = 0; - for (int i = 0; i < S; i++) { - System.out.print(P[c]); - double rowSum = P[c]; - c += 1; - for (int j = 1; j < S; j++) { - System.out.print(", " + P[c]); - rowSum += P[c]; - c += 1; - } - System.out.println(" : " + rowSum); - } - - } -} - diff --git a/src/dr/oldevomodel/substmodel/GeneralSubstitutionModel.java b/src/dr/oldevomodel/substmodel/GeneralSubstitutionModel.java deleted file mode 100644 index 4f2483d22d..0000000000 --- a/src/dr/oldevomodel/substmodel/GeneralSubstitutionModel.java +++ /dev/null @@ -1,155 +0,0 @@ -/* - * GeneralSubstitutionModel.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.substmodel; - -import dr.evolution.datatype.DataType; -import dr.oldevomodelxml.substmodel.GeneralSubstitutionModelParser; -import dr.inference.model.DuplicatedParameter; -import dr.inference.model.Parameter; - -/** - * A general model of sequence substitution. A general reversible class for any - * data type. - * - * @author Andrew Rambaut - * @author Alexei Drummond - */ -public class GeneralSubstitutionModel extends AbstractSubstitutionModel implements dr.util.XHTMLable { - - /** - * the rate which the others are set relative to - */ - protected int ratesRelativeTo; - - /** - * constructor - * - * @param dataType the data type - * @param freqModel the equilibrium frequency model - this must match the data type - * @param parameter the rates parameter, minus the rate that they are specified relative to - * @param relativeTo the index of the rate that all other are specified relative to - */ - public GeneralSubstitutionModel( - DataType dataType, - FrequencyModel freqModel, - Parameter parameter, - int relativeTo) { - - super(GeneralSubstitutionModelParser.GENERAL_SUBSTITUTION_MODEL, dataType, freqModel); - - ratesParameter = parameter; - if (ratesParameter != null) { - addVariable(ratesParameter); - if (!(ratesParameter instanceof DuplicatedParameter)) - ratesParameter.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, 0.0, ratesParameter.getDimension())); - } - setRatesRelativeTo(relativeTo); - } - - /** - * constructor - * - * @param name a name to give the substitution model - * @param dataType the data type - * @param freqModel the equilibrium frequency model - this must match the data type - * @param relativeTo the index of the rate that all other are specified relative to - */ - protected GeneralSubstitutionModel( - String name, - DataType dataType, - FrequencyModel freqModel, - int relativeTo) { - - super(name, dataType, freqModel); - - setRatesRelativeTo(relativeTo); - } - - protected void frequenciesChanged() { - // Nothing to precalculate - } - - protected void ratesChanged() { - // Nothing to precalculate - } - - protected void setupRelativeRates() { - - for (int i = 0; i < relativeRates.length; i++) { - if (i == ratesRelativeTo) { - relativeRates[i] = 1.0; - } else if (i < ratesRelativeTo) { - relativeRates[i] = ratesParameter.getParameterValue(i); - } else { - relativeRates[i] = ratesParameter.getParameterValue(i - 1); - } - } - } - - /** - * set which rate the others are relative to - * - * @param ratesRelativeTo the index of the rate in the matrix that all other - * rates are parameterized relative to. - */ - public void setRatesRelativeTo(int ratesRelativeTo) { - this.ratesRelativeTo = ratesRelativeTo; - } - - // ***************************************************************** - // Interface Model - // ***************************************************************** - - - protected void storeState() { - } // nothing to do - - /** - * Restore the additional stored state - */ - protected void restoreState() { - updateMatrix = true; - } - - protected void acceptState() { - } // nothing to do - - // ************************************************************** - // XHTMLable IMPLEMENTATION - // ************************************************************** - - public String toXHTML() { - StringBuffer buffer = new StringBuffer(); - - buffer.append("General Model"); - - return buffer.toString(); - } - - protected Parameter ratesParameter = null; -} diff --git a/src/dr/oldevomodel/substmodel/HKY.java b/src/dr/oldevomodel/substmodel/HKY.java deleted file mode 100644 index 6b8fc4d08a..0000000000 --- a/src/dr/oldevomodel/substmodel/HKY.java +++ /dev/null @@ -1,415 +0,0 @@ -/* - * HKY.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.substmodel; - -import dr.inference.model.Parameter; -import dr.inference.model.Statistic; -import dr.inference.model.Variable; -import dr.util.Author; -import dr.util.Citable; -import dr.util.Citation; - -import java.util.Collections; -import java.util.List; - - -/** - * Hasegawa-Kishino-Yano model of nucleotide evolution - * - * @author Alexei Drummond - * @author Andrew Rambaut - */ -public class HKY extends AbstractNucleotideModel implements Citable { - - /** - * tsTv - */ - private double tsTv; - - private Variable kappaParameter = null; - - private boolean updateIntermediates = true; - - /** - * Used for precalculations - */ - private double beta, A_R, A_Y; - private double tab1A, tab2A, tab3A; - private double tab1C, tab2C, tab3C; - private double tab1G, tab2G, tab3G; - private double tab1T, tab2T, tab3T; - - /** - * A constructor which allows a more programmatic approach with - * fixed kappa. - * @param kappa - * @param freqModel - */ - public HKY(double kappa, FrequencyModel freqModel) { - this(new Parameter.Default(kappa), freqModel); - } - /** - * Constructor - */ - public HKY(Variable kappaParameter, FrequencyModel freqModel) { - - super(NucModelType.HKY.getXMLName(), freqModel); - this.kappaParameter = kappaParameter; - addVariable(kappaParameter); - kappaParameter.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, 0.0, 1)); - updateIntermediates = true; - - addStatistic(tsTvStatistic); - } - - /** - * set kappa - */ - public void setKappa(double kappa) { - kappaParameter.setValue(0, kappa); - updateMatrix = true; - } - - /** - * @return kappa - */ - public final double getKappa() { - return kappaParameter.getValue(0); - } - - /** - * set ts/tv - */ - public void setTsTv(double tsTv) { - this.tsTv = tsTv; - calculateFreqRY(); - setKappa((tsTv * freqR * freqY) / (freqA * freqG + freqC * freqT)); - } - - /** - * @return tsTv - */ - public double getTsTv() { - calculateFreqRY(); - tsTv = (getKappa() * (freqA * freqG + freqC * freqT)) / (freqR * freqY); - - return tsTv; - } - - protected void frequenciesChanged() { - // frequencyModel changed - updateIntermediates = true; - } - - private void calculateIntermediates() { - - calculateFreqRY(); - - // small speed up - reduce calculations. Comments show original code - - // (C+T) / (A+G) - final double r1 = (1 / freqR) - 1; - tab1A = freqA * r1; - - tab3A = freqA / freqR; - tab2A = 1 - tab3A; // (freqR-freqA)/freqR; - - final double r2 = 1 / r1; // ((1 / freqY) - 1); - tab1C = freqC * r2; - - tab3C = freqC / freqY; - tab2C = 1 - tab3C; // (freqY-freqC)/freqY; assert tab2C + tab3C == 1.0; - - tab1G = freqG * r1; - tab3G = tab2A; // 1 - tab3A; // freqG/freqR; - tab2G = tab3A; // 1 - tab3G; // (freqR-freqG)/freqR; - - tab1T = freqT * r2; - - tab3T = tab2C; // 1 - tab3C; // freqT/freqY; - tab2T = tab3C; // 1 - tab3T; // (freqY-freqT)/freqY; //assert tab2T + tab3T == 1.0 ; - - updateMatrix = true; - updateIntermediates = false; - } - - /** - * get the complete transition probability matrix for the given distance - * - * @param distance the expected number of substitutions - * @param matrix an array to store the matrix - */ - public void getTransitionProbabilities(double distance, double[] matrix) { - synchronized (this) { - if (updateIntermediates) { - calculateIntermediates(); - } - - if (updateMatrix) { - setupMatrix(); - } - } - - final double xx = beta * distance; - final double bbR = Math.exp(xx * A_R); - final double bbY = Math.exp(xx * A_Y); - - final double aa = Math.exp(xx); - final double oneminusa = 1 - aa; - - final double t1Aaa = (tab1A * aa); - matrix[0] = freqA + t1Aaa + (tab2A * bbR); - - matrix[1] = freqC * oneminusa; - final double t1Gaa = (tab1G * aa); - matrix[2] = freqG + t1Gaa - (tab3G * bbR); - matrix[3] = freqT * oneminusa; - - matrix[4] = freqA * oneminusa; - final double t1Caa = (tab1C * aa); - matrix[5] = freqC + t1Caa + (tab2C * bbY); - matrix[6] = freqG * oneminusa; - final double t1Taa = (tab1T * aa); - matrix[7] = freqT + t1Taa - (tab3T * bbY); - - matrix[8] = freqA + t1Aaa - (tab3A * bbR); - matrix[9] = matrix[1]; - matrix[10] = freqG + t1Gaa + (tab2G * bbR); - matrix[11] = matrix[3]; - - matrix[12] = matrix[4]; - matrix[13] = freqC + t1Caa - (tab3C * bbY); - matrix[14] = matrix[6]; - matrix[15] = freqT + t1Taa + (tab2T * bbY); - } - - /** - * setup substitution matrix - */ - public void setupMatrix() { - final double kappa = getKappa(); - beta = -1.0 / (2.0 * (freqR * freqY + kappa * (freqA * freqG + freqC * freqT))); - - A_R = 1.0 + freqR * (kappa - 1); - A_Y = 1.0 + freqY * (kappa - 1); - - updateMatrix = false; - } - - protected void setupRelativeRates() { - } - - /** - * This function returns the Eigen vectors. - * - * @return the array - */ - public double[][] getEigenVectors() { - synchronized (this) { - if (updateMatrix) { - setupEigenSystem(); - } - } - return Evec; - } - - /** - * This function returns the inverse Eigen vectors. - * - * @return the array - */ - public double[][] getInverseEigenVectors() { - synchronized (this) { - if (updateMatrix) { - setupEigenSystem(); - } - } - return Ievc; - } - - /** - * This function returns the Eigen values. - */ - public double[] getEigenValues() { - synchronized (this) { - if (updateMatrix) { - setupEigenSystem(); - } - } - return Eval; - } - - /** - * setup substitution matrix - */ - protected void setupEigenSystem() { - if (!eigenInitialised) - initialiseEigen(); - - final double kappa = getKappa(); - - // left eigenvector #1 - Ievc[0][0] = freqA; // or, evec[0] = pi; - Ievc[0][1] = freqC; - Ievc[0][2] = freqG; - Ievc[0][3] = freqT; - - // left eigenvector #2 - Ievc[1][0] = freqA * freqY; - Ievc[1][1] = -freqC * freqR; - Ievc[1][2] = freqG * freqY; - Ievc[1][3] = -freqT * freqR; - - Ievc[2][1] = 1; // left eigenvectors 3 = (0,1,0,-1); 4 = (1,0,-1,0) - Ievc[2][3] = -1; - - Ievc[3][0] = 1; - Ievc[3][2] = -1; - - Evec[0][0] = 1; // right eigenvector 1 = (1,1,1,1)' - Evec[1][0] = 1; - Evec[2][0] = 1; - Evec[3][0] = 1; - - // right eigenvector #2 - Evec[0][1] = 1.0/freqR; - Evec[1][1] = -1.0/freqY; - Evec[2][1] = 1.0/freqR; - Evec[3][1] = -1.0/freqY; - - // right eigenvector #3 - Evec[1][2] = freqT / freqY; - Evec[3][2] = -freqC / freqY; - - // right eigenvector #4 - Evec[0][3] = freqG / freqR; - Evec[2][3] = -freqA / freqR; - - // eigenvectors - beta = -1.0 / (2.0 * (freqR * freqY + kappa * (freqA * freqG + freqC * freqT))); - - A_R = 1.0 + freqR * (kappa - 1); - A_Y = 1.0 + freqY * (kappa - 1); - - Eval[1] = beta; - Eval[2] = beta*A_Y; - Eval[3] = beta*A_R; - - updateMatrix = false; - } - - /** - * allocate memory for the Eigen routines - */ - protected void initialiseEigen() { - - Eval = new double[stateCount]; - Evec = new double[stateCount][stateCount]; - Ievc = new double[stateCount][stateCount]; - - eigenInitialised = true; - updateMatrix = true; - } - // ***************************************************************** - // Interface Model - // ***************************************************************** - - /** - * Restore the stored state - */ - public void restoreState() { - super.restoreState(); - updateIntermediates = true; - } - - // ************************************************************** - // XHTMLable IMPLEMENTATION - // ************************************************************** - - public String toXHTML() { - StringBuffer buffer = new StringBuffer(); - - buffer.append("HKY Model Ts/Tv = "); - buffer.append(getTsTv()); - buffer.append(" (kappa = "); - buffer.append(getKappa()); - buffer.append(")"); - - return buffer.toString(); - } - - // - // Private stuff - // - - private final Statistic tsTvStatistic = new Statistic.Abstract() { - - public String getStatisticName() { - return "tsTv"; - } - - public int getDimension() { - return 1; - } - - public double getStatisticValue(int dim) { - return getTsTv(); - } - - }; - - @Override - public Citation.Category getCategory() { - return Citation.Category.SUBSTITUTION_MODELS; - } - - @Override - public String getDescription() { - return "HKY nucleotide substitution model"; - } - - @Override - public List getCitations() { - return Collections.singletonList(CITATION); - } - - - public static Citation CITATION = new Citation( - new Author[]{ - new Author("M", "Hasegawa"), - new Author("H", "Kishino"), - new Author("T", "Yano") - }, - "Dating the human-ape splitting by a molecular clock of mitochondrial DNA", - 1985, - "Journal of Molecular Evolution", - 22, - 160, 174, - Citation.Status.PUBLISHED - ); -} diff --git a/src/dr/oldevomodel/substmodel/JTT.java b/src/dr/oldevomodel/substmodel/JTT.java deleted file mode 100644 index 72f42391c1..0000000000 --- a/src/dr/oldevomodel/substmodel/JTT.java +++ /dev/null @@ -1,221 +0,0 @@ -/* - * JTT.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.substmodel; - -import dr.evolution.datatype.AminoAcids; -import dr.util.Author; -import dr.util.Citation; - -import java.util.*; - -/** - * JTT model for amino acid evolution - * D.T. Jones, W.R. Taylor, and J.M. Thornton - * The rapid generation of mutation data matrices from protein sequences - * CABIOS vol. 8 no. 3 1992 pp. 275-282 - * - * - * @author Andrew Rambaut - * @author Alexei Drummond - */ -public class JTT extends EmpiricalRateMatrix.AbstractAminoAcid { - - public static final JTT INSTANCE = new JTT(); - - // The rates below are specified assuming that the amino acids are in this order: - // ARNDCQEGHILKMFPSTWYV - // but the AminoAcids dataType wants them in this order: - // ACDEFGHIKLMNPQRSTVWY - // This is solved by calling the setEmpiricalRates and setEmpiricalFrequencies methods - private JTT() { super("JTT"); - - int n = AminoAcids.INSTANCE.getStateCount(); - - double[][] rate = new double[n][n]; - - // Q matrix - rate[0][1]=3.1628651460584e+00; rate[0][2]=3.2804935927860e+00; - rate[0][3]=4.8477237048666e+00; rate[0][4]=3.4612244897959e+00; - rate[0][5]=3.3130910900946e+00; rate[0][6]=6.3199473337722e+00; - rate[0][7]=1.0440154440154e+01; rate[0][8]=1.3061224489796e+00; - rate[0][9]=2.1726844583987e+00; rate[0][10]=1.8443597219107e+00; - rate[0][11]=2.2137668626773e+00; rate[0][12]=2.7210884353741e+00; - rate[0][13]=8.3265306122449e-01; rate[0][14]=1.1537414965986e+01; - rate[0][15]=2.2838213546288e+01; rate[0][16]=2.7007955724663e+01; - rate[0][17]=5.1311953352770e-01; rate[0][18]=8.3673469387755e-01; - rate[0][19]=1.7474335188621e+01; - - rate[1][2]=2.6598918637222e+00; rate[1][3]=9.1014867485456e-01; - rate[1][4]=6.1624649859944e+00; rate[1][5]=1.8036482885837e+01; - rate[1][6]=1.8924731182796e+00; rate[1][7]=8.1810886516769e+00; - rate[1][8]=1.9119717452198e+01; rate[1][9]=1.4410687351864e+00; - rate[1][10]=2.2211961707760e+00; rate[1][11]=3.9239234676922e+01; - rate[1][12]=2.5060690943044e+00; rate[1][13]=3.9439775910364e-01; - rate[1][14]=4.1953094963476e+00; rate[1][15]=5.9016766126741e+00; - rate[1][16]=3.8437069743152e+00; rate[1][17]=7.6766706682673e+00; - rate[1][18]=1.4173669467787e+00; rate[1][19]=1.0308123249300e+00; - - rate[2][3]=3.2226935854843e+01; rate[2][4]=1.8710963455150e+00; - rate[2][5]=4.5351268130622e+00; rate[2][6]=3.3951344979102e+00; - rate[2][7]=4.5987249708180e+00; rate[2][8]=2.3693774375271e+01; - rate[2][9]=2.9235880398671e+00; rate[2][10]=8.0960899565551e-01; - rate[2][11]=1.5024269384537e+01; rate[2][12]=1.9003322259136e+00; - rate[2][13]=4.3853820598007e-01; rate[2][14]=7.1083317047749e-01; - rate[2][15]=2.9456208772690e+01; rate[2][16]=1.3735908553410e+01; - rate[2][17]=1.6706217370669e-01; rate[2][18]=4.1661129568106e+00; - rate[2][19]=9.7452934662237e-01; - - rate[3][4]=6.2857142857143e-01; rate[3][5]=3.0662020905923e+00; - rate[3][6]=4.5450549450549e+01; rate[3][7]=7.5402435402435e+00; - rate[3][8]=6.0544672718586e+00; rate[3][9]=6.8808114961961e-01; - rate[3][10]=3.6130902064968e-01; rate[3][11]=1.6718197057180e+00; - rate[3][12]=1.0879120879121e+00; rate[3][13]=1.9340659340659e-01; - rate[3][14]=7.3949579831933e-01; rate[3][15]=3.4196528109572e+00; - rate[3][16]=2.4749487800335e+00; rate[3][17]=3.4536891679749e-01; - rate[3][18]=2.6895604395604e+00; rate[3][19]=1.8608058608059e+00; - - rate[4][5]=5.5191637630662e-01; rate[4][6]=3.2442396313364e-01; - rate[4][7]=3.3297297297297e+00; rate[4][8]=4.3726708074534e+00; - rate[4][9]=9.1868131868132e-01; rate[4][10]=9.9466248037677e-01; - rate[4][11]=2.9830508474576e-01; rate[4][12]=2.4095238095238e+00; - rate[4][13]=4.1485714285714e+00; rate[4][14]=7.3949579831933e-01; - rate[4][15]=1.2862939958592e+01; rate[4][16]=2.8125907990315e+00; - rate[4][17]=6.8244897959184e+00; rate[4][18]=1.2885714285714e+01; - rate[4][19]=3.7714285714286e+00; - - rate[5][6]=2.0316061593796e+01; rate[5][7]=1.3922214897825e+00; - rate[5][8]=3.3861536130889e+01; rate[5][9]=4.7172339855267e-01; - rate[5][10]=4.2320327755868e+00; rate[5][11]=1.7835941652395e+01; - rate[5][12]=2.6573751451800e+00; rate[5][13]=2.7595818815331e-01; - rate[5][14]=9.4992143198743e+00; rate[5][15]=3.2350653941322e+00; - rate[5][16]=3.0973838067678e+00; rate[5][17]=1.0512692882031e+00; - rate[5][18]=1.5331010452962e+00; rate[5][19]=1.0778164924506e+00; - - rate[6][7]=6.6857641051189e+00; rate[6][8]=1.4458024443999e+00; - rate[6][9]=6.7068415455512e-01; rate[6][10]=5.7932850559579e-01; - rate[6][11]=1.0365070686558e+01; rate[6][12]=1.0138248847926e+00; - rate[6][13]=2.6359447004608e-01; rate[6][14]=1.1291226167887e+00; - rate[6][15]=1.8337006611901e+00; rate[6][16]=1.9520424900414e+00; - rate[6][17]=6.9519420671494e-01; rate[6][18]=3.8018433179723e-01; - rate[6][19]=2.7772657450077e+00; - - rate[7][8]=1.2113479939567e+00; rate[7][9]=3.2670032670033e-01; - rate[7][10]=4.1817641817642e-01; rate[7][11]=1.6354950592239e+00; - rate[7][12]=7.6447876447876e-01; rate[7][13]=3.0579150579151e-01; - rate[7][14]=1.2391551215081e+00; rate[7][15]=1.1138492529797e+01; - rate[7][16]=1.8888816176952e+00; rate[7][17]=3.3491450634308e+00; - rate[7][18]=3.1853281853282e-01; rate[7][19]=2.8416988416988e+00; - - rate[8][9]=1.0931677018634e+00; rate[8][10]=3.2194389461470e+00; - rate[8][11]=3.1498052426571e+00; rate[8][12]=1.9130434782609e+00; - rate[8][13]=2.7329192546584e+00; rate[8][14]=6.7304834977469e+00; - rate[8][15]=4.3726708074534e+00; rate[8][16]=2.8162964522581e+00; - rate[8][17]=7.8083407275954e-01; rate[8][18]=3.5118012422360e+01; - rate[8][19]=7.2877846790890e-01; - - rate[9][10]=1.4069798333535e+01; rate[9][11]=1.2292791953809e+00; - rate[9][12]=2.8366300366300e+01; rate[9][13]=4.7384615384615e+00; - rate[9][14]=5.8780435251023e-01; rate[9][15]=2.4105749323141e+00; - rate[9][16]=1.5243062022723e+01; rate[9][17]=8.2888540031397e-01; - rate[9][18]=1.8434065934066e+00; rate[9][19]=5.7699633699634e+01; - - rate[10][11]=8.8039805231089e-01; rate[10][12]=2.2425954997384e+01; - rate[10][13]=1.5099529042386e+01; rate[10][14]=6.2626896912611e+00; - rate[10][15]=3.4917298022888e+00; rate[10][16]=1.6109411169944e+00; - rate[10][17]=3.2366001345593e+00; rate[10][18]=1.4505494505495e+00; - rate[10][19]=1.0557823129252e+01; - - rate[11][12]=3.6577885391445e+00; rate[11][13]=1.4915254237288e-01; - rate[11][14]=1.2868062479229e+00; rate[11][15]=2.8162964522581e+00; - rate[11][16]=5.7494151926786e+00; rate[11][17]=5.4790729851263e-01; - rate[11][18]=5.3268765133172e-01; rate[11][19]=7.4899112187248e-01; - - rate[12][13]=2.5666666666667e+00; rate[12][14]=9.4491129785247e-01; - rate[12][15]=1.6397515527950e+00; rate[12][16]=1.2180790960452e+01; - rate[12][17]=1.1972789115646e+00; rate[12][18]=1.1130952380952e+00; - rate[12][19]=1.7746031746032e+01; - - rate[13][14]=8.8739495798319e-01; rate[13][15]=5.6298136645963e+00; - rate[13][16]=8.3099273607748e-01; rate[13][17]=3.3224489795918e+00; - rate[13][18]=3.3392857142857e+01; rate[13][19]=3.6000000000000e+00; - - rate[14][15]=1.6261762676085e+01; rate[14][16]=6.8852490148602e+00; - rate[14][17]=4.2256902761104e-01; rate[14][18]=6.7787114845938e-01; - rate[14][19]=1.2549019607843e+00; - - rate[15][16]=2.7891216619293e+01; rate[15][17]=1.8740017746229e+00; - rate[15][18]=3.7349896480331e+00; rate[15][19]=2.4182194616977e+00; - - rate[16][17]=4.8702870978900e-01; rate[16][18]=1.1985472154964e+00; - rate[16][19]=6.7925746569814e+00; - - rate[17][18]=4.6020408163265e+00; rate[17][19]=1.4693877551020e+00; - - rate[18][19]=1.0000000000000e+00; - - setEmpiricalRates(rate, "ARNDCQEGHILKMFPSTWYV"); - - double[] f = new double[n]; - f[0] = 0.077; f[1] = 0.051; f[2] = 0.043; f[3] = 0.052; - f[4] = 0.02; f[5] = 0.041; f[6] = 0.062; f[7] = 0.074; - f[8] = 0.023; f[9] = 0.052; f[10] = 0.091; f[11] = 0.059; - f[12] = 0.024; f[13] = 0.04; f[14] = 0.051; f[15] = 0.069; - f[16] = 0.059; f[17] = 0.014; f[18] = 0.032; f[19] = 0.066; - setEmpiricalFrequencies(f, "ARNDCQEGHILKMFPSTWYV"); - } - - - @Override - public Citation.Category getCategory() { - return Citation.Category.SUBSTITUTION_MODELS; - } - - @Override - public String getDescription() { - return "JTT amino acid substitution model"; - } - - @Override - public List getCitations() { - return Collections.singletonList(CITATION); - } - - public static Citation CITATION = new Citation( - new Author[]{ - new Author("DT", "Jones"), - new Author("WR", "Taylor"), - new Author("JM", "Thornton") - }, - "The rapid generation of mutation data matrices from protein sequences", - 1992, - "CABIOS", - 8, - 275, 282, - Citation.Status.PUBLISHED - ); -} diff --git a/src/dr/oldevomodel/substmodel/LG.java b/src/dr/oldevomodel/substmodel/LG.java deleted file mode 100644 index 9f80f5bc54..0000000000 --- a/src/dr/oldevomodel/substmodel/LG.java +++ /dev/null @@ -1,342 +0,0 @@ -/* - * LG.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.substmodel; - -import dr.evolution.datatype.AminoAcids; -import dr.util.Author; -import dr.util.Citation; - -import java.util.*; - -/** - * LG model of amino acid evolution (Le and Gascuel, 2008) - * Le, S. Q. and O. Gascuel. 2008. Mol. Biol. Evol. 25(7):1307-1320. - * - * @author Guy Baele - */ -public class LG extends EmpiricalRateMatrix.AbstractAminoAcid { - - public static final LG INSTANCE = new LG(); - - // The rates below are specified assuming that the amino acids are in this order: - // ARNDCQEGHILKMFPSTWYV - // but the AminoAcids dataType wants them in this order: - // ACDEFGHIKLMNPQRSTVWY - // This is solved by calling the setEmpiricalRates and setEmpiricalFrequencies methods - private LG() { super("LG"); - - int n = AminoAcids.INSTANCE.getStateCount(); - - double[][] rate = new double[n][n]; - - // Q matrix - rate[0][1] = 0.425093; - rate[0][2] = 0.276818; - rate[0][3] = 0.395144; - rate[0][4] = 2.489084; - rate[0][5] = 0.969894; - rate[0][6] = 1.038545; - rate[0][7] = 2.066040; - rate[0][8] = 0.358858; - rate[0][9] = 0.149830; - rate[0][10] = 0.395337; - rate[0][11] = 0.536518; - rate[0][12] = 1.124035; - rate[0][13] = 0.253701; - rate[0][14] = 1.177651; - rate[0][15] = 4.727182; - rate[0][16] = 2.139501; - rate[0][17] = 0.180717; - rate[0][18] = 0.218959; - rate[0][19] = 2.547870; - - rate[1][2] = 0.751878; - rate[1][3] = 0.123954; - rate[1][4] = 0.534551; - rate[1][5] = 2.807908; - rate[1][6] = 0.363970; - rate[1][7] = 0.390192; - rate[1][8] = 2.426601; - rate[1][9] = 0.126991; - rate[1][10] = 0.301848; - rate[1][11] = 6.326067; - rate[1][12] = 0.484133; - rate[1][13] = 0.052722; - rate[1][14] = 0.332533; - rate[1][15] = 0.858151; - rate[1][16] = 0.578987; - rate[1][17] = 0.593607; - rate[1][18] = 0.314440; - rate[1][19] = 0.170887; - - rate[2][3] = 5.076149; - rate[2][4] = 0.528768; - rate[2][5] = 1.695752; - rate[2][6] = 0.541712; - rate[2][7] = 1.437645; - rate[2][8] = 4.509238; - rate[2][9] = 0.191503; - rate[2][10] = 0.068427; - rate[2][11] = 2.145078; - rate[2][12] = 0.371004; - rate[2][13] = 0.089525; - rate[2][14] = 0.161787; - rate[2][15] = 4.008358; - rate[2][16] = 2.000679; - rate[2][17] = 0.045376; - rate[2][18] = 0.612025; - rate[2][19] = 0.083688; - - rate[3][4] = 0.062556; - rate[3][5] = 0.523386; - rate[3][6] = 5.243870; - rate[3][7] = 0.844926; - rate[3][8] = 0.927114; - rate[3][9] = 0.010690; - rate[3][10] = 0.015076; - rate[3][11] = 0.282959; - rate[3][12] = 0.025548; - rate[3][13] = 0.017416; - rate[3][14] = 0.394456; - rate[3][15] = 1.240275; - rate[3][16] = 0.425860; - rate[3][17] = 0.029890; - rate[3][18] = 0.135107; - rate[3][19] = 0.037967; - - rate[4][5] = 0.084808; - rate[4][6] = 0.003499; - rate[4][7] = 0.569265; - rate[4][8] = 0.640543; - rate[4][9] = 0.320627; - rate[4][10] = 0.594007; - rate[4][11] = 0.013266; - rate[4][12] = 0.893680; - rate[4][13] = 1.105251; - rate[4][14] = 0.075382; - rate[4][15] = 2.784478; - rate[4][16] = 1.143480; - rate[4][17] = 0.670128; - rate[4][18] = 1.165532; - rate[4][19] = 1.959291; - - rate[5][6] = 4.128591; - rate[5][7] = 0.267959; - rate[5][8] = 4.813505; - rate[5][9] = 0.072854; - rate[5][10] = 0.582457; - rate[5][11] = 3.234294; - rate[5][12] = 1.672569; - rate[5][13] = 0.035855; - rate[5][14] = 0.624294; - rate[5][15] = 1.223828; - rate[5][16] = 1.080136; - rate[5][17] = 0.236199; - rate[5][18] = 0.257336; - rate[5][19] = 0.210332; - - rate[6][7] = 0.348847; - rate[6][8] = 0.423881; - rate[6][9] = 0.044265; - rate[6][10] = 0.069673; - rate[6][11] = 1.807177; - rate[6][12] = 0.173735; - rate[6][13] = 0.018811; - rate[6][14] = 0.419409; - rate[6][15] = 0.611973; - rate[6][16] = 0.604545; - rate[6][17] = 0.077852; - rate[6][18] = 0.120037; - rate[6][19] = 0.245034; - - rate[7][8] = 0.311484; - rate[7][9] = 0.008705; - rate[7][10] = 0.044261; - rate[7][11] = 0.296636; - rate[7][12] = 0.139538; - rate[7][13] = 0.089586; - rate[7][14] = 0.196961; - rate[7][15] = 1.739990; - rate[7][16] = 0.129836; - rate[7][17] = 0.268491; - rate[7][18] = 0.054679; - rate[7][19] = 0.076701; - - rate[8][9] = 0.108882; - rate[8][10] = 0.366317; - rate[8][11] = 0.697264; - rate[8][12] = 0.442472; - rate[8][13] = 0.682139; - rate[8][14] = 0.508851; - rate[8][15] = 0.990012; - rate[8][16] = 0.584262; - rate[8][17] = 0.597054; - rate[8][18] = 5.306834; - rate[8][19] = 0.119013; - - rate[9][10] = 4.145067; - rate[9][11] = 0.159069; - rate[9][12] = 4.273607; - rate[9][13] = 1.112727; - rate[9][14] = 0.078281; - rate[9][15] = 0.064105; - rate[9][16] = 1.033739; - rate[9][17] = 0.111660; - rate[9][18] = 0.232523; - rate[9][19] = 10.649107; - - rate[10][11] = 0.137500; - rate[10][12] = 6.312358; - rate[10][13] = 2.592692; - rate[10][14] = 0.249060; - rate[10][15] = 0.182287; - rate[10][16] = 0.302936; - rate[10][17] = 0.619632; - rate[10][18] = 0.299648; - rate[10][19] = 1.702745; - - rate[11][12] = 0.656604; - rate[11][13] = 0.023918; - rate[11][14] = 0.390322; - rate[11][15] = 0.748683; - rate[11][16] = 1.136863; - rate[11][17] = 0.049906; - rate[11][18] = 0.131932; - rate[11][19] = 0.185202; - - rate[12][13] = 1.798853; - rate[12][14] = 0.099849; - rate[12][15] = 0.346960; - rate[12][16] = 2.020366; - rate[12][17] = 0.696175; - rate[12][18] = 0.481306; - rate[12][19] = 1.898718; - - rate[13][14] = 0.094464; - rate[13][15] = 0.361819; - rate[13][16] = 0.165001; - rate[13][17] = 2.457121; - rate[13][18] = 7.803902; - rate[13][19] = 0.654683; - - rate[14][15] = 1.338132; - rate[14][16] = 0.571468; - rate[14][17] = 0.095131; - rate[14][18] = 0.089613; - rate[14][19] = 0.296501; - - rate[15][16] = 6.472279; - rate[15][17] = 0.248862; - rate[15][18] = 0.400547; - rate[15][19] = 0.098369; - - rate[16][17] = 0.140825; - rate[16][18] = 0.245841; - rate[16][19] = 2.188158; - - rate[17][18] = 3.151815; - rate[17][19] = 0.189510; - - rate[18][19] = 0.249313; - - setEmpiricalRates(rate, "ARNDCQEGHILKMFPSTWYV"); - - //the order of the amino acid codes below - //Ala = A - //Arg = R - //Asn = N - //Asp = D - //Cys = C - //Gln = Q - //Glu = E - //Gly = G - //His = H - //Ile = I - //Leu = L - //Lys = K - //Met = M - //Phe = F - //Pro = P - //Ser = S - //Thr = T - //Trp = W - //Tyr = Y - //Val = V - double[] f = new double[n]; - f[0] = 0.079066; - f[1] = 0.055941; - f[2] = 0.041977; - f[3] = 0.053052; - f[4] = 0.012937; - f[5] = 0.040767; - f[6] = 0.071586; - f[7] = 0.057337; - f[8] = 0.022355; - f[9] = 0.062157; - f[10] = 0.099081; - f[11] = 0.064600; - f[12] = 0.022951; - f[13] = 0.042302; - f[14] = 0.044040; - f[15] = 0.061197; - f[16] = 0.053287; - f[17] = 0.012066; - f[18] = 0.034155; - f[19] = 0.069147; - setEmpiricalFrequencies(f, "ARNDCQEGHILKMFPSTWYV"); - } - - @Override - public Citation.Category getCategory() { - return Citation.Category.SUBSTITUTION_MODELS; - } - - @Override - public String getDescription() { - return "LG amino acid substitution model"; - } - - @Override - public List getCitations() { - return Collections.singletonList(CITATION); - } - - - public static Citation CITATION = new Citation( - new Author[]{ - new Author("S. Q.", "Le"), - new Author("O.", "Gascuel") - }, - "An Improved General Amino Acid Replacement Matrix", - 2008, - "Mol. Biol. Evol.", - 25, - 1307, 1320, - Citation.Status.PUBLISHED - ); -} diff --git a/src/dr/oldevomodel/substmodel/LinearBiasModel.java b/src/dr/oldevomodel/substmodel/LinearBiasModel.java deleted file mode 100644 index 07324bfe6a..0000000000 --- a/src/dr/oldevomodel/substmodel/LinearBiasModel.java +++ /dev/null @@ -1,240 +0,0 @@ -/* - * LinearBiasModel.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.substmodel; - -import dr.evolution.datatype.Microsatellite; -import dr.inference.model.Parameter; -import dr.inference.model.Variable; - -import java.util.ArrayList; - -/** - * @author Chieh-Hsi Wu - * - * Implements the LinearBiasModel of microsatellites. - */ -public class LinearBiasModel extends OnePhaseModel{ - - /* - *Parameters for setting up the infinitesimal rate matrix. - */ - private Parameter biasConst; - private Parameter biasLin; - private ArrayList> submodelParameters = null; - private boolean estimateSubmodelParams = false; - private boolean updateSubmodelRates = false; - private boolean inLogitSpace = false; - - public static final double delta = 1e-15; - - public static final String LINEAR_BIAS_MODEL = "LINEARBIASModel"; - - - /** - * Constructor - * - * @param microsatellite microsatellite data type - * @param freqModel user specified initial equilibrium frequencies - * @param submodel submodel of this linear bias model - * @param biasConst bias constant parameter - * @param biasLinear bias linear parameter - * @param inLogitSpace indicates whether the bias parameters are in the logit space - * @param estimateSubmodelParams inidicate whether the parameters of submodel will be estimated - * @param isSubmodel inidicate whether this model is a submodel of another microsatellite model - */ - public LinearBiasModel( - Microsatellite microsatellite, - FrequencyModel freqModel, - OnePhaseModel submodel, - Parameter biasConst, - Parameter biasLinear, - boolean inLogitSpace, - boolean estimateSubmodelParams, - boolean isSubmodel){ - - super(LINEAR_BIAS_MODEL, microsatellite, freqModel, null); - - isNested = isSubmodel; - this.subModel = submodel; - this.estimateSubmodelParams = estimateSubmodelParams; - if(this.estimateSubmodelParams){ - submodelParameters = new ArrayList>(); - for(int i = 0; i < subModel.getNestedParameterCount(); i++){ - - if(isNested){ - addVariable(subModel.getNestedParameter(i)); - } - - addParam(subModel.getNestedParameter(i)); - submodelParameters.add(subModel.getNestedParameter(i)); - } - updateSubmodelRates = true; - } - - - - //The default setting of the parameters gives infinitesimal rates with no directional bias. - if(biasConst != null){ - this.biasConst = biasConst; - }else{ - this.biasConst = new Parameter.Default(0.5); - } - - - if(biasLinear != null){ - biasLin = biasLinear; - }else{ - biasLin = new Parameter.Default(0.0); - } - addParam(this.biasConst); - addParam(this.biasLin); - - this.inLogitSpace = inLogitSpace; - - //printDetails(); - - setupInfinitesimalRates(); - - if(freqModel == null){ - useStationaryFreqs = true; - computeStationaryDistribution(); - }else{ - this.freqModel = freqModel; - - } - addModel(this.freqModel); - - } - protected void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) { - if(submodelParameters !=null && submodelParameters.indexOf((Parameter)variable) != -1){ - updateSubmodelRates = true; - } - updateMatrix = true; - - } - - public void setupInfinitesimalRates(){ - if(updateSubmodelRates){ - subModel.setupInfinitesimalRates(); - updateSubmodelRates = false; - } - - double biasConst = this.biasConst.getParameterValue(0); - double biasLin = this.biasLin.getParameterValue(0); - setupInfinitesimalRates( - infinitesimalRateMatrix, - subModel.getInfinitesimalRates(), - biasConst, - biasLin, - stateCount, - inLogitSpace - ); - - } - - - public static void setupInfinitesimalRates( - double[][] rates, - double[][] subModelRateMatrix, - double biasConst, - double biasLin, - int stateCount, - boolean inLogitSpace){ - double rowSum; - double expansionProb = 0.5; - for(int i = 0; i < stateCount;i++){ - rowSum = 0.0; - expansionProb = computeExpansionProb(biasConst,biasLin,i, inLogitSpace); - if(expansionProb < delta){ - System.out.println("changing expan prob from " + expansionProb+ " to " + delta - +"\nbiasConst: "+biasConst+", biasLin: "+biasLin); - expansionProb = delta; - - }else if (expansionProb > (1.0-delta)){ - - System.out.println("changing expan prob from " + expansionProb+ " to " + (1.0-delta) - +"\nbiasConst: "+biasConst+", biasLin: "+biasLin); - expansionProb = 1.0-delta; - } - if(i - 1 > -1){ - rates[i][i - 1] = subModelRateMatrix[i][i-1]*(1.0 - expansionProb); - rowSum = rowSum+rates[i][i - 1]; - } - if(i + 1 < stateCount){ - rates[i][i + 1] = subModelRateMatrix[i][i+1]*expansionProb; - rowSum = rowSum + rates[i][i + 1]; - } - - rates[i][i] = rowSum*-1; - - } - } - - public static double computeExpansionProb(double biasConst, double biasLin, int length, boolean inLogitSpace){ - double expanProb = 0.5; - if(inLogitSpace){ - double numerator = Math.exp(biasConst+biasLin*length); - expanProb = numerator/(1+numerator); - }else{ - expanProb = biasConst+biasLin*length; - } - return expanProb; - - } - - - public Parameter getBiasConstant(){ - return biasConst; - } - - public Parameter getBiasLinearPercent(){ - return biasLin; - } - - public boolean isEstimatingSubmodelParams(){ - return estimateSubmodelParams; - } - - public boolean isInLogitSpace(){ - return inLogitSpace; - } - - public void printDetails(){ - System.out.println("Details of the Linear Bias Model and its paramters:"); - System.out.println("a submodel: "+isNested); - System.out.println("in logit space: "+inLogitSpace); - System.out.println("has submodel: "+hasSubmodel()); - if(hasSubmodel()){ - System.out.println("submodel class: "+subModel.getClass()); - } - System.out.println("esitmating submodel parameters: "+estimateSubmodelParams); - System.out.println("bias constant: "+biasConst.getParameterValue(0)); - System.out.println("bias linear coefficient: "+biasLin.getParameterValue(0)); - } - -} diff --git a/src/dr/oldevomodel/substmodel/MTREV.java b/src/dr/oldevomodel/substmodel/MTREV.java deleted file mode 100644 index 0f2ca12d06..0000000000 --- a/src/dr/oldevomodel/substmodel/MTREV.java +++ /dev/null @@ -1,213 +0,0 @@ -/* - * MTREV.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.substmodel; - -import dr.evolution.datatype.AminoAcids; -import dr.util.Author; -import dr.util.Citation; - -import java.util.*; - -/** - * MTREV24 model of amino acid evolution - * (complete sequence data of mtDNA from 24 vertebrate species) - * Adachi, J., and Hasegawa, M. 1996. J. Mol. Evol. 42:459-468. - * - * - * @author Andrew Rambaut - * @author Alexei Drummond - */ -public class MTREV extends EmpiricalRateMatrix.AbstractAminoAcid { - - public static final MTREV INSTANCE = new MTREV(); - - // The rates below are specified assuming that the amino acids are in this order: - // ARNDCQEGHILKMFPSTWYV - // but the AminoAcids dataType wants them in this order: - // ACDEFGHIKLMNPQRSTVWY - // This is solved by calling the setEmpiricalRates and setEmpiricalFrequencies methods - private MTREV() { super("mtREV24"); - - int n = AminoAcids.INSTANCE.getStateCount(); - - double[][] rate = new double[n][n]; - - // Q matrix - rate[0][1]=1.2199217606346e+01; rate[0][2]=1.4182139942122e+01; - rate[0][3]=9.2985091873208e+00; rate[0][4]=3.1542792981957e+01; - rate[0][5]=1.0025852846688e+00; rate[0][6]=5.1418866803338e+00; - rate[0][7]=6.3531246495131e+01; rate[0][8]=7.3137132861715e+00; - rate[0][9]=5.0782382656186e+01; rate[0][10]=1.3399741808481e+01; - rate[0][11]=4.4021672780560e+00; rate[0][12]=7.4673480520104e+01; - rate[0][13]=3.3513021631978e+00; rate[0][14]=2.8582502221773e+01; - rate[0][15]=2.0413623195312e+02; rate[0][16]=2.5301305153906e+02; - rate[0][17]=1.0000000000000e+00; rate[0][18]=3.4084158197615e+00; - rate[0][19]=1.0266468401249e+02; - - rate[1][2]=6.9661274444534e+00; rate[1][3]=1.0000000000000e+00; - rate[1][4]=5.4384584796568e+01; rate[1][5]=1.1631134513343e+02; - rate[1][6]=1.0000000000000e+00; rate[1][7]=1.2122831341194e+01; - rate[1][8]=8.6961067087353e+01; rate[1][9]=1.0000000000000e+00; - rate[1][10]=8.1976829394538e+00; rate[1][11]=7.4423215395318e+01; - rate[1][12]=1.0000000000000e+00; rate[1][13]=2.4659158338099e+00; - rate[1][14]=1.2439947713615e+01; rate[1][15]=3.1791814866372e+00; - rate[1][16]=1.0935327216119e+00; rate[1][17]=1.1550775790126e+01; - rate[1][18]=1.0000000000000e+00; rate[1][19]=4.0211417480338e+00; - - rate[2][3]=4.1809325468160e+02; rate[2][4]=3.1020979842967e+01; - rate[2][5]=9.1349622725361e+01; rate[2][6]=3.3185663516310e+01; - rate[2][7]=2.8052324651124e+01; rate[2][8]=2.6112087577885e+02; - rate[2][9]=1.4261453863336e+01; rate[2][10]=7.9775653461977e+00; - rate[2][11]=3.2036829276162e+02; rate[2][12]=3.4424354918739e+01; - rate[2][13]=7.9996445145608e+00; rate[2][14]=3.8586541461044e+01; - rate[2][15]=2.6020426225852e+02; rate[2][16]=1.2550758780474e+02; - rate[2][17]=5.6207759736659e+00; rate[2][18]=1.0071406219571e+02; - rate[2][19]=1.0000000000000e+00; - - rate[3][4]=1.0000000000000e+00; rate[3][5]=2.9097352675564e+01; - rate[3][6]=3.0713149855302e+02; rate[3][7]=2.9877072751897e+01; - rate[3][8]=5.9995408885817e+01; rate[3][9]=2.2827096245105e+00; - rate[3][10]=1.0000000000000e+00; rate[3][11]=1.2183938185384e+00; - rate[3][12]=1.0000000000000e+00; rate[3][13]=2.6221929413096e+00; - rate[3][14]=7.0708004204733e+00; rate[3][15]=3.6327934317139e+01; - rate[3][16]=1.4743408713748e+01; rate[3][17]=1.0453246057102e+01; - rate[3][18]=1.1165627147496e+01; rate[3][19]=1.0000000000000e+00; - - rate[4][5]=3.9599394038972e+01; rate[4][6]=1.0000000000000e+00; - rate[4][7]=1.6163581056674e+01; rate[4][8]=7.4467985406234e+01; - rate[4][9]=3.3018175376623e+01; rate[4][10]=1.3500725995091e+01; - rate[4][11]=1.0000000000000e+00; rate[4][12]=3.2504095376923e+00; - rate[4][13]=3.7264767083096e+01; rate[4][14]=1.6454136037822e+01; - rate[4][15]=1.4581783243113e+02; rate[4][16]=9.4720031458442e+01; - rate[4][17]=1.7684087896962e+01; rate[4][18]=1.3409157685926e+02; - rate[4][19]=1.0000000000000e+00; - - rate[5][6]=1.6503249008836e+02; rate[5][7]=3.5530760735494e+00; - rate[5][8]=3.0652523140859e+02; rate[5][9]=4.3905393139325e+00; - rate[5][10]=2.0895470525345e+01; rate[5][11]=2.4504076430724e+02; - rate[5][12]=2.4931300477797e+01; rate[5][13]=1.0059428264289e+01; - rate[5][14]=7.2256314165467e+01; rate[5][15]=2.8480937892158e+01; - rate[5][16]=4.9962974409828e+01; rate[5][17]=1.0000000000000e+00; - rate[5][18]=2.0430790980529e+01; rate[5][19]=9.9986289000676e+00; - - rate[6][7]=1.4884496769963e+01; rate[6][8]=2.5853576435567e+01; - rate[6][9]=1.7418201388328e+00; rate[6][10]=1.0000000000000e+00; - rate[6][11]=1.6519126809071e+02; rate[6][12]=1.0000000000000e+00; - rate[6][13]=1.4067850525292e+00; rate[6][14]=6.7547121641947e+00; - rate[6][15]=2.8794794140840e+01; rate[6][16]=7.8001372062558e+00; - rate[6][17]=1.0000000000000e+00; rate[6][18]=6.9067239183061e+00; - rate[6][19]=1.1127702362585e+01; - - rate[7][8]=1.0000000000000e+00; rate[7][9]=3.1466649021550e+00; - rate[7][10]=1.2699794194865e+00; rate[7][11]=1.1962111069278e+01; - rate[7][12]=1.0000000000000e+00; rate[7][13]=1.0000000000000e+00; - rate[7][14]=1.0000000000000e+00; rate[7][15]=6.6277950574411e+01; - rate[7][16]=5.8800079133028e+00; rate[7][17]=5.7494182626674e+00; - rate[7][18]=1.6887657206208e+00; rate[7][19]=1.3320553471351e+00; - - rate[8][9]=6.4536986087271e+00; rate[8][10]=6.0472584534958e+00; - rate[8][11]=6.7197196398961e+01; rate[8][12]=6.2977633277779e+00; - rate[8][13]=2.5347805183364e+01; rate[8][14]=3.2089868698728e+01; - rate[8][15]=4.0766987134407e+01; rate[8][16]=2.3570850628539e+01; - rate[8][17]=3.7286635325194e+00; rate[8][18]=3.5270764890474e+02; - rate[8][19]=1.0000000000000e+00; - - rate[9][10]=1.7320653206333e+02; rate[9][11]=1.0298655619743e+01; - rate[9][12]=2.7262244199514e+02; rate[9][13]=4.4561065036310e+01; - rate[9][14]=1.0856482766156e+01; rate[9][15]=2.5107659603898e+01; - rate[9][16]=1.9391167162525e+02; rate[9][17]=1.0000000000000e+00; - rate[9][18]=1.3161329199391e+01; rate[9][19]=6.4365086389428e+02; - - rate[10][11]=7.8314019154706e+00; rate[10][12]=2.8290920517725e+02; - rate[10][13]=1.1371735519833e+02; rate[10][14]=2.1105885757279e+01; - rate[10][15]=3.8741359395934e+01; rate[10][16]=6.6524559321657e+01; - rate[10][17]=1.7071378554833e+01; rate[10][18]=2.3234516108847e+01; - rate[10][19]=4.8247261078055e+01; - - rate[11][12]=4.8092094826036e+01; rate[11][13]=3.3887559483420e+00; - rate[11][14]=2.6368577564199e+01; rate[11][15]=5.5679895711418e+01; - rate[11][16]=7.1750284708933e+01; rate[11][17]=1.2631893872825e+01; - rate[11][18]=2.6932728996777e+01; rate[11][19]=1.0000000000000e+00; - - rate[12][13]=4.7798798034572e+01; rate[12][14]=9.9165053447429e+00; - rate[12][15]=5.8505442466161e+01; rate[12][16]=2.7798190504760e+02; - rate[12][17]=1.1427000119701e+01; rate[12][18]=2.1029990530586e+01; - rate[12][19]=2.0397078683768e+02; - - rate[13][14]=9.1089574817139e+00; rate[13][15]=3.3835737720574e+01; - rate[13][16]=1.7815549567056e+01; rate[13][17]=4.1272404968214e+00; - rate[13][18]=2.4504156395152e+02; rate[13][19]=3.3435675442163e+00; - - rate[14][15]=8.9421193040709e+01; rate[14][16]=6.7485067008375e+01; - rate[14][17]=2.2161693733113e+00; rate[14][18]=8.5338209390745e+00; - rate[14][19]=4.3342126659660e+00; - - rate[15][16]=3.1432036618746e+02; rate[15][17]=2.0305343047059e+01; - rate[15][18]=3.4167877957799e+01; rate[15][19]=1.0000000000000e+00; - - rate[16][17]=5.2559565123081e+00; rate[16][18]=2.0382362288681e+01; - rate[16][19]=1.0765527137500e+02; - - rate[17][18]=1.3814733274637e+01; rate[17][19]=2.8259139240676e+00; - - rate[18][19]=1.0000000000000e+00; - - setEmpiricalRates(rate, "ARNDCQEGHILKMFPSTWYV"); - - double[] f = new double[n]; - f[0]=0.072; f[1]=0.019; f[2]=0.039; f[3]=0.019; f[4]=0.006; - f[5]=0.025; f[6]=0.024; f[7]=0.056; f[8]=0.028; f[9]=0.088; - f[10]=0.168; f[11]=0.023; f[12]=0.054; f[13]=0.061; f[14]=0.054; - f[15]=0.072; f[16]=0.086; f[17]=0.029; f[18]=0.033; f[19]=0.043; - setEmpiricalFrequencies(f, "ARNDCQEGHILKMFPSTWYV"); - } - - @Override - public Citation.Category getCategory() { - return Citation.Category.SUBSTITUTION_MODELS; - } - - @Override - public String getDescription() { - return "MTREV amino acid substitution model"; - } - - @Override - public List getCitations() { - return Collections.singletonList(CITATION); - } - - public static Citation CITATION = new Citation( - new Author[]{ - new Author("J", "Adachi"), - new Author("M", "Hasegawa") - }, - "Model of amino acid substitution in proteins encoded by mitochondrial DNA", - 1996, "Journal of Molecular Evolution", 42, 459, 468 - ); -} diff --git a/src/dr/oldevomodel/substmodel/MarginalVarianceStatistic.java b/src/dr/oldevomodel/substmodel/MarginalVarianceStatistic.java deleted file mode 100644 index 1849699f71..0000000000 --- a/src/dr/oldevomodel/substmodel/MarginalVarianceStatistic.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * MarginalVarianceStatistic.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.substmodel; - -import dr.inferencexml.distribution.MultivariateOUModel; -import dr.xml.*; -import dr.inference.model.Statistic; - -/** - * @author Marc A. Suchard - */ -public class MarginalVarianceStatistic extends Statistic.Abstract { - - public static final String VARIANCE_STATISTIC = "marginalVariance"; - - public MarginalVarianceStatistic(MultivariateOUModel mvou) { - this.mvou = mvou; - } - - public int getDimension() { - return mvou.getDimension(); - } - - public double getStatisticValue(int dim) { - return mvou.getStatisticValue(dim); - } - - public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { - - public String getParserName() { - return VARIANCE_STATISTIC; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - MultivariateOUModel mvou = (MultivariateOUModel) xo.getChild(MultivariateOUModel.class); - return new MarginalVarianceStatistic(mvou); - - } - - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - - public String getParserDescription() { - return "This element returns a statistic that is the matrix inverse of the child statistic."; - } - - public Class getReturnType() { - return MarginalVarianceStatistic.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{ - new ElementRule(MultivariateOUModel.class) - }; - }; - - private MultivariateOUModel mvou; -} diff --git a/src/dr/oldevomodel/substmodel/MicrosatelliteModel.java b/src/dr/oldevomodel/substmodel/MicrosatelliteModel.java deleted file mode 100644 index 602b95dfe5..0000000000 --- a/src/dr/oldevomodel/substmodel/MicrosatelliteModel.java +++ /dev/null @@ -1,373 +0,0 @@ -/* - * MicrosatelliteModel.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.substmodel; - - -import dr.evolution.datatype.Microsatellite; -import dr.inference.model.Parameter; -import dr.inference.model.Model; - - -/** - * @author Chieh-Hsi Wu - * - * An abstract class for microsatellite models - */ -public abstract class MicrosatelliteModel extends ComplexSubstitutionModel{ - protected OnePhaseModel subModel = null; - protected boolean isNested = false; - protected double[][] infinitesimalRateMatrix = null; - protected boolean useStationaryFreqs = false; - protected boolean modelUpdate = false; - - - - /** - * Constructor - * @param name Model name - * @param msat Microsatellite data type - * @param rootFreqModel Frequency model - * @param parameter Infinitesimal rates - */ - public MicrosatelliteModel(String name, Microsatellite msat, FrequencyModel rootFreqModel, Parameter parameter) { - super(name, msat, rootFreqModel, parameter); - if(parameter == null){ - double[] q = new double[stateCount*(stateCount-1)]; - infinitesimalRates = new Parameter.Default(q); - } - - infinitesimalRateMatrix = new double[stateCount][stateCount]; - } - - public void setToEqualFrequencies(){ - double[] freqs = new double[stateCount]; - for(int i = 0; i < freqs.length; i++){ - freqs[i] = 1.0/stateCount; - } - this.freqModel = new FrequencyModel(dataType, freqs); - } - - protected void handleModelChangedEvent(Model model, Object object, int index) { - updateMatrix = true; - } - - //store the infinitesimal rates in the vector to a matrix called amat - public void storeIntoAmat(){ - amat = infinitesimalRateMatrix; - } - - //matrix is already valid - protected void makeValid(double[][] matrix, int dimension){} - - protected double getRate(int i, int j){ - return infinitesimalRateMatrix[i][j]; - } - - /* - * Set up stationary frequencies - */ - public void computeTwoPhaseStationaryDistribution(){ - synchronized (this) { - if (updateMatrix) { - setupMatrix(); - } - } - - if (!wellConditioned) { - throw new RuntimeException("not well conditioned"); - } - int eigenValPos = -1; - - for(int i = 0; i < stateCount; i++){ - if(Eval[i] == 0){ - eigenValPos = i; - break; - } - } - /*for(int i = 0; i < EvalImag.length; i++){ - //System.out.println("imaginery part" + EvalImag[i]); - if(EvalImag[i] != 0.0){ - throw new RuntimeException("imaginery part" + EvalImag[i]); - } - }*/ - - double[] empFreq = new double[stateCount]; - //System.out.println("eq dist"); - for(int i = 0; i < stateCount; i++){ - empFreq[i] = Evec[i][eigenValPos]*Ievc[eigenValPos][i]; - //System.out.println(empFreq[i]); - - } - this.freqModel = new FrequencyModel(dataType, empFreq); - } - - - /*public void computeTwoPhaseStationaryDistribution2(){ - setToEqualFrequencies(); - super.computeStationaryDistribution(); - synchronized (this) { - if (updateMatrix) { - setupMatrix(); - } - } - - if (!wellConditioned) { - throw new RuntimeException("not well conditioned"); - } - - double[] empFreq = new double[stateCount]; - - for(int i = 0; i < stateCount; i++){ - empFreq[i] = getOneTransitionProbabilityEntry(Double.MAX_VALUE, i, i); - //System.out.println(empFreq[i]); - } - - this.freqModel = new FrequencyModel(dataType, empFreq); - }*/ - - - public double[] getRates(){ - return super.getRates(); - } - - /*public void computeStationaryDistribution(){ - super.computeStationaryDistribution(); - }*/ - - public abstract void setupInfinitesimalRates(); - - public double[][] getInfinitesimalRates(){ - return infinitesimalRateMatrix; - } - - public double getLogOneTransitionProbabilityEntry(double distance, int parentState, int childState){ - return Math.log(getOneTransitionProbabilityEntry(distance, parentState, childState)); - } - - public double getOneTransitionProbabilityEntry(double distance, int parentState, int childState){ - if(dataType.isAmbiguousState(childState)){ - return 1.0; - } - - double probability = 0.0; - double temp; - - synchronized (this) { - if (updateMatrix) { - setupMatrix(); - } - } - - if (!wellConditioned) { - - //throw new RuntimeException("not well conditioned"); - return 0.0; - } - - double [] iexp = new double[stateCount]; - for(int i = 0; i < stateCount; i++){ - if(EvalImag[i] == 0){ - temp = Math.exp(distance*(Eval[i])); - iexp[i] = temp*Ievc[i][childState]; - - }else{ - int i2 = i + 1; - double b = EvalImag[i]; - double expat = Math.exp(distance * Eval[i]); - double expatcosbt = expat * Math.cos(distance * b); - double expatsinbt = expat * Math.sin(distance * b); - iexp[i] = expatcosbt * Ievc[i][childState] + expatsinbt * Ievc[i2][childState]; - iexp[i2] = expatcosbt * Ievc[i2][childState] - expatsinbt * Ievc[i][childState]; - i ++; - - } - } - for(int i = 0; i < stateCount; i++){ - probability += Evec[parentState][i]*iexp[i]; - } - - if(probability <= 0.0){ - probability = minProb; - } - - return probability; - } - - public double[] getColTransitionProbabilities(double distance, int childState){ - - double[] probability = new double[stateCount]; - double temp; - - synchronized (this) { - if (updateMatrix) { - setupMatrix(); - } - } - - if (!wellConditioned) { - - //throw new RuntimeException("not well conditioned"); - return probability; - } - - double [] iexp = new double[stateCount]; - for(int i = 0; i < stateCount; i++){ - if(EvalImag[i] == 0){ - temp = Math.exp(distance*(Eval[i])); - iexp[i] = temp*Ievc[i][childState]; - - }else{ - int i2 = i + 1; - double b = EvalImag[i]; - double expat = Math.exp(distance * Eval[i]); - double expatcosbt = expat * Math.cos(distance * b); - double expatsinbt = expat * Math.sin(distance * b); - iexp[i] = expatcosbt * Ievc[i][childState] + expatsinbt * Ievc[i2][childState]; - iexp[i2] = expatcosbt * Ievc[i2][childState] - expatsinbt * Ievc[i][childState]; - i ++; - - } - } - for(int i = 0; i < stateCount; i++){ - for(int j = 0; j < stateCount; j++){ - probability[i] += Evec[i][j]*iexp[j]; - - } - if(probability[i] <= 0.0){ - probability[i] = minProb; - } - } - - return probability; - } - public double[] getRowTransitionProbabilities(double distance, int parentState){ - - double[] probability = new double[stateCount]; - double temp; - - synchronized (this) { - if (updateMatrix) { - setupMatrix(); - } - } - - if (!wellConditioned) { - - //throw new RuntimeException("not well conditioned"); - return probability; - } - - int i,j; - double[][] iexp = new double[stateCount][stateCount]; - - for (i = 0; i < stateCount; i++) { - - if (EvalImag[i] == 0) { - // 1x1 block - temp = Math.exp(distance * Eval[i]); - for (j = 0; j < stateCount; j++) { - iexp[i][j] = Ievc[i][j] * temp; - } - } else { - // 2x2 conjugate block - // If A is 2x2 with complex conjugate pair eigenvalues a +/- bi, then - // exp(At) = exp(at)*( cos(bt)I + \frac{sin(bt)}{b}(A - aI)). - int i2 = i + 1; - double b = EvalImag[i]; - double expat = Math.exp(distance * Eval[i]); - double expatcosbt = expat * Math.cos(distance * b); - double expatsinbt = expat * Math.sin(distance * b); - - for (j = 0; j < stateCount; j++) { - iexp[i][j] = expatcosbt * Ievc[i][j] + expatsinbt * Ievc[i2][j]; - iexp[i2][j] = expatcosbt * Ievc[i2][j] - expatsinbt * Ievc[i][j]; - } - i++; // processed two conjugate rows - } - } - for(i = 0; i < stateCount; i++){ - for(j = 0; j < stateCount; j++){ - probability[i] += Evec[parentState][j]*iexp[j][i]; - - } - if(probability[i] <= 0.0){ - probability[i] = minProb; - } - } - - return probability; - } - /* - * The One Phase Models are special cases of the birth-death chain, - * and therefore we can use this to calculate the stationay distribution - * given a infinitesimal rate matrix. - */ - public void computeOnePhaseStationaryDistribution(){ - double[] pi = new double[stateCount]; - - pi[0] = 1.0; - double piSum = 1.0; - for(int i = 1; i < stateCount; i++){ - pi[i] = pi[i-1]*infinitesimalRateMatrix[i-1][i]/infinitesimalRateMatrix[i][i-1]; - piSum = piSum+pi[i]; - } - - for(int i = 0; i < stateCount; i++){ - pi[i] = pi[i]/piSum; - //System.out.println(pi[i]); - - } - freqModel = new FrequencyModel(dataType,pi); - - - } - - public void setupMatrix(){ - setupInfinitesimalRates(); - super.setupMatrix(); - } - - - public MicrosatelliteModel getSubmodel(){ - return subModel; - } - - public boolean isSubmodel(){ - return isNested; - } - - public boolean hasSubmodel(){ - return subModel != null; - } - - - public boolean isModelUpdated(){ - return true; - } - -} \ No newline at end of file diff --git a/src/dr/oldevomodel/substmodel/MsatBMA.java b/src/dr/oldevomodel/substmodel/MsatBMA.java deleted file mode 100644 index f9a279f598..0000000000 --- a/src/dr/oldevomodel/substmodel/MsatBMA.java +++ /dev/null @@ -1,265 +0,0 @@ -/* - * MsatBMA.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.substmodel; - -import dr.inference.model.Parameter; -import dr.inference.model.Variable; -import dr.evolution.datatype.Microsatellite; - -import java.util.Map; -import java.util.ArrayList; - -/** - * @author Chieh-Hsi Wu - * - * This class is used for model averaging over a subset of microsatellite models. - */ -public class MsatBMA extends MicrosatelliteModel{ - private boolean logit; - public static final int PROP_INDEX = 0; - public static final int QUAD_INDEX = 1; - public static final int BIAS_CONST_INDEX = 2; - public static final int BIAS_LIN_INDEX = 3; - public static final int GEO_INDEX = 4; - public static final int PHASE_PROB_INDEX = 5; - public static final double DEFAULT_VALUE = 0.0; - public static final int PARAMETER_PRESENT = 1; - - public Parameter[][] paramModelMap; - public Map modelMap; - public Parameter modelChoose; - public Parameter modelIndicator; - - public ArrayList propRates = new ArrayList(); - public ArrayList quadRates = new ArrayList(); - public ArrayList biasConsts = new ArrayList(); - public ArrayList biasLins = new ArrayList(); - public ArrayList geos = new ArrayList(); - public ArrayList phaseProb = new ArrayList(); - - public MsatBMA( - Microsatellite msat, - boolean logit, - ArrayList propRates, - ArrayList quadRates, - ArrayList biasConsts, - ArrayList biasLins, - ArrayList geos, - ArrayList phaseProb, - Parameter[][] paramModelMap, - Parameter modelChoose, - Parameter modelIndicator, - Map modelMap){ - - super("MsatAveragingModel",msat, null, null); - - for(int i = 0; i < propRates.size(); i++){ - addVariable(propRates.get(i)); - } - - for(int i = 0; i < quadRates.size(); i++){ - addVariable(quadRates.get(i)); - } - - for(int i = 0; i < biasConsts.size(); i++){ - addVariable(biasConsts.get(i)); - - } - - for(int i = 0; i < biasLins.size(); i++){ - addVariable(biasLins.get(i)); - } - - for(int i = 0; i < geos.size(); i++){ - addVariable(geos.get(i)); - } - - for(int i = 0; i < phaseProb.size();i++){ - addVariable(phaseProb.get(i)); - } - - addVariable(modelChoose); - addVariable(modelIndicator); - this.propRates = propRates; - this.biasConsts = biasConsts; - this.biasLins = biasLins; - this.geos = geos; - - this.logit = logit; - this.modelChoose = modelChoose; - this.modelIndicator = modelIndicator; - this.paramModelMap = paramModelMap; - this.modelMap = modelMap; - - setupInfinitesimalRates(); - setupMatrix(); - - - } - - - protected void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) { - modelUpdate = false; - int paramIndex = -1; - if(propRates.contains(variable)){ - paramIndex = PROP_INDEX; - }else if(quadRates.contains(variable)){ - paramIndex = QUAD_INDEX; - }else if(biasConsts.contains(variable)){ - paramIndex = BIAS_CONST_INDEX; - }else if(biasLins.contains(variable)){ - paramIndex = BIAS_LIN_INDEX; - }else if(geos.contains(variable)){ - paramIndex = GEO_INDEX; - }else if(phaseProb.contains(variable)){ - paramIndex = PHASE_PROB_INDEX; - } - //System.out.println("changeModel: "+ variable); - if(paramIndex > -1){ - //System.out.println(modelMap); - //System.out.println(getBitVectorValue()); - if(paramModelMap[paramIndex][modelMap.get(getBitVectorValue())] != null){ - updateMatrix = true; - modelUpdate = true; - - } - - }else if(variable == modelChoose){ - updateMatrix = true; - indicateModel(); - modelUpdate = true; - - } - - - } - - public void indicateModel(){ - modelIndicator.setParameterValueQuietly(0, modelMap.get(getBitVectorValue())); - } - - public void setupInfinitesimalRates(){ - double rowSum; - double prop = DEFAULT_VALUE; - double quad = DEFAULT_VALUE; - double biasConst = DEFAULT_VALUE; - double biasLin = DEFAULT_VALUE; - double geo = DEFAULT_VALUE; - double phaseProb = DEFAULT_VALUE; - - infinitesimalRateMatrix = new double[stateCount][stateCount]; - - //if the rate proportional parameter is present - if((int)modelChoose.getParameterValue(PROP_INDEX) == PARAMETER_PRESENT){ - // - prop = getModelParameterValue(PROP_INDEX); - if((int)modelChoose.getParameterValue(QUAD_INDEX) == PARAMETER_PRESENT){ - quad = getModelParameterValue(QUAD_INDEX); - } - } - for(int i = 0; i < stateCount;i++){ - rowSum = 0.0; - if(i - 1 > -1){ - infinitesimalRateMatrix[i][i - 1] = 1+prop*i; - rowSum = rowSum + infinitesimalRateMatrix[i][i - 1]; - } - - if(i + 1 < stateCount){ - infinitesimalRateMatrix[i][i + 1] = 1+prop*i; - rowSum = rowSum + infinitesimalRateMatrix[i][i + 1]; - } - infinitesimalRateMatrix[i][i] = -rowSum; - - } - - if((int)modelChoose.getParameterValue(BIAS_CONST_INDEX) == PARAMETER_PRESENT){ - - biasConst = getModelParameterValue(BIAS_CONST_INDEX); - //System.out.print("biasConst: "+biasConst); - if((int)modelChoose.getParameterValue(BIAS_LIN_INDEX) == PARAMETER_PRESENT){ - biasLin = getModelParameterValue(BIAS_LIN_INDEX); - //System.out.print("biasLin: "+biasLin); - } - - double[][] subRates = infinitesimalRateMatrix; - infinitesimalRateMatrix = new double[stateCount][stateCount]; - - LinearBiasModel.setupInfinitesimalRates( - infinitesimalRateMatrix, - subRates, - biasConst, - biasLin, - stateCount, - logit - ); - } - - if((int)modelChoose.getParameterValue(GEO_INDEX) == PARAMETER_PRESENT){ - geo = getModelParameterValue(GEO_INDEX); - if((int)modelChoose.getParameterValue(PHASE_PROB_INDEX) == PARAMETER_PRESENT){ - phaseProb = getModelParameterValue(PHASE_PROB_INDEX); - } - double[][] subRates = infinitesimalRateMatrix; - infinitesimalRateMatrix = new double[stateCount][stateCount]; - - TwoPhaseModel.setupInfinitesimalRates( - stateCount, - geo, - phaseProb, - infinitesimalRateMatrix, - subRates - ); - } - } - - private double getModelParameterValue(int paramIndex){ - int modelCode = modelMap.get(getBitVectorValue()); - return (paramModelMap[paramIndex][modelCode]).getParameterValue(0); - - } - - private int getBitVectorValue(){ - String bitVec = ""; - for(int i = 0; i < modelChoose.getDimension(); i++){ - bitVec = bitVec + (int)modelChoose.getParameterValue(i); - } - - - return Integer.parseInt(bitVec,2); - } - - public void computeStationaryDistribution(){ - if((int)modelChoose.getParameterValue(GEO_INDEX) == PARAMETER_PRESENT){ - computeTwoPhaseStationaryDistribution(); - }else{ - computeOnePhaseStationaryDistribution(); - } - super.computeStationaryDistribution(); - } - -} diff --git a/src/dr/oldevomodel/substmodel/MutationDeathModel.java b/src/dr/oldevomodel/substmodel/MutationDeathModel.java deleted file mode 100644 index 4215b299a0..0000000000 --- a/src/dr/oldevomodel/substmodel/MutationDeathModel.java +++ /dev/null @@ -1,178 +0,0 @@ -/* - * MutationDeathModel.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -/** - * Package: MutationDeathModel - * Description: - * - * - * Created by - * Alexander V. Alekseyenko (alexander.alekseyenko@gmail.com) - * Date: Feb 19, 2008 - * Time: 12:41:01 PM - */ - -package dr.oldevomodel.substmodel; - -import dr.evolution.datatype.DataType; -import dr.oldevomodelxml.substmodel.MutationDeathModelParser; -import dr.inference.model.Model; -import dr.inference.model.Parameter; - -public class MutationDeathModel extends AbstractSubstitutionModel { - private AbstractSubstitutionModel CTMCModel; - private Parameter delParameter = null; - protected double[] trMatrix; - private Parameter baseSubModelFreq; - private Parameter thisSubModelFreq; - private Parameter mutationRate; - - - public MutationDeathModel(Parameter delParameter, DataType dT, AbstractSubstitutionModel evoModel, - FrequencyModel freqModel, Parameter mutationRate) { - super(MutationDeathModelParser.MD_MODEL, dT, freqModel); - CTMCModel = evoModel; - stateCount = freqModel.getFrequencyCount(); - this.delParameter = delParameter; - this.dataType = dT; - this.mutationRate = mutationRate; - - addVariable(delParameter); - delParameter.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, 0.0, 1)); - - addVariable(mutationRate); -// addModel(freqModel); - if (evoModel != null) { - addModel(evoModel.getFrequencyModel()); - addModel(evoModel); - } - trMatrix = new double[(stateCount - 1) * (stateCount - 1)]; - - if (CTMCModel != null) { - baseSubModelFreq = CTMCModel.getFrequencyModel().getFrequencyParameter(); - } else { - baseSubModelFreq = new Parameter.Default(new double[]{1.0}); - } - thisSubModelFreq = getFrequencyModel().getFrequencyParameter(); - - double total = 0; - for (int i = 0; i < baseSubModelFreq.getDimension(); i++) { - double value = thisSubModelFreq.getParameterValue(i); - total += value; - baseSubModelFreq.setParameterValue(i, value); - } - - for (int i = 0; i < baseSubModelFreq.getDimension(); i++) { - baseSubModelFreq.setParameterValue(i, baseSubModelFreq.getParameterValue(i) / total); - } - - thisSubModelFreq.setParameterValue(thisSubModelFreq.getDimension() - 1, 0.0); - - copyFrequencies(); - - frequenciesChanged(); - ratesChanged(); - setupRelativeRates(); - } - - public Parameter getDeathParameter() { - return this.delParameter; - } - - protected void storeState() { - } - - protected void restoreState() { - } - - protected void handleModelChangedEvent(Model model, Object object, int index) { - - if (object == baseSubModelFreq) { - copyFrequencies(); - fireModelChanged(object, index); - } else if (model == CTMCModel) { - fireModelChanged(object, index); - } - } - - private void copyFrequencies() { - for (int i = 0; i < baseSubModelFreq.getDimension(); i++) - thisSubModelFreq.setParameterValueQuietly(i, baseSubModelFreq.getParameterValue(i)); - - } - - @Override - protected void frequenciesChanged() { - } - - @Override - protected void ratesChanged() { - } - - @Override - protected void setupRelativeRates() { - } - - public void getTransitionProbabilities(double distance, double[] matrix) { - int i, j; - // assuming that expected number of changes in CTMCModel is 1 per unit time - // we are contributing s*deathRate number of changes per unit of time - double deathProb = Math.exp(-distance * delParameter.getParameterValue(0)); - double mutationR = 2 * mutationRate.getParameterValue(0); - double freqs[] = freqModel.getFrequencyParameter().getParameterValues(); - - for (i = 0; i < freqs.length - 1; ++i) { - mutationR *= freqs[i]; - } - if (CTMCModel != null) { - CTMCModel.getTransitionProbabilities(mutationR * distance, trMatrix); - } else { - trMatrix[0] = 1.0; - } - - for (i = 0; i < stateCount - 1; ++i) { - for (j = 0; j < stateCount - 1; j++) { - matrix[i * (stateCount) + j] = trMatrix[i * (stateCount - 1) + j] * deathProb; - } - matrix[i * (stateCount) + j] = (1.0 - deathProb); - } - - for (j = 0; j < stateCount - 1; ++j) { - matrix[stateCount * (stateCount - 1) + j] = 0.0; - } - - matrix[stateCount * stateCount - 1] = 1.0; -/* System.err.println("Transition matrix t = "+distance); - for(i=0;i logKappa = null; - private Variable logTN = null; - private Variable logAC = null; - private Variable logAT = null; - private Variable logGC = null; - private Variable logGT = null; - private Variable modelChoose = null; - - public static final int TN_INDEX = 0; - public static final int GTR_INDEX = 1; - - public static final int ABSENT = 0; - public static final int PRESENT = 1; - - public NtdBMA( - Variable logKappa, - Variable logTN, - Variable logAC, - Variable logAT, - Variable logGC, - Variable logGT, - Variable modelChoose, - FrequencyModel freqModel){ - super("NucleotideBMA", freqModel); - - - addVariable(logKappa); - logKappa.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, 1)); - this.logKappa = logKappa; - - addVariable(logTN); - logTN.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, 1)); - this.logTN = logTN; - - addVariable(logAC); - logAC.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, 1)); - this.logAC = logAC; - - addVariable(logAT); - logAT.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, 1)); - this.logAT = logAT; - - addVariable(logGC); - logGC.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, 1)); - this.logGC = logGC; - - addVariable(logGT); - logGT.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, 1)); - this.logGT = logGT; - - addVariable(modelChoose); - modelChoose.addBounds(new Bounds.Int(modelChoose, 0, 1)); - - - this.modelChoose = modelChoose; - } - - protected void setupRelativeRates() { - - //rate AG value - relativeRates[1] = Math.exp(logKappa.getValue(0)+modelChoose.getValue(TN_INDEX)*logTN.getValue(0)); - //rate CT value - relativeRates[4] = Math.exp(logKappa.getValue(0)-modelChoose.getValue(TN_INDEX)*logTN.getValue(0)); - //rate AC value - relativeRates[0] = Math.exp(modelChoose.getValue(GTR_INDEX)*logAC.getValue(0)); - //rate AT value - relativeRates[2] = Math.exp(modelChoose.getValue(GTR_INDEX)*logAT.getValue(0)); - //rate GC value - relativeRates[3] = Math.exp(modelChoose.getValue(GTR_INDEX)*logGC.getValue(0)); - //rate GT value - relativeRates[5] = Math.exp(modelChoose.getValue(GTR_INDEX)*logGT.getValue(0)); - - } - - protected void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) { - boolean changeRateMatrix = false; - - if(variable == modelChoose){ - //changing the substitution model - changeRateMatrix = true; - }else if(variable == logKappa){ - //changing kappa value (which is in all models) - changeRateMatrix = true; - }else if(variable == logTN && modelChoose.getValue(TN_INDEX) == PRESENT){ - //changing the tn value when the current model is TN. - changeRateMatrix = true; - }else if(variable == logAC || - variable == logAT || - variable == logGC || - variable == logGT && - modelChoose.getValue(GTR_INDEX) == PRESENT && modelChoose.getValue(TN_INDEX) == PRESENT){ - //Changing any one of A<->C, A<->T, G<->C, G<->T rates while the current model is GTR. - changeRateMatrix = true; - } - // relativeRates changed - if(changeRateMatrix){ - super.handleVariableChangedEvent(variable, index, type); - } - changeRateMatrix = false; - } - -} diff --git a/src/dr/oldevomodel/substmodel/NucModelType.java b/src/dr/oldevomodel/substmodel/NucModelType.java deleted file mode 100644 index 7ed1f64359..0000000000 --- a/src/dr/oldevomodel/substmodel/NucModelType.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * NucModelType.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.substmodel; - -/** - * @author Alexei Drummond - */ -public enum NucModelType { - - JC, HKY, GTR, TN93; - - public final String getXMLName() { - return name() + "Model"; - } - - public String toString() { - return name(); - } -} diff --git a/src/dr/oldevomodel/substmodel/OnePhaseModel.java b/src/dr/oldevomodel/substmodel/OnePhaseModel.java deleted file mode 100644 index ad5ac45d53..0000000000 --- a/src/dr/oldevomodel/substmodel/OnePhaseModel.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * OnePhaseModel.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.substmodel; - -import dr.evolution.datatype.Microsatellite; -import dr.inference.model.Parameter; -import dr.inference.model.Variable; - -import java.util.ArrayList; - - -/** - * @author Chieh-Hsi Wu - * - * An abstract for One Phase Microsatellite Models - */ -public abstract class OnePhaseModel extends MicrosatelliteModel{ - protected ArrayList> nestedParams = null; - - /** - * Constructor - * - * @param name Model name - * @param microsatellite Microsatellite data type - * @param freqModel Equilibrium frequencies - * @param parameter Infinitesimal rates - */ - public OnePhaseModel(String name, Microsatellite microsatellite, FrequencyModel freqModel, Parameter parameter){ - super(name, microsatellite, freqModel, parameter); - nestedParams=new ArrayList>(); - } - - /* - * adding the parameters only if its not a submodel. - */ - protected void addParam(Variable param){ - if(isNested){ - nestedParams.add(param); - }else{ - super.addVariable(param); - } - } - - /* - * get the parameters in this submodel - */ - public Variable getNestedParameter(int i){ - return nestedParams.get(i); - } - - /* - * get number of nested parameters in the submodel - */ - public int getNestedParameterCount(){ - return nestedParams.size(); - } - - /* - * The One Phase Models are special cases of the birth-death chain, - * and therefore we can use this to calculate the stationay distribution - * given a infinitesimal rate matrix. - */ - public void computeStationaryDistribution(){ - if(useStationaryFreqs){ - computeOnePhaseStationaryDistribution(); - } - super.computeStationaryDistribution(); - - } - - -} diff --git a/src/dr/oldevomodel/substmodel/PCACodonModel.java b/src/dr/oldevomodel/substmodel/PCACodonModel.java deleted file mode 100644 index b9612cb0f7..0000000000 --- a/src/dr/oldevomodel/substmodel/PCACodonModel.java +++ /dev/null @@ -1,173 +0,0 @@ -/* - * PCACodonModel.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.substmodel; - -import dr.evolution.datatype.Codons; -import dr.oldevomodelxml.substmodel.PCACodonModelParser; -import dr.inference.model.Parameter; - -/** - * PCA model of codon evolution - * - * @author Stefan Zoller - */ -public class PCACodonModel extends AbstractCodonModel { - // principal components, means, scale factors - protected AbstractPCARateMatrix rateMatrix; - - protected byte[] rateMap; - - private Parameter pcFactors; - - /** - * constructor - * - * @param codonDataType Data type as Codons.UNIVERSAL - * @param pcaType Rate matrix with PCs, means, scale factors - * @param pcaDimensionParameter Scalars for PCs - * @param freqModel Frequency model - */ - public PCACodonModel(Codons codonDataType, - AbstractPCARateMatrix pcaType, - Parameter pcaDimensionParameter, - FrequencyModel freqModel) - { - super(PCACodonModelParser.PCA_CODON_MODEL, codonDataType, freqModel); - - this.rateMatrix = pcaType; - - // initialize scalars for principal components - this.pcFactors = pcaDimensionParameter; - double[] startFacs = pcaType.getStartFacs(); - double facSum = 0.0; - for(int i=0; iPCA Codon Model"); - - return buffer.toString(); - } - - - static String format1 = "%2.1e"; - static String format2 = "%2.4e"; - - public String printQ() { - double[][] myQ = getQ(); - if (myQ != null) { - StringBuffer sb = new StringBuffer(); - for (int i = 0; i < myQ.length; i++) { - for(int j = 0; j < myQ[0].length; j++) { - sb.append(String.format(format1, myQ[i][j])); - sb.append("\t"); - } - sb.append("\n"); - } - return sb.toString(); - } else { - return "No Q ready."; - } - } - - public String printRelRates() { - StringBuffer sb = new StringBuffer(); - for (int i = 0; i < relativeRates.length; i++) { - sb.append(String.format(format2, relativeRates[i])); - sb.append("\t"); - } - sb.append("\n"); - return sb.toString(); - } -} diff --git a/src/dr/oldevomodel/substmodel/PCARateMatrixMammalia.java b/src/dr/oldevomodel/substmodel/PCARateMatrixMammalia.java deleted file mode 100644 index 3b224414b5..0000000000 --- a/src/dr/oldevomodel/substmodel/PCARateMatrixMammalia.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * PCARateMatrixMammalia.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.substmodel; - -import dr.evolution.datatype.Codons; -import java.util.*; -import java.io.*; - -/** - * Mammalia rate matrix for PCACodonModel - * - * @author Stefan Zoller - * - */ -public class PCARateMatrixMammalia extends AbstractPCARateMatrix{ - - // filenames for csv files including actual rate matrices - public static final String FREQS_FILE = "freqs.csv"; - public static final String SCALES_FILE = "scales.csv"; - public static final String MEANS_FILE = "means.csv"; - public static final String FACTORS_FILE = "startfacs.csv"; - public static final String PCS_FILE = "pcs.csv"; - - /** - * constructor - * - * @param nrOfPCs Number of PCs to use - * @param dir Directory which includes the rate matrix csv files - */ - public PCARateMatrixMammalia(int nrOfPCs, String dir) { - super("mammalia", Codons.UNIVERSAL, dir); - - // reading data files: - setupMeans(); - setupFreqs(); - setupScales(); - setupStartFacs(); - setupPCs(nrOfPCs); - } - - private void setupFreqs() { - // 61 frequencies for the codons - double[] f = readSingleArray(FREQS_FILE, 61); - setFrequencies(f); - } - - private void setupScales() { - // 1830 scale factors for the PCs - double[] s = readSingleArray(SCALES_FILE, 1830); - setScales(s); - } - - private void setupMeans() { - // 1830 mean values for the PCs - double[] m = readSingleArray(MEANS_FILE, 1830); - setMeans(m); - } - - private void setupStartFacs() { - // 1830 start factors for the PCs - double[] sf = readSingleArray(FACTORS_FILE, 1830); - setStartFacs(sf); - } - - private void setupPCs(int nr) { - double[][] p = new double[nr][1830]; - - File file = new File(dataDir, PCS_FILE); - - try { - BufferedReader bufRdr = new BufferedReader(new FileReader(file)); - - String line = null; - int row = 0; - int col = 0; - - //read each line of text file - while(((line = bufRdr.readLine()) != null) && (row < nr)) - { - col = 0; - StringTokenizer st = new StringTokenizer(line,","); - while (st.hasMoreTokens()) - { - //get next token and store it in the array - p[row][col] = Double.valueOf(st.nextToken()).doubleValue(); - col++; - } - row++; - } - bufRdr.close(); - } catch (FileNotFoundException e) { - System.err.println("Caught FileNotFoundException: " + e.getMessage()); - } catch (IOException e) { - System.err.println("Caught IOException: " + e.getMessage()); - } finally { - } - setPCs(p); - } - - private double[] readSingleArray(String filename, int dim) { - File file = new File(dataDir, filename); - double[] arr = new double[dim]; - - try { - BufferedReader bufRdr = new BufferedReader(new FileReader(file)); - String line = null; - int col = 0; - - while((line = bufRdr.readLine()) != null) { - StringTokenizer st = new StringTokenizer(line,","); - while (st.hasMoreTokens()) { - arr[col] = Double.valueOf(st.nextToken()).doubleValue(); - col++; - } - } - bufRdr.close(); - } catch (FileNotFoundException e) { - System.err.println("Caught FileNotFoundException: " + e.getMessage()); - } catch (IOException e) { - System.err.println("Caught IOException: " + e.getMessage()); - } finally { - } - return arr; - } -} diff --git a/src/dr/oldevomodel/substmodel/PositiveDefiniteSubstitutionModel.java b/src/dr/oldevomodel/substmodel/PositiveDefiniteSubstitutionModel.java deleted file mode 100644 index b03f3a6c56..0000000000 --- a/src/dr/oldevomodel/substmodel/PositiveDefiniteSubstitutionModel.java +++ /dev/null @@ -1,982 +0,0 @@ -/* - * PositiveDefiniteSubstitutionModel.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.substmodel; - -import dr.evolution.datatype.DataType; -import dr.oldevomodelxml.substmodel.PositiveDefiniteSubstitutionModelParser; -import dr.inference.loggers.LogColumn; -import dr.inference.loggers.Loggable; -import dr.inference.loggers.NumberColumn; -import dr.inference.model.*; -import dr.math.MachineAccuracy; -import dr.math.matrixAlgebra.Matrix; - -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -/** - * A general model of sequence substitution with stochastic variable selection. A general reversible class for any - * data type. - * - * @author Marc Suchard - */ - -public class PositiveDefiniteSubstitutionModel extends AbstractModel implements SubstitutionModel, Loggable { - - protected DataType dataType = null; - - protected FrequencyModel freqModel; - protected double[] relativeRates; - protected double[] storedRelativeRates; - - protected int stateCount; - protected final int Ksquared; - protected int rateCount; - - private boolean eigenInitialised = false; - protected boolean updateMatrix = true; - private boolean storedUpdateMatrix = true; - - private boolean precalculatedTimes = false; - Map mapTimes; - - public PositiveDefiniteSubstitutionModel(MatrixParameter parameter) { - super(PositiveDefiniteSubstitutionModelParser.SVS_GENERAL_SUBSTITUTION_MODEL); - - stateCount = parameter.getRowDimension(); - Ksquared = stateCount * stateCount; - - rates = parameter; - addVariable(rates); - - eigenInitialised = false; - } - - public MatrixParameter getRates() { - return rates; - } - - public void addPrecalculatedTime(double time) { - if (mapTimes == null) - mapTimes = new HashMap(); - if (!mapTimes.containsKey(time)) { - mapTimes.put(time, mapTimes.size()); - expQt = new double[Ksquared * mapTimes.size()]; - storedExpQt = new double[Ksquared * mapTimes.size()]; - setupMatrix(); - updatePrecalculatedTimes(); - } - precalculatedTimes = true; - } - - private double[] expQt; - private double[] storedExpQt; - - private void updatePrecalculatedTimes() { - - double[] tempW = new double[Ksquared]; - - for (double deltaTime : mapTimes.keySet()) { - getRawTransitionProbabilities(deltaTime, tempW); - System.arraycopy(tempW, 0, expQt, Ksquared * mapTimes.get(deltaTime), Ksquared); - } - } - - // ***************************************************************** - // Interface Model - // ***************************************************************** - - protected void handleModelChangedEvent(Model model, Object object, int index) { - updateMatrix = true; - assert false; // no submodels - } - - protected final void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) { - updateMatrix = true; - ratesChanged(); - } - - protected void storeState() { - - storedUpdateMatrix = updateMatrix; - - System.arraycopy(Eval, 0, storedEval, 0, stateCount); - for (int i = 0; i < stateCount; i++) { - System.arraycopy(Ievc[i], 0, storedIevc[i], 0, stateCount); - System.arraycopy(Evec[i], 0, storedEvec[i], 0, stateCount); - } - - System.arraycopy(expQt, 0, storedExpQt, 0, Ksquared * mapTimes.size()); - - } - - /** - * Restore the additional stored state - */ - protected void restoreState() { - - updateMatrix = storedUpdateMatrix; - - // To restore all this stuff just swap the pointers... - double[] tmp1 = storedRelativeRates; - storedRelativeRates = relativeRates; - relativeRates = tmp1; - - tmp1 = storedEval; - storedEval = Eval; - Eval = tmp1; - - double[][] tmp2 = storedIevc; - storedIevc = Ievc; - Ievc = tmp2; - - tmp2 = storedEvec; - storedEvec = Evec; - Evec = tmp2; - - tmp1 = storedExpQt; - storedExpQt = expQt; - expQt = tmp1; - - } - - protected void acceptState() { - } // nothing to do - - - protected void ratesChanged() { - } - - protected void setupRelativeRates() { - } - - - public void getTransitionProbabilities(double distance, double[] matrix) { - - synchronized (this) { - if (updateMatrix) { - setupMatrix(); - if (precalculatedTimes) - updatePrecalculatedTimes(); - } - } - - if (precalculatedTimes && mapTimes.containsKey(distance)) { - System.arraycopy(expQt, Ksquared * mapTimes.get(distance), matrix, 0, Ksquared); - -// assert checkPrecomputedAndRawValues(distance,matrix); - - } else - getRawTransitionProbabilities(distance, matrix); - } - - public double[][] getEigenVectors() { - throw new UnsupportedOperationException("Not yet implemented."); - } - - public double[][] getInverseEigenVectors() { - throw new UnsupportedOperationException("Not yet implemented."); - } - - public double[] getEigenValues() { - throw new UnsupportedOperationException("Not yet implemented."); - } - - private boolean checkPrecomputedAndRawValues(double distance, double[] precalculated) { - double[] compare = new double[Ksquared]; - getRawTransitionProbabilities(distance, compare); - for (int i = 0; i < precalculated.length; i++) { - if (precalculated[i] != compare[i]) - return false; - } - return true; - } - - /** - * get the complete transition probability matrix for the given distance - * - * @param distance the expected number of substitutions - * @param matrix an array to store the matrix - */ - public void getRawTransitionProbabilities(double distance, double[] matrix) { - int i, j, k; - double temp; - - // implemented a pool of iexp matrices to support multiple threads - // without creating a new matrix each call. - AJD - double[][] iexp = popiexp(); - for (i = 0; i < stateCount; i++) { - temp = Math.exp(distance * Eval[i]); - for (j = 0; j < stateCount; j++) { - iexp[i][j] = Ievc[i][j] * temp; - } - } - - int u = 0; - for (i = 0; i < stateCount; i++) { - for (j = 0; j < stateCount; j++) { - temp = 0.0; - for (k = 0; k < stateCount; k++) { - temp += Evec[i][k] * iexp[k][j]; - } - - //matrix[u] = Math.abs(temp); - matrix[u] = temp; - u++; - } - } - pushiexp(iexp); - } - - public FrequencyModel getFrequencyModel() { - return null; //To change body of implemented methods use File | Settings | File Templates. - } - - public DataType getDataType() { - return new MyDataType(stateCount); - } - - public LogColumn[] getColumns() { - LogColumn[] columns = new LogColumn[stateCount * stateCount]; - for (int i = 0; i < stateCount * stateCount; i++) - columns[i] = new ProbabilityColumn(getId() + (i + 1), i); - return columns; - } - - private class ProbabilityColumn extends NumberColumn { - - private int index; - private double[] matrix; - - public ProbabilityColumn(String label, int index) { - super(label); - this.index = index; - matrix = new double[stateCount * stateCount]; - } - - public double getDoubleValue() { - getTransitionProbabilities(0, matrix); - return matrix[index]; - } - } - - private class MyDataType extends DataType { - - MyDataType(int count) { - stateCount = count; - } - - @Override - public char[] getValidChars() { - return null; - } - - public String getDescription() { - return null; //To change body of implemented methods use File | Settings | File Templates. - } - - public int getType() { - return stateCount; //To change body of implemented methods use File | Settings | File Templates. - } - } - - /** - * setup substitution matrix - */ - protected void setupMatrix() { - - if (!eigenInitialised) - initialiseEigen(); - - int i, j, k = 0; - - amat = new Matrix(rates.getParameterAsMatrix()).inverse().toComponents(); - - // copy q matrix for unit testing - for (i = 0; i < amat.length; i++) { - System.arraycopy(amat[i], 0, q[i], 0, amat[i].length); - } - - // compute eigenvalues and eigenvectors - elmhes(amat, ordr, stateCount); - eltran(amat, Evec, ordr, stateCount); - hqr2(stateCount, 1, stateCount, amat, Evec, Eval, evali); - luinverse(Evec, Ievc, stateCount); - - updateMatrix = false; - } - - - /** - * allocate memory for the Eigen routines - */ - private void initialiseEigen() { - - Eval = new double[stateCount]; - Evec = new double[stateCount][stateCount]; - Ievc = new double[stateCount][stateCount]; - - storedEval = new double[stateCount]; - storedEvec = new double[stateCount][stateCount]; - storedIevc = new double[stateCount][stateCount]; - - amat = new double[stateCount][stateCount]; - q = new double[stateCount][stateCount]; - - ordr = new int[stateCount]; - evali = new double[stateCount]; - - eigenInitialised = true; - updateMatrix = true; - } - - // Eigenvalues, eigenvectors, and inverse eigenvectors - private double[] Eval; - private double[] storedEval; - private double[][] Evec; - private double[][] storedEvec; - private double[][] Ievc; - private double[][] storedIevc; - - List iexpPool = new LinkedList(); - - private int[] ordr; - private double[] evali; - double amat[][]; - double q[][]; - - private synchronized double[][] popiexp() { - - if (iexpPool.size() == 0) { - iexpPool.add(new double[stateCount][stateCount]); - } - return iexpPool.remove(0); - } - - private synchronized void pushiexp(double[][] iexp) { - iexpPool.add(0, iexp); - } - - private void elmhes(double[][] a, int[] ordr, int n) { - int m, j, i; - double y, x; - - for (i = 0; i < n; i++) { - ordr[i] = 0; - } - for (m = 2; m < n; m++) { - x = 0.0; - i = m; - for (j = m; j <= n; j++) { - if (Math.abs(a[j - 1][m - 2]) > Math.abs(x)) { - x = a[j - 1][m - 2]; - i = j; - } - } - ordr[m - 1] = i; - if (i != m) { - for (j = m - 2; j < n; j++) { - y = a[i - 1][j]; - a[i - 1][j] = a[m - 1][j]; - a[m - 1][j] = y; - } - for (j = 0; j < n; j++) { - y = a[j][i - 1]; - a[j][i - 1] = a[j][m - 1]; - a[j][m - 1] = y; - } - } - if (x != 0.0) { - for (i = m; i < n; i++) { - y = a[i][m - 2]; - if (y != 0.0) { - y /= x; - a[i][m - 2] = y; - for (j = m - 1; j < n; j++) { - a[i][j] -= y * a[m - 1][j]; - } - for (j = 0; j < n; j++) { - a[j][m - 1] += y * a[j][i]; - } - } - } - } - } - } - - // Helper variables for mcdiv - private double cr, ci; - - private void mcdiv(double ar, double ai, double br, double bi) { - double s, ars, ais, brs, bis; - - s = Math.abs(br) + Math.abs(bi); - ars = ar / s; - ais = ai / s; - brs = br / s; - bis = bi / s; - s = brs * brs + bis * bis; - cr = (ars * brs + ais * bis) / s; - ci = (ais * brs - ars * bis) / s; - } - - void hqr2(int n, int low, int hgh, double[][] h, double[][] zz, - double[] wr, double[] wi) throws ArithmeticException { - int i, j, k, l = 0, m, en, na, itn, its; - double p = 0, q = 0, r = 0, s = 0, t, w, x = 0, y, ra, sa, vi, vr, z = 0, norm, tst1, tst2; - boolean notLast; - - - norm = 0.0; - k = 1; - /* store isolated roots and compute matrix norm */ - for (i = 0; i < n; i++) { - for (j = k - 1; j < n; j++) { - norm += Math.abs(h[i][j]); - } - k = i + 1; - if (i + 1 < low || i + 1 > hgh) { - wr[i] = h[i][i]; - wi[i] = 0.0; - } - } - en = hgh; - t = 0.0; - itn = n * 30; - while (en >= low) { /* search for next eigenvalues */ - its = 0; - na = en - 1; - while (en >= 1) { - /* look for single small sub-diagonal element */ - boolean fullLoop = true; - for (l = en; l > low; l--) { - s = Math.abs(h[l - 2][l - 2]) + Math.abs(h[l - 1][l - 1]); - if (s == 0.0) { - s = norm; - } - tst1 = s; - tst2 = tst1 + Math.abs(h[l - 1][l - 2]); - if (tst2 == tst1) { - fullLoop = false; - break; - } - } - if (fullLoop) { - l = low; - } - - x = h[en - 1][en - 1]; /* form shift */ - if (l == en || l == na) { - break; - } - if (itn == 0) { - /* eigenvalues have not converged */ - System.out.println("Eigenvalues not converged"); - throw new ArithmeticException(); - } - y = h[na - 1][na - 1]; - w = h[en - 1][na - 1] * h[na - 1][en - 1]; - /* form exceptional shift */ - if (its == 10 || its == 20) { - t += x; - for (i = low - 1; i < en; i++) { - h[i][i] -= x; - } - s = Math.abs(h[en - 1][na - 1]) + Math.abs(h[na - 1][en - 3]); - x = 0.75 * s; - y = x; - w = -0.4375 * s * s; - } - its++; - itn--; - /* look for two consecutive small sub-diagonal elements */ - for (m = en - 2; m >= l; m--) { - z = h[m - 1][m - 1]; - r = x - z; - s = y - z; - p = (r * s - w) / h[m][m - 1] + h[m - 1][m]; - q = h[m][m] - z - r - s; - r = h[m + 1][m]; - s = Math.abs(p) + Math.abs(q) + Math.abs(r); - p /= s; - q /= s; - r /= s; - if (m == l) { - break; - } - tst1 = Math.abs(p) * (Math.abs(h[m - 2][m - 2]) + Math.abs(z) + Math.abs(h[m][m])); - tst2 = tst1 + Math.abs(h[m - 1][m - 2]) * (Math.abs(q) + Math.abs(r)); - if (tst2 == tst1) { - break; - } - } - for (i = m + 2; i <= en; i++) { - h[i - 1][i - 3] = 0.0; - if (i != m + 2) { - h[i - 1][i - 4] = 0.0; - } - } - for (k = m; k <= na; k++) { - notLast = k != na; - if (k != m) { - p = h[k - 1][k - 2]; - q = h[k][k - 2]; - r = 0.0; - if (notLast) { - r = h[k + 1][k - 2]; - } - x = Math.abs(p) + Math.abs(q) + Math.abs(r); - if (x != 0.0) { - p /= x; - q /= x; - r /= x; - } - } - if (x != 0.0) { - if (p < 0.0) { /* sign */ - s = -Math.sqrt(p * p + q * q + r * r); - } else { - s = Math.sqrt(p * p + q * q + r * r); - } - if (k != m) { - h[k - 1][k - 2] = -s * x; - } else if (l != m) { - h[k - 1][k - 2] = -h[k - 1][k - 2]; - } - p += s; - x = p / s; - y = q / s; - z = r / s; - q /= p; - r /= p; - if (!notLast) { - for (j = k - 1; j < n; j++) { /* row modification */ - p = h[k - 1][j] + q * h[k][j]; - h[k - 1][j] -= p * x; - h[k][j] -= p * y; - } - j = (en < (k + 3)) ? en : (k + 3); /* min */ - for (i = 0; i < j; i++) { /* column modification */ - p = x * h[i][k - 1] + y * h[i][k]; - h[i][k - 1] -= p; - h[i][k] -= p * q; - } - /* accumulate transformations */ - for (i = low - 1; i < hgh; i++) { - p = x * zz[i][k - 1] + y * zz[i][k]; - zz[i][k - 1] -= p; - zz[i][k] -= p * q; - } - } else { - for (j = k - 1; j < n; j++) { /* row modification */ - p = h[k - 1][j] + q * h[k][j] + r * h[k + 1][j]; - h[k - 1][j] -= p * x; - h[k][j] -= p * y; - h[k + 1][j] -= p * z; - } - j = (en < (k + 3)) ? en : (k + 3); /* min */ - for (i = 0; i < j; i++) { /* column modification */ - p = x * h[i][k - 1] + y * h[i][k] + z * h[i][k + 1]; - h[i][k - 1] -= p; - h[i][k] -= p * q; - h[i][k + 1] -= p * r; - } - /* accumulate transformations */ - for (i = low - 1; i < hgh; i++) { - p = x * zz[i][k - 1] + y * zz[i][k] + - z * zz[i][k + 1]; - zz[i][k - 1] -= p; - zz[i][k] -= p * q; - zz[i][k + 1] -= p * r; - } - } - } - } /* for k */ - } /* while infinite loop */ - if (l == en) { /* one root found */ - h[en - 1][en - 1] = x + t; - wr[en - 1] = h[en - 1][en - 1]; - wi[en - 1] = 0.0; - en = na; - continue; - } - y = h[na - 1][na - 1]; - w = h[en - 1][na - 1] * h[na - 1][en - 1]; - p = (y - x) / 2.0; - q = p * p + w; - z = Math.sqrt(Math.abs(q)); - h[en - 1][en - 1] = x + t; - x = h[en - 1][en - 1]; - h[na - 1][na - 1] = y + t; - if (q >= 0.0) { /* real pair */ - if (p < 0.0) { /* sign */ - z = p - Math.abs(z); - } else { - z = p + Math.abs(z); - } - wr[na - 1] = x + z; - wr[en - 1] = wr[na - 1]; - if (z != 0.0) { - wr[en - 1] = x - w / z; - } - wi[na - 1] = 0.0; - wi[en - 1] = 0.0; - x = h[en - 1][na - 1]; - s = Math.abs(x) + Math.abs(z); - p = x / s; - q = z / s; - r = Math.sqrt(p * p + q * q); - p /= r; - q /= r; - for (j = na - 1; j < n; j++) { /* row modification */ - z = h[na - 1][j]; - h[na - 1][j] = q * z + p * h[en - 1][j]; - h[en - 1][j] = q * h[en - 1][j] - p * z; - } - for (i = 0; i < en; i++) { /* column modification */ - z = h[i][na - 1]; - h[i][na - 1] = q * z + p * h[i][en - 1]; - h[i][en - 1] = q * h[i][en - 1] - p * z; - } - /* accumulate transformations */ - for (i = low - 1; i < hgh; i++) { - z = zz[i][na - 1]; - zz[i][na - 1] = q * z + p * zz[i][en - 1]; - zz[i][en - 1] = q * zz[i][en - 1] - p * z; - } - } else { /* complex pair */ - wr[na - 1] = x + p; - wr[en - 1] = x + p; - wi[na - 1] = z; - wi[en - 1] = -z; - } - en -= 2; - } /* while en >= low */ - /* backsubstitute to find vectors of upper triangular form */ - if (norm != 0.0) { - for (en = n; en >= 1; en--) { - p = wr[en - 1]; - q = wi[en - 1]; - na = en - 1; - if (q == 0.0) {/* real vector */ - m = en; - h[en - 1][en - 1] = 1.0; - if (na != 0) { - for (i = en - 2; i >= 0; i--) { - w = h[i][i] - p; - r = 0.0; - for (j = m - 1; j < en; j++) { - r += h[i][j] * h[j][en - 1]; - } - if (wi[i] < 0.0) { - z = w; - s = r; - } else { - m = i + 1; - if (wi[i] == 0.0) { - t = w; - if (t == 0.0) { - tst1 = norm; - t = tst1; - do { - t = 0.01 * t; - tst2 = norm + t; - } - while (tst2 > tst1); - } - h[i][en - 1] = -(r / t); - } else { /* solve real equations */ - x = h[i][i + 1]; - y = h[i + 1][i]; - q = (wr[i] - p) * (wr[i] - p) + wi[i] * wi[i]; - t = (x * s - z * r) / q; - h[i][en - 1] = t; - if (Math.abs(x) > Math.abs(z)) - h[i + 1][en - 1] = (-r - w * t) / x; - else - h[i + 1][en - 1] = (-s - y * t) / z; - } - /* overflow control */ - t = Math.abs(h[i][en - 1]); - if (t != 0.0) { - tst1 = t; - tst2 = tst1 + 1.0 / tst1; - if (tst2 <= tst1) { - for (j = i; j < en; j++) { - h[j][en - 1] /= t; - } - } - } - } - } - } - } else if (q > 0.0) { - m = na; - if (Math.abs(h[en - 1][na - 1]) > Math.abs(h[na - 1][en - 1])) { - h[na - 1][na - 1] = q / h[en - 1][na - 1]; - h[na - 1][en - 1] = (p - h[en - 1][en - 1]) / h[en - 1][na - 1]; - } else { - mcdiv(0.0, -h[na - 1][en - 1], h[na - 1][na - 1] - p, q); - h[na - 1][na - 1] = cr; - h[na - 1][en - 1] = ci; - } - h[en - 1][na - 1] = 0.0; - h[en - 1][en - 1] = 1.0; - if (en != 2) { - for (i = en - 3; i >= 0; i--) { - w = h[i][i] - p; - ra = 0.0; - sa = 0.0; - for (j = m - 1; j < en; j++) { - ra += h[i][j] * h[j][na - 1]; - sa += h[i][j] * h[j][en - 1]; - } - if (wi[i] < 0.0) { - z = w; - r = ra; - s = sa; - } else { - m = i + 1; - if (wi[i] == 0.0) { - mcdiv(-ra, -sa, w, q); - h[i][na - 1] = cr; - h[i][en - 1] = ci; - } else { /* solve complex equations */ - x = h[i][i + 1]; - y = h[i + 1][i]; - vr = (wr[i] - p) * (wr[i] - p); - vr = vr + wi[i] * wi[i] - q * q; - vi = (wr[i] - p) * 2.0 * q; - if (vr == 0.0 && vi == 0.0) { - tst1 = norm * (Math.abs(w) + Math.abs(q) + Math.abs(x) + - Math.abs(y) + Math.abs(z)); - vr = tst1; - do { - vr = 0.01 * vr; - tst2 = tst1 + vr; - } - while (tst2 > tst1); - } - mcdiv(x * r - z * ra + q * sa, x * s - z * sa - q * ra, vr, vi); - h[i][na - 1] = cr; - h[i][en - 1] = ci; - if (Math.abs(x) > Math.abs(z) + Math.abs(q)) { - h[i + 1] - [na - 1] = (q * h[i][en - 1] - - w * h[i][na - 1] - ra) / x; - h[i + 1][en - 1] = (-sa - w * h[i][en - 1] - - q * h[i][na - 1]) / x; - } else { - mcdiv(-r - y * h[i][na - 1], -s - y * h[i][en - 1], z, q); - h[i + 1][na - 1] = cr; - h[i + 1][en - 1] = ci; - } - } - /* overflow control */ - t = (Math.abs(h[i][na - 1]) > Math.abs(h[i][en - 1])) ? - Math.abs(h[i][na - 1]) : Math.abs(h[i][en - 1]); - if (t != 0.0) { - tst1 = t; - tst2 = tst1 + 1.0 / tst1; - if (tst2 <= tst1) { - for (j = i; j < en; j++) { - h[j][na - 1] /= t; - h[j][en - 1] /= t; - } - } - } - } - } - } - } - } - /* end back substitution. vectors of isolated roots */ - for (i = 0; i < n; i++) { - if (i + 1 < low || i + 1 > hgh) { - for (j = i; j < n; j++) { - zz[i][j] = h[i][j]; - } - } - } - /* multiply by transformation matrix to give vectors of - * original full matrix. */ - for (j = n - 1; j >= low - 1; j--) { - m = ((j + 1) < hgh) ? (j + 1) : hgh; /* min */ - for (i = low - 1; i < hgh; i++) { - z = 0.0; - for (k = low - 1; k < m; k++) { - z += zz[i][k] * h[k][j]; - } - zz[i][j] = z; - } - } - } - } - - private void eltran(double[][] a, double[][] zz, int[] ordr, int n) { - int i, j, m; - - for (i = 0; i < n; i++) { - for (j = i + 1; j < n; j++) { - zz[i][j] = 0.0; - zz[j][i] = 0.0; - } - zz[i][i] = 1.0; - } - if (n <= 2) { - return; - } - for (m = n - 1; m >= 2; m--) { - for (i = m; i < n; i++) { - zz[i][m - 1] = a[i][m - 2]; - } - i = ordr[m - 1]; - if (i != m) { - for (j = m - 1; j < n; j++) { - zz[m - 1][j] = zz[i - 1][j]; - zz[i - 1][j] = 0.0; - } - zz[i - 1][m - 1] = 1.0; - } - } - } - - void luinverse(double[][] inmat, double[][] imtrx, int size) throws IllegalArgumentException { - int i, j, k, l, maxi = 0, idx, ix, jx; - double sum, tmp, maxb, aw; - int[] index; - double[] wk; - double[][] omtrx; - - - index = new int[size]; - omtrx = new double[size][size]; - - /* copy inmat to omtrx */ - for (i = 0; i < size; i++) { - for (j = 0; j < size; j++) { - omtrx[i][j] = inmat[i][j]; - } - } - - wk = new double[size]; - aw = 1.0; - for (i = 0; i < size; i++) { - maxb = 0.0; - for (j = 0; j < size; j++) { - if (Math.abs(omtrx[i][j]) > maxb) { - maxb = Math.abs(omtrx[i][j]); - } - } - if (maxb == 0.0) { - /* Singular matrix */ - System.out.println("Singular matrix encountered"); - throw new IllegalArgumentException("Singular matrix"); - } - wk[i] = 1.0 / maxb; - } - for (j = 0; j < size; j++) { - for (i = 0; i < j; i++) { - sum = omtrx[i][j]; - for (k = 0; k < i; k++) { - sum -= omtrx[i][k] * omtrx[k][j]; - } - omtrx[i][j] = sum; - } - maxb = 0.0; - for (i = j; i < size; i++) { - sum = omtrx[i][j]; - for (k = 0; k < j; k++) { - sum -= omtrx[i][k] * omtrx[k][j]; - } - omtrx[i][j] = sum; - tmp = wk[i] * Math.abs(sum); - if (tmp >= maxb) { - maxb = tmp; - maxi = i; - } - } - if (j != maxi) { - for (k = 0; k < size; k++) { - tmp = omtrx[maxi][k]; - omtrx[maxi][k] = omtrx[j][k]; - omtrx[j][k] = tmp; - } - aw = -aw; - wk[maxi] = wk[j]; - } - index[j] = maxi; - if (omtrx[j][j] == 0.0) { - omtrx[j][j] = MachineAccuracy.EPSILON; - } - if (j != size - 1) { - tmp = 1.0 / omtrx[j][j]; - for (i = j + 1; i < size; i++) { - omtrx[i][j] *= tmp; - } - } - } - for (jx = 0; jx < size; jx++) { - for (ix = 0; ix < size; ix++) { - wk[ix] = 0.0; - } - wk[jx] = 1.0; - l = -1; - for (i = 0; i < size; i++) { - idx = index[i]; - sum = wk[idx]; - wk[idx] = wk[i]; - if (l != -1) { - for (j = l; j < i; j++) { - sum -= omtrx[i][j] * wk[j]; - } - } else if (sum != 0.0) { - l = i; - } - wk[i] = sum; - } - for (i = size - 1; i >= 0; i--) { - sum = wk[i]; - for (j = i + 1; j < size; j++) { - sum -= omtrx[i][j] * wk[j]; - } - wk[i] = sum / omtrx[i][i]; - } - for (ix = 0; ix < size; ix++) { - imtrx[ix][jx] = wk[ix]; - } - } - wk = null; - index = null; - omtrx = null; - } - - private MatrixParameter rates; -} diff --git a/src/dr/oldevomodel/substmodel/PseudoCodonModel.java b/src/dr/oldevomodel/substmodel/PseudoCodonModel.java deleted file mode 100644 index 806e62f3a1..0000000000 --- a/src/dr/oldevomodel/substmodel/PseudoCodonModel.java +++ /dev/null @@ -1,320 +0,0 @@ -/* - * PseudoCodonModel.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.substmodel; - -import dr.evolution.datatype.Nucleotides; -import dr.oldevomodel.sitemodel.GammaSiteModel; -import dr.inference.model.AbstractModel; -import dr.inference.model.Model; -import dr.inference.model.Parameter; -import dr.inference.model.Variable; -import dr.xml.*; -import org.w3c.dom.Document; -import org.w3c.dom.Element; - -/** - * PseudoCodonModel - provides an approximation to the codon substitution model. - * - * @author Alexei Drummond - * @author Andrew Rambaut - */ - -public class PseudoCodonModel extends AbstractModel { - - // - // Public stuff - // - - public static final String PSEUDO_CODON_MODEL = "pseudoCodonModel"; - public static final String MU = "mu"; - public static final String OMEGA = "omega"; - public static final String KAPPA = "kappa"; - public static final String FIRST_POSITION = "firstPosition"; - public static final String SECOND_POSITION = "secondPosition"; - public static final String THIRD_POSITION = "thirdPosition"; - - /** - * Constructor - */ - public PseudoCodonModel(GammaSiteModel siteModel1, - GammaSiteModel siteModel2, - GammaSiteModel siteModel3, - Parameter muParameter, - Parameter omegaParameter, - Parameter kappaParameter, - FrequencyModel freqModel) { - - super(PSEUDO_CODON_MODEL); - - this.gtr1 = (GTR) siteModel1.getSubstitutionModel(); - this.siteModel1 = siteModel1; - - this.gtr2 = (GTR) siteModel2.getSubstitutionModel(); - this.siteModel2 = siteModel2; - - this.gtr3 = (GTR) siteModel3.getSubstitutionModel(); - this.siteModel3 = siteModel3; - - if (freqModel.getDataType() != Nucleotides.INSTANCE) { - throw new IllegalArgumentException("Datatypes do not match!"); - } - - this.frequencyModel = freqModel; - addModel(frequencyModel); - - this.muParameter = muParameter; - muParameter.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, 0.0, 1)); - addVariable(muParameter); - - this.omegaParameter = omegaParameter; - omegaParameter.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, 0.0, 1)); - addVariable(omegaParameter); - - this.kappaParameter = kappaParameter; - kappaParameter.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, 0.0, 1)); - addVariable(kappaParameter); - - excludeStopCodons = true; - - calculateSubstitutionModel(); - } - - // ************************************************************** - // Model IMPLEMENTATION - // ************************************************************** - - protected void handleModelChangedEvent(Model model, Object object, int index) { - // frequencyModel changed! - calculateSubstitutionModel(); - } - - protected final void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) { - // parameter changed! - calculateSubstitutionModel(); - } - - protected void storeState() { - } // no additional state needs storing - - protected void restoreState() { - } // no additional state needs restoring - - protected void acceptState() { - } // no additional state needs accepting - - // - // Private stuff - // - - private void calculateSubstitutionModel() { - double omega = omegaParameter.getParameterValue(0); - double kappa = kappaParameter.getParameterValue(0); - double mu = muParameter.getParameterValue(0); - - double[] frequencies = frequencyModel.getFrequencies(); - double piAC = frequencies[0] * frequencies[1]; - double piAG = frequencies[0] * frequencies[2]; - double piAT = frequencies[0] * frequencies[3]; - double piCG = frequencies[1] * frequencies[2]; - double piCT = frequencies[1] * frequencies[3]; - double piGT = frequencies[2] * frequencies[3]; - - double[][] rates = new double[3][6]; - - if (excludeStopCodons) { - // A-C - rates[0][0] = ((omega * 14.0 / 16.0) + (2.0 / 16.0)); - rates[1][0] = omega; - rates[2][0] = ((omega * 5.0 / 14.0) + (9.0 / 14.0)); - - // A-G - rates[0][1] = omega * kappa; - rates[1][1] = rates[0][1]; - rates[2][1] = ((omega / 14.0) + (13.0 / 14.0)) * kappa; - - // A-T - rates[0][2] = omega; - rates[1][2] = rates[0][2]; - rates[2][2] = ((omega * 5.0 / 14.0) + (9.0 / 14.0)); - - // C-G - rates[0][3] = omega; - rates[1][3] = rates[0][3]; - rates[2][3] = ((omega * 7.0 / 15.0) + (8.0 / 15.0)); - - // C-T - rates[0][4] = ((omega * 11.0 / 13.0) + (2.0 / 13.0)) * kappa; - rates[1][4] = omega * kappa; - rates[2][4] = kappa; - - // G-T - rates[0][5] = omega; - rates[1][5] = rates[0][5]; - rates[2][5] = ((omega * 7.0 / 15.0) + (8.0 / 15.0)); - } else { - // A-C - rates[0][0] = ((omega * 14.0 / 16.0) + (2.0 / 16.0)); - rates[1][0] = omega; - rates[2][0] = ((omega * 5.0 / 16.0) + (9.0 / 16.0)); - - // A-G - rates[0][1] = omega * kappa; - rates[1][1] = rates[0][1]; - rates[2][1] = ((omega / 16.0) + (13.0 / 16.0)) * kappa; - - // A-T - rates[0][2] = (omega * 13.0 / 16.0); - rates[1][2] = omega; - rates[2][2] = ((omega * 5.0 / 16.0) + (9.0 / 16.0)); - - // C-G - rates[0][3] = omega; - rates[1][3] = rates[0][3]; - rates[2][3] = ((omega * 7.0 / 16.0) + (8.0 / 16.0)); - - // C-T - rates[0][4] = ((omega * 11.0 / 16.0) + (2.0 / 16.0)) * kappa; - rates[1][4] = omega * kappa; - rates[2][4] = kappa; - - // G-T - rates[0][5] = (omega * 13.0 / 16.0); - rates[1][5] = omega; - rates[2][5] = ((omega * 7.0 / 16.0) + (8.0 / 16.0)); - } - - double sumRates1 = (rates[0][0] * piAC) + - (rates[0][1] * piAG) + - (rates[0][2] * piAT) + - (rates[0][3] * piCG) + - (rates[0][4] * piCT) + - (rates[0][5] * piGT); - double sumRates2 = (rates[1][0] * piAC) + - (rates[1][1] * piAG) + - (rates[1][2] * piAT) + - (rates[1][3] * piCG) + - (rates[1][4] * piCT) + - (rates[1][5] * piGT); - double sumRates3 = (rates[2][0] * piAC) + - (rates[2][1] * piAG) + - (rates[2][2] * piAT) + - (rates[2][3] * piCG) + - (rates[2][4] * piCT) + - (rates[2][5] * piGT); - - double f = (mu * 3.0) / (sumRates1 + sumRates2 + sumRates3); - - double mu1 = f * sumRates1; - double mu2 = f * sumRates2; - double mu3 = f * sumRates3; - - gtr1.setAbsoluteRates(rates[0], 4); - siteModel1.setMu(mu1); - gtr2.setAbsoluteRates(rates[1], 4); - siteModel2.setMu(mu2); - gtr3.setAbsoluteRates(rates[2], 4); - siteModel3.setMu(mu3); - } - - // ************************************************************** - // XMLElement IMPLEMENTATION - // ************************************************************** - - public Element createElement(Document d) { - throw new RuntimeException("createElement not implemented"); - } - - public static XMLObjectParser PSEUDO_CODON_MODEL_PARSER = new AbstractXMLObjectParser() { - - public String getParserName() { - return PSEUDO_CODON_MODEL; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - Parameter muParam = (Parameter) xo.getElementFirstChild(MU); - Parameter omegaParam = (Parameter) xo.getElementFirstChild(OMEGA); - Parameter kappaParam = (Parameter) xo.getElementFirstChild(KAPPA); - - GammaSiteModel siteModel1 = (GammaSiteModel) xo.getElementFirstChild(FIRST_POSITION); - GammaSiteModel siteModel2 = (GammaSiteModel) xo.getElementFirstChild(SECOND_POSITION); - GammaSiteModel siteModel3 = (GammaSiteModel) xo.getElementFirstChild(THIRD_POSITION); - - if (!(siteModel1.getSubstitutionModel() instanceof GTR) || - !(siteModel2.getSubstitutionModel() instanceof GTR) || - !(siteModel3.getSubstitutionModel() instanceof GTR)) { - throw new XMLParseException("Substitution models in " + getParserName() + " elements must be GTRs"); - } - - GTR gtr = (GTR) siteModel1.getSubstitutionModel(); - FrequencyModel freqModel = gtr.getFrequencyModel(); - - return new PseudoCodonModel(siteModel1, siteModel2, siteModel3, muParam, omegaParam, kappaParam, freqModel); - } - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - - public String getParserDescription() { - return "This element represents the Pseudo-Codon model of nucleotide evolution."; - } - - public Class getReturnType() { - return PseudoCodonModel.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{ - new ElementRule(MU, Parameter.class), - new ElementRule(OMEGA, Parameter.class), - new ElementRule(KAPPA, Parameter.class), - new ElementRule(FIRST_POSITION, GammaSiteModel.class), - new ElementRule(SECOND_POSITION, GammaSiteModel.class), - new ElementRule(THIRD_POSITION, GammaSiteModel.class) - }; - }; - - // ************************************************************** - // INSTANCE VARIABLES - // ************************************************************** - - /** - * the site models - */ - private GammaSiteModel siteModel1, siteModel2, siteModel3; - private GTR gtr1, gtr2, gtr3; - private FrequencyModel frequencyModel; - private boolean excludeStopCodons; - - protected Parameter muParameter = null; - protected Parameter omegaParameter = null; - protected Parameter kappaParameter = null; -} \ No newline at end of file diff --git a/src/dr/oldevomodel/substmodel/SVSComplexSubstitutionModel.java b/src/dr/oldevomodel/substmodel/SVSComplexSubstitutionModel.java deleted file mode 100644 index 2a0b6b903d..0000000000 --- a/src/dr/oldevomodel/substmodel/SVSComplexSubstitutionModel.java +++ /dev/null @@ -1,164 +0,0 @@ -/* - * SVSComplexSubstitutionModel.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.substmodel; - -import dr.evolution.datatype.DataType; -import dr.inference.model.BayesianStochasticSearchVariableSelection; -import dr.inference.model.Parameter; -import dr.inference.model.Variable; -import dr.math.matrixAlgebra.Vector; - -/** - * @author Marc A. Suchard - */ -public class SVSComplexSubstitutionModel extends ComplexSubstitutionModel implements BayesianStochasticSearchVariableSelection { - - public SVSComplexSubstitutionModel(String name, DataType dataType, FrequencyModel rootFreqModel, - Parameter rates, Parameter indicators) { - super(name, dataType, rootFreqModel, rates); - if (indicators != null) { - this.indicators = indicators; - addVariable(indicators); - } else { - this.indicators = new Parameter.Default(rates.getDimension(), 1.0); - } - } - - protected double[] getRates() { - double[] rates = infinitesimalRates.getParameterValues(); - double[] indies = indicators.getParameterValues(); - final int dim = rates.length; - for (int i = 0; i < dim; i++) - rates[i] *= indies[i]; - return rates; - } - - protected void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) { - if (variable == infinitesimalRates && indicators.getParameterValue(index) == 0) - return; // ignore, does not affect likelihood - super.handleVariableChangedEvent(variable, index, type); - } - - public Parameter getIndicators() { - return indicators; - } - -// public double getLogLikelihood() { -// double logL = super.getLogLikelihood(); -// if (logL == 0 && considerConnectedness && !isStronglyConnected()) { // Also check that graph is connected -// logL = Double.NEGATIVE_INFINITY; -// } -// return logL; -// } - -// private boolean hasEdge(int i, int j) { -// return i != j && getIndicators().getParameterValue(getEntry(i,j,stateCount)) == 1; -// } -// -// private static int getEntry(int i, int j, int dim) { -// int entry = i * (dim - 1) + j; -// if( j > i ) -// entry--; -// return entry; -// } -// -// private void depthFirstSearch(int node, BitVector visited) { -// visited.set(node); -// for(int v=0; v getLikelihoodSet() { - return new HashSet(Arrays.asList(this)); - } - - @Override - public boolean isUsed() { - return super.isUsed() && isUsed; - } - - public void setUsed() { - isUsed = true; - } - - private boolean isUsed = false; - - private Parameter rateIndicator; - - @Override - public Citation.Category getCategory() { - return Citation.Category.SUBSTITUTION_MODELS; - } - - @Override - public String getDescription() { - return "Stochastic search variable selection, reversible substitution model"; - } - - @Override - public List getCitations() { - return Collections.singletonList(CommonCitations.LEMEY_2009_BAYESIAN); - } -} diff --git a/src/dr/oldevomodel/substmodel/SubstitutionEpochModel.java b/src/dr/oldevomodel/substmodel/SubstitutionEpochModel.java deleted file mode 100644 index 1c0cf91225..0000000000 --- a/src/dr/oldevomodel/substmodel/SubstitutionEpochModel.java +++ /dev/null @@ -1,235 +0,0 @@ -/* - * SubstitutionEpochModel.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.substmodel; - -import dr.evolution.datatype.DataType; -import dr.inference.model.Model; -import dr.inference.model.Parameter; -import dr.inference.model.Variable; -import dr.math.matrixAlgebra.Vector; - -import java.util.List; - -/** - * @author Marc A. Suchard - */ - -public class SubstitutionEpochModel extends AbstractSubstitutionModel { - - public static final boolean DEBUG = false; - - public SubstitutionEpochModel(String name, - List modelList, - Parameter transitionTimes, - DataType dataType, FrequencyModel freqModel) { - - super(name, dataType, freqModel); - - this.modelList = modelList; - this.transitionTimesParameter = transitionTimes; - this.transitionTimes = transitionTimesParameter.getParameterValues(); - - addVariable(transitionTimes); - - for (SubstitutionModel model : modelList) - addModel(model); - - numberModels = modelList.size(); - weight = new double[numberModels]; - stateCount = dataType.getStateCount(); - stepMatrix = new double[stateCount * stateCount]; - productMatrix = new double[stateCount * stateCount]; - resultMatrix = new double[stateCount * stateCount]; - } - - - protected void frequenciesChanged() { - } - - protected void handleModelChangedEvent(Model model, Object object, int index) { - if (model == freqModel) - frequenciesChanged(); - else // This is an epoch model and I need to pass the info on - fireModelChanged(object, index); - } - - protected void ratesChanged() { - } - - protected void setupRelativeRates() { - } - - public void getTransitionProbabilities(double startTime, double endTime, double distance, double[] matrix) { - int matrixCount = 0; - -// System.out.println("startTime " + startTime ); -// System.out.println("endTime " + endTime ); -// EpochBranchSubstitutionModel.printMatrix(resultMatrix); - - 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++; - -// System.out.println("first " + weight[m] * (endTime - startTime) + " " + model.getVariable(0).getValue(0) + model.getId()); -// EpochBranchSubstitutionModel.printMatrix(resultMatrix); - - } else { - model.getTransitionProbabilities(distance * weight[m], stepMatrix); - // Sum over unobserved state - int index = 0; - -// System.out.println("startTime " + startTime ); -// System.out.println("endTime " + endTime ); -// System.out.println("second " + weight[m] * (endTime - startTime) + " " + model.getVariable(0).getValue(0) + model.getId()); -// EpochBranchSubstitutionModel.printMatrix(stepMatrix); - - 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++; - } - } - -// EpochBranchSubstitutionModel.printMatrix(productMatrix); - - // Swap pointers - double[] tmpMatrix = resultMatrix; - resultMatrix = productMatrix; - productMatrix = tmpMatrix; - } - } - } - if (!oneMatrix) - System.arraycopy(productMatrix, 0, matrix, 0, stateCount * stateCount); - -// System.out.println("C:"); -// EpochBranchSubstitutionModel.printMatrix(resultMatrix); -// System.exit(-1); - - } - - private int getEpochWeights(double startTime, double endTime, double[] weights) { - - int matrixCount = 0; - final double lengthTime = endTime - startTime; - final int lastTime = numberModels - 2; - - // model 0, 1, 2, ..., K-2, K-1 - // times 0, 1, ..., K-2, - // where K = numberModels - -// System.out.println(lengthTime); - - // First epoch: 0 -> transitionTimes[0]; - if (startTime <= transitionTimes[0]) { - if (endTime <= transitionTimes[0]) - weights[0] = 1; - else - weights[0] = (transitionTimes[0] - startTime) / lengthTime; - matrixCount++; - } else - weights[0] = 0; - - // Middle epoches: - for (int i = 1; i <= lastTime; i++) { - if (startTime <= transitionTimes[i]) { - double start = Math.max(startTime, transitionTimes[i - 1]); - double end = Math.min(endTime, transitionTimes[i]); - weights[i] = (end - start) / lengthTime; - matrixCount++; - } else - weights[i] = 0; - } - - // Last epoch: transitionTimes[K-2] -> Infinity - if (lastTime >= 0) { - if (endTime > transitionTimes[lastTime]) { - double start = Math.max(startTime, transitionTimes[lastTime]); - weights[lastTime + 1] = (endTime - start) / lengthTime; - matrixCount++; - } else - weights[lastTime + 1] = 0; - } - - if (DEBUG) { - double totalWeight = 0; - for (int i = 0; i < numberModels; i++) - totalWeight += weights[i]; - System.err.println("Start: " + startTime + " End: " + endTime + " Count: " + matrixCount + " Weight: " + totalWeight + " - " + new Vector(weights)); - if (totalWeight > 1.001) System.exit(-1); - if (totalWeight < 0.999) System.exit(-1); - } - -// System.out.println(endTime-startTime); -// System.out.println(matrixCount); -// EpochBranchSubstitutionModel.printArray(weights); - - return matrixCount; - } - - public void getTransitionProbabilities(double distance, double[] matrix) { - throw new RuntimeException("Should not get here in a substitution epoch model."); - } - - protected final void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) { - super.handleVariableChangedEvent(variable, index, type); - - if (variable == transitionTimesParameter) { - transitionTimes = transitionTimesParameter.getParameterValues(); - fireModelChanged(variable, index); - } - } - - protected void storeState() { - } - - protected void restoreState() { - } - - private List modelList; - private Parameter transitionTimesParameter; - private double[] transitionTimes; - private double[] weight; - private double[] stepMatrix; - private double[] productMatrix; - private double[] resultMatrix; - private int numberModels; - private int stateCount; - -} diff --git a/src/dr/oldevomodel/substmodel/SubstitutionModel.java b/src/dr/oldevomodel/substmodel/SubstitutionModel.java deleted file mode 100644 index 8db1692174..0000000000 --- a/src/dr/oldevomodel/substmodel/SubstitutionModel.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * SubstitutionModel.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.substmodel; - -import dr.evolution.datatype.DataType; -import dr.inference.model.Model; - -/** - * model of sequence substitution (rate matrix). - * provides a convenient interface for the computation of transition probabilities - * - * @author Andrew Rambaut - * @author Alexei Drummond - */ -public interface SubstitutionModel extends Model { - - /** - * Get the complete transition probability matrix for the given distance. - * - * @param distance the time (branch length) - * @param matrix an array to store the matrix - */ - void getTransitionProbabilities(double distance, double[] matrix); - - /** - * This function returns the Eigen vectors. - * @return the array - */ - double[][] getEigenVectors(); - - /** - * This function returns the inverse Eigen vectors. - * @return the array - */ - double[][] getInverseEigenVectors(); - - /** - * This function returns the Eigen values. - * @return the Eigen values - */ - double[] getEigenValues(); - - /** - * get the state frequencies - * - * @return the frequencies - */ - FrequencyModel getFrequencyModel(); - - /** - * @return the data type - */ - DataType getDataType(); - -} diff --git a/src/dr/oldevomodel/substmodel/TN93.java b/src/dr/oldevomodel/substmodel/TN93.java deleted file mode 100644 index 785ca93680..0000000000 --- a/src/dr/oldevomodel/substmodel/TN93.java +++ /dev/null @@ -1,368 +0,0 @@ -/* - * TN93.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.substmodel; - -import dr.oldevomodelxml.substmodel.TN93Parser; -import dr.inference.model.Parameter; -import dr.inference.model.Variable; -import dr.util.Author; -import dr.util.Citable; -import dr.util.Citation; - -import java.util.Collections; -import java.util.List; - -/** - * Tamura and Nei model of nucleotide evolution. - *

- *

- *

- * pr = p[0]+p[1] - * py = 1 - pr - *

- * eigen values - *

- * [0, -1, -(k[0]*pr + py), -(k[1]*py + pr)] - *

- * unnormalized eigen vectors - * [1,1,1,1], - * [1,1,-pr/py,-pr/py], - * [1, -p[0]/p[1], 0, 0], - * [0, 0, 1,-p[2]/p[3]] - * - * @author Joseph Heled - */ -public class TN93 extends AbstractNucleotideModel implements Citable { - - private Variable kappa1Variable = null; - private Variable kappa2Variable = null; - - private boolean updateIntermediates = true; - - /** - * Used for precalculations - */ - - private double p1a; - private double p0a; - private double p3b; - private double p2b; - private double a; - private double b; - private double p1aa; - private double p0aa; - private double p3bb; - private double p2bb; - private double p1aIsa; - private double p0aIsa; - private double p3bIsb; - private double p2bIsb; - private double k1g; - private double k1a; - private double k2t; - private double k2c; - private double subrateScale; - - /** - * TN93 - * - * @param kappa1Variable - * @param kappa2Variable - * @param freqModel - */ - public TN93(Variable kappa1Variable, Variable kappa2Variable, FrequencyModel freqModel) { - - super(TN93Parser.TN93_MODEL, freqModel); - this.kappa1Variable = kappa1Variable; - this.kappa2Variable = kappa2Variable; - addVariable(kappa1Variable); - addVariable(kappa2Variable); - kappa1Variable.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, 0.0, 1)); - kappa2Variable.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, 0.0, 1)); - updateIntermediates = true; - } - - /** - * @return kappa1 - */ - public final double getKappa1() { - return kappa1Variable.getValue(0); - } - - /** - * @return kappa2 - */ - public final double getKappa2() { - return kappa2Variable.getValue(0); - } - - - protected void frequenciesChanged() { - // frequencyModel changed - updateIntermediates = true; - } - - // I am not sure how HKY works without this - // Comment this function out to get bug 138 - protected void ratesChanged() { - // frequencyModel changed - updateIntermediates = true; - } - - private void calculateIntermediates() { - - calculateFreqRY(); - - double k1 = getKappa1(); - double k2 = getKappa2(); - -// System.out.println(getModelName() + " Using " + k1 + " " + k2); - // A hack until I get right this boundary case. gives results accurate to 1e-8 in the P matrix - // so should be OK even like this. - if (k1 == 1) { - k1 += 1E-10; - } - if (k2 == 1) { - k2 += 1e-10; - } - - double l1 = k1 * k1 * freqR + k1 * (2 * freqY - 1) - freqY; - double l2 = k2 * k2 * freqY + k2 * (2 * freqR - 1) - freqR; - - p1a = freqG * l1; - p0a = freqA * l1; - p3b = freqT * l2; - p2b = freqC * l2; - - a = -(k1 * freqR + freqY); - b = -(k2 * freqY + freqR); - - p1aa = p1a / a; - p0aa = p0a / a; - p3bb = p3b / b; - p2bb = p2b / b; - - p1aIsa = p1a / (1 + a); - p0aIsa = p0a / (1 + a); - p3bIsb = p3b / (1 + b); - p2bIsb = p2b / (1 + b); - - k1g = k1 * freqG; - k1a = k1 * freqA; - k2t = k2 * freqT; - k2c = k2 * freqC; - - subrateScale = 2 * (k1 * freqA * freqG + k2 * freqC * freqT + freqR * freqY); - // updateMatrix = true; - updateIntermediates = false; - } - - /** - * get the complete transition probability matrix for the given distance. - *

- * Based on work I did in my 691 project. - * - * @param distance the expected number of substitutions - * @param matrix an array to store the matrix - */ - public void getTransitionProbabilities(double distance, double[] matrix) { - synchronized (this) { - if (updateIntermediates) { - calculateIntermediates(); - } - } - - distance /= subrateScale; - - double[] q = { - 0, k1g, freqC, freqT, - k1a, 0, freqC, freqT, - freqA, freqG, 0, k2t, - freqA, freqG, k2c, 0 - }; - - q[0] = -(q[1] + q[2] + q[3]); - q[5] = -(q[4] + q[6] + q[7]); - q[10] = -(q[8] + q[9] + q[11]); - q[15] = -(q[12] + q[13] + q[14]); - - double[] fa0 = { - 1 + q[0] - p1aa, q[1] + p1aa, q[2], q[3], - q[4] + p0aa, 1 + q[5] - p0aa, q[6], q[7], - q[8], q[9], 1 + q[10] - p3bb, q[11] + p3bb, - q[12], q[13], q[14] + p2bb, 1 + q[15] - p2bb - }; - - - double[] fa1 = { - -q[0] + p1aIsa, -q[1] - p1aIsa, -q[2], -q[3], - -q[4] - p0aIsa, -q[5] + p0aIsa, -q[6], -q[7], - -q[8], -q[9], -q[10] + p3bIsb, -q[11] - p3bIsb, - -q[12], -q[13], -q[14] - p2bIsb, -q[15] + p2bIsb}; - - double et = Math.exp(-distance); - - for (int k = 0; k < 16; ++k) { - fa1[k] = fa1[k] * et + fa0[k]; - } - - final double eta = Math.exp(distance * a); - final double etb = Math.exp(distance * b); - - double za = eta / (a * (1 + a)); - double zb = etb / (b * (1 + b)); - double u0 = p1a * za; - double u1 = p0a * za; - double u2 = p3b * zb; - double u3 = p2b * zb; - - fa1[0] += u0; - fa1[1] -= u0; - fa1[4] -= u1; - fa1[5] += u1; - - fa1[10] += u2; - fa1[11] -= u2; - fa1[14] -= u3; - fa1[15] += u3; - - // transpose 2 middle rows and columns - matrix[0] = fa1[0]; - matrix[1] = fa1[2]; - matrix[2] = fa1[1]; - matrix[3] = fa1[3]; - matrix[4] = fa1[8]; - matrix[5] = fa1[10]; - matrix[6] = fa1[9]; - matrix[7] = fa1[11]; - matrix[8] = fa1[4]; - matrix[9] = fa1[6]; - matrix[10] = fa1[5]; - matrix[11] = fa1[7]; - matrix[12] = fa1[12]; - matrix[13] = fa1[14]; - matrix[14] = fa1[13]; - matrix[15] = fa1[15]; - - //System.arraycopy(fa1, 0, matrix, 0, 16); - } - - /** - * setup substitution matrix - */ - public void setupMatrix() { - } - - protected void setupRelativeRates() { - } - - // untested -// public double[] getEigenValues() { -// final double k1 = getKappa1(); -// final double k2 = getKappa2(); -// calculateFreqRY(); -// -// return new double[]{0, -1, -(k1*freqR + freqY), -(k2*freqY + freqR)}; -// } -// -// public double[][] getEigenVectors() { -// calculateFreqRY(); -// -// final double[][] emat = { -// {1., 1, 1., 1}, -// {1, 1, -freqR / freqY, -freqR / freqY}, -// {1, -freqA / freqC, 0, 0}, -// {0, 0, 1, -freqG / freqT}}; -// -// // make them norm 1 -// for(int k = 0; k < 4; ++k) { -// double s = 0; -// for(int i = 0; i < 4; ++i) { -// s += emat[k][i]; -// } -// s = 1.0/Math.sqrt(s); -// for(int i = 0; i < 4; ++i) { -// emat[k][i] *= s; -// } -// } -// return emat; -// } - - // ***************************************************************** - // Interface Model - // ***************************************************************** - - /** - * Restore the stored state - */ - public void restoreState() { - super.restoreState(); - updateIntermediates = true; - } - - // ************************************************************** - // XHTMLable IMPLEMENTATION - // ************************************************************** - - public String toXHTML() { - StringBuffer buffer = new StringBuffer(); - - buffer.append("TN93 Model"); - buffer.append(" (kappa = "); - buffer.append(getKappa1()).append(",").append(getKappa2()); - buffer.append(")"); - - return buffer.toString(); - } - - @Override - public Citation.Category getCategory() { - return Citation.Category.SUBSTITUTION_MODELS; - } - - @Override - public String getDescription() { - return "Tamura-Nei nucleotide substitution model"; - } - - @Override - public List getCitations() { - return Collections.singletonList(CITATION); - } - - public static Citation CITATION = new Citation( - new Author[]{ - new Author("K", "Tamura"), - new Author("M", "Nei") - }, - "Estimation of the number of nucleotide substitutions in the control region of mitochondrial DNA in humans and chimpanzees", - 1993, - "Mol Biol Evol", - 10, 512, 526 - ); -} \ No newline at end of file diff --git a/src/dr/oldevomodel/substmodel/TwoPhaseModel.java b/src/dr/oldevomodel/substmodel/TwoPhaseModel.java deleted file mode 100644 index ecea0b6b25..0000000000 --- a/src/dr/oldevomodel/substmodel/TwoPhaseModel.java +++ /dev/null @@ -1,268 +0,0 @@ -/* - * TwoPhaseModel.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.substmodel; - - -import dr.evolution.datatype.Microsatellite; -import dr.inference.model.Parameter; -import dr.inference.model.Variable; - -import java.util.ArrayList; - -/** - * @author Chieh-Hsi Wu - * - * Implements Two Phase Model of microsatellites - */ -public class TwoPhaseModel extends MicrosatelliteModel{ - - - /* - *Parameters for setting up the infinitesimal rate matrix. - */ - private Parameter geoParam; - private Parameter onePhasePrParam; - private Parameter transformParam; - private boolean estimateSubmodelParams = false; - private ArrayList> submodelParameters = null; - private boolean updateSubmodelRates = false; - - public static final String TWO_PHASE_MODEL = "TWOPHASEModel"; - - /** - * Constructor - * - * @param microsatellite microsatellite data type - * @param freqModel user specified initial equilibrium frequencies - * @param submodel this submodel of this - * @param onePhasePrParam the probability that the rate will conform to the one phase model - * @param geoParam the probability of a success in geometric distribution of the TwoPhaseModel - * @param transParam the parameter for transforming onePhasePrParam and geoParam when onePhasePrParam > 0 - * @param estimateSubmodelParams indicate whether the submodel parameters are estimated - */ - - public TwoPhaseModel( - Microsatellite microsatellite, - FrequencyModel freqModel, - OnePhaseModel submodel, - Parameter onePhasePrParam, - Parameter geoParam, - Parameter transParam, - boolean estimateSubmodelParams){ - - super(TWO_PHASE_MODEL, microsatellite, freqModel, null); - - this.subModel = submodel; - this.estimateSubmodelParams = estimateSubmodelParams; - - if(this.estimateSubmodelParams){ - submodelParameters = new ArrayList>(); - for(int i = 0; i < subModel.getNestedParameterCount(); i++){ - addVariable(subModel.getNestedParameter(i)); - submodelParameters.add(subModel.getNestedParameter(i)); - } - updateSubmodelRates = true; - } - - this.geoParam = geoParam; - this.onePhasePrParam = onePhasePrParam; - - addVariable(this.geoParam); - addVariable(this.onePhasePrParam); - - this.estimateSubmodelParams = estimateSubmodelParams; - - if(transParam != null){ - this.transformParam = transParam; - }else{ - this.transformParam = new Parameter.Default(0.0); - } - - //printDetails(); - - setupInfinitesimalRates(); - - if(freqModel == null){ - useStationaryFreqs = true; - computeStationaryDistribution(); - }else{ - useStationaryFreqs = false; - } - - - } - - private Parameter transOnePhase; - private Parameter transGeo; - private void transform(){ - double e = transformParam.getParameterValue(0); - double m = geoParam.getParameterValue(0); - double p = onePhasePrParam.getParameterValue(0); - if(p < 1 - e && m < 1 - e || p ==m || e ==0){ - transOnePhase = onePhasePrParam; - transGeo = geoParam; - }else if(m > Math.max(1 - e,p)){ - p = p*(m-(m+e-1)/e)/m+(m+e-1)/e; - transOnePhase = new Parameter.Default(p); - }else if(p > Math.max(1 - e,m)){ - m = m*(p-(p+e-1)/e)/p+(p+e-1)/e; - transGeo = new Parameter.Default(m); - } - } - - - protected void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) { - if(submodelParameters !=null && submodelParameters.indexOf(variable) != -1){ - updateSubmodelRates = true; - } - updateMatrix = true; - - } - - public void setupInfinitesimalRates(){ - if(updateSubmodelRates){ - subModel.setupInfinitesimalRates(); - updateSubmodelRates = false; - } - transform(); - - double geoParameter = transGeo.getParameterValue(0); - double p = transOnePhase.getParameterValue(0); - - /*double[] condProbNum = new double[stateCount]; - for(int i = 1; i < stateCount; i++){ - condProbNum[i] = geoParameter*Math.pow((1.0 - geoParameter),i-1); - }*/ - - setupInfinitesimalRates( - stateCount, - geoParameter, - p, - infinitesimalRateMatrix, - subModel.getInfinitesimalRates() - ); - - - } - - public static void setupInfinitesimalRates( - int stateCount, - double geoParameter, - double p, - double[][] rates, - double[][] subRates){ - - double[] condProbNum = new double[stateCount]; - - for(int i = 1; i < stateCount; i++){ - condProbNum[i] = (1.0-geoParameter)*Math.pow(geoParameter,i-1); - } - double condGeo = 0.0; - - for(int i = 0; i < stateCount; i++){ - double expansionGeoDenom = 1-Math.pow(geoParameter,stateCount - 1 - i); - double contractionGeoDenom = 1 - Math.pow(geoParameter, i); - double rowSum = 0.0; - double submodelRate = 0.0; - - for(int j = 0; j < stateCount; j++){ - if(j < i){ - condGeo = condProbNum[Math.abs(i-j)]/contractionGeoDenom; - submodelRate = subRates[i][i-1]; - }else if(j > i){ - submodelRate = subRates[i][i+1]; - condGeo = condProbNum[Math.abs(i-j)]/expansionGeoDenom; - } - - if(i != j){ - if(i == j + 1 || i == j - 1){ - rates[i][j]= submodelRate*(p + (1 - p)*condGeo); - }else { - rates[i][j] = submodelRate*(1 - p)*condGeo; - } - rowSum = rowSum+rates[i][j]; - } - - } - - rates[i][i] = 0.0-rowSum; - } - } - - - public void computeStationaryDistribution() { - - if(useStationaryFreqs){ - computeTwoPhaseStationaryDistribution(); - } - super.computeStationaryDistribution(); - } - - public MicrosatelliteModel getSubModel(){ - return subModel; - } - - public Parameter getGeometricParamter(){ - return geoParam; - } - - public Parameter getOnePhasePrParamter(){ - return onePhasePrParam; - - } - - public Parameter getTransGeometricParamter(){ - return transGeo; - } - - public Parameter getTransOnePhasePrParamter(){ - return transOnePhase; - } - - public Parameter getTransformParam(){ - return transformParam; - } - - public boolean isEstimatingSubmodelParams(){ - return estimateSubmodelParams; - } - - public void printDetails(){ - System.out.println("Details of the TwoPhase Model and its paramters:"); - System.out.println("a submodel: "+isNested); - System.out.println("has submodel: "+hasSubmodel()); - if(hasSubmodel()){ - System.out.println("submodel class: "+subModel.getClass()); - } - System.out.println("esitmating submodel parameters: "+estimateSubmodelParams); - System.out.println("one phase probability: "+onePhasePrParam.getParameterValue(0)); - System.out.println("geometric parameter: "+geoParam.getParameterValue(0)); - System.out.println("transformation parameter: "+transformParam.getParameterValue(0)); - } - -} diff --git a/src/dr/oldevomodel/substmodel/TwoStateCovarionModel.java b/src/dr/oldevomodel/substmodel/TwoStateCovarionModel.java deleted file mode 100755 index 30cc63379a..0000000000 --- a/src/dr/oldevomodel/substmodel/TwoStateCovarionModel.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * TwoStateCovarionModel.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.substmodel; - -import dr.evolution.datatype.TwoStateCovarion; -import dr.oldevomodelxml.substmodel.TwoStateCovarionModelParser; -import dr.inference.model.Parameter; - -/** - * @author Helen Shearman - * @author Alexei Drummond - */ -public class TwoStateCovarionModel extends AbstractSubstitutionModel { - - /** - * constructor - * - * @param dataType the data type - * @param freqModel the frequencies - * @param alphaParameter the rate of evolution in slow mode - * @param switchingParameter the rate of flipping between slow and fast modes - */ - public TwoStateCovarionModel(TwoStateCovarion dataType, FrequencyModel freqModel, - Parameter alphaParameter, - Parameter switchingParameter) { - super(TwoStateCovarionModelParser.COVARION_MODEL, dataType, freqModel); - - alpha = alphaParameter; - this.switchingParameter = switchingParameter; - - addVariable(alpha); - addVariable(switchingParameter); - setupRelativeRates(); - } - - protected void frequenciesChanged() { - // DO NOTHING - } - - protected void ratesChanged() { - setupRelativeRates(); - } - - protected void setupRelativeRates() { - - relativeRates[0] = alpha.getParameterValue(0); - relativeRates[1] = switchingParameter.getParameterValue(0); - relativeRates[2] = 0.0; - relativeRates[3] = 0.0; - relativeRates[4] = switchingParameter.getParameterValue(0); - relativeRates[5] = 1.0; - } - - public String toString() { - - return SubstitutionModelUtils.toString(relativeRates, dataType, true, 2); - } - - /** - * Normalize rate matrix to one expected substitution per unit time - * - * @param matrix the matrix to normalize to one expected substitution - * @param pi the equilibrium distribution of states - */ - void normalize(double[][] matrix, double[] pi) { - - if (isNormalized) { - - double subst = 0.0; - int dimension = pi.length; - - for (int i = 0; i < dimension; i++) { - subst += -matrix[i][i] * pi[i]; - } - - // normalize, including switches - for (int i = 0; i < dimension; i++) { - for (int j = 0; j < dimension; j++) { - matrix[i][j] = matrix[i][j] / subst; - } - } - - double switchingProportion = 0.0; - switchingProportion += matrix[0][2] * pi[2]; - switchingProportion += matrix[2][0] * pi[0]; - switchingProportion += matrix[1][3] * pi[3]; - switchingProportion += matrix[3][1] * pi[1]; - - //System.out.println("switchingProportion=" + switchingProportion); - - // normalize, removing switches - for (int i = 0; i < dimension; i++) { - for (int j = 0; j < dimension; j++) { - matrix[i][j] = matrix[i][j] / (1.0 - switchingProportion); - } - } - } - } - - private Parameter alpha; - private Parameter switchingParameter; - - // if true then matrix will be normalized to output 1 substitution per unit time - private boolean isNormalized = true; - -} diff --git a/src/dr/oldevomodel/substmodel/WAG.java b/src/dr/oldevomodel/substmodel/WAG.java deleted file mode 100644 index 2a733d9505..0000000000 --- a/src/dr/oldevomodel/substmodel/WAG.java +++ /dev/null @@ -1,232 +0,0 @@ -/* - * WAG.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.substmodel; - -import dr.evolution.datatype.AminoAcids; -import dr.util.Author; -import dr.util.Citation; - -import java.util.*; - -/** - * WAG model of amino acid evolution (S. Whelan and N. Goldman 2000) - * Whelan, S. and N. Goldman. 2000. Bioinformatics ?. - * - * - * @author Andrew Rambaut - * @author Alexei Drummond - */ -public class WAG extends EmpiricalRateMatrix.AbstractAminoAcid { - - public static final WAG INSTANCE = new WAG(); - - // The rates below are specified assuming that the amino acids are in this order: - // ARNDCQEGHILKMFPSTWYV - // but the AminoAcids dataType wants them in this order: - // ACDEFGHIKLMNPQRSTVWY - // This is solved by calling the setEmpiricalRates and setEmpiricalFrequencies methods - private WAG() { super("WAG"); - - int n = AminoAcids.INSTANCE.getStateCount(); - - double[][] rate = new double[n][n]; - - // Q matrix - rate[0][1] = 0.610810; rate[0][2] = 0.569079; - rate[0][3] = 0.821500; rate[0][4] = 1.141050; - rate[0][5] = 1.011980; rate[0][6] = 1.756410; - rate[0][7] = 1.572160; rate[0][8] = 0.354813; - rate[0][9] = 0.219023; rate[0][10] = 0.443935; - rate[0][11] = 1.005440; rate[0][12] = 0.989475; - rate[0][13] = 0.233492; rate[0][14] = 1.594890; - rate[0][15] = 3.733380; rate[0][16] = 2.349220; - rate[0][17] = 0.125227; rate[0][18] = 0.268987; - rate[0][19] = 2.221870; - - rate[1][2] = 0.711690; rate[1][3] = 0.165074; - rate[1][4] = 0.585809; rate[1][5] = 3.360330; - rate[1][6] = 0.488649; rate[1][7] = 0.650469; - rate[1][8] = 2.362040; rate[1][9] = 0.206722; - rate[1][10] = 0.551450; rate[1][11] = 5.925170; - rate[1][12] = 0.758446; rate[1][13] = 0.116821; - rate[1][14] = 0.753467; rate[1][15] = 1.357640; - rate[1][16] = 0.613776; rate[1][17] = 1.294610; - rate[1][18] = 0.423612; rate[1][19] = 0.280336; - - rate[2][3] = 6.013660; rate[2][4] = 0.296524; - rate[2][5] = 1.716740; rate[2][6] = 1.056790; - rate[2][7] = 1.253910; rate[2][8] = 4.378930; - rate[2][9] = 0.615636; rate[2][10] = 0.147156; - rate[2][11] = 3.334390; rate[2][12] = 0.224747; - rate[2][13] = 0.110793; rate[2][14] = 0.217538; - rate[2][15] = 4.394450; rate[2][16] = 2.257930; - rate[2][17] = 0.078463; rate[2][18] = 1.208560; - rate[2][19] = 0.221176; - - rate[3][4] = 0.033379; rate[3][5] = 0.691268; - rate[3][6] = 6.833400; rate[3][7] = 0.961142; - rate[3][8] = 1.032910; rate[3][9] = 0.043523; - rate[3][10] = 0.093930; rate[3][11] = 0.533362; - rate[3][12] = 0.116813; rate[3][13] = 0.052004; - rate[3][14] = 0.472601; rate[3][15] = 1.192810; - rate[3][16] = 0.417372; rate[3][17] = 0.146348; - rate[3][18] = 0.363243; rate[3][19] = 0.169417; - - rate[4][5] = 0.109261; rate[4][6] = 0.023920; - rate[4][7] = 0.341086; rate[4][8] = 0.275403; - rate[4][9] = 0.189890; rate[4][10] = 0.428414; - rate[4][11] = 0.083649; rate[4][12] = 0.437393; - rate[4][13] = 0.441300; rate[4][14] = 0.122303; - rate[4][15] = 1.560590; rate[4][16] = 0.570186; - rate[4][17] = 0.795736; rate[4][18] = 0.604634; - rate[4][19] = 1.114570; - - rate[5][6] = 6.048790; rate[5][7] = 0.366510; - rate[5][8] = 4.749460; rate[5][9] = 0.131046; - rate[5][10] = 0.964886; rate[5][11] = 4.308310; - rate[5][12] = 1.705070; rate[5][13] = 0.110744; - rate[5][14] = 1.036370; rate[5][15] = 1.141210; - rate[5][16] = 0.954144; rate[5][17] = 0.243615; - rate[5][18] = 0.252457; rate[5][19] = 0.333890; - - rate[6][7] = 0.630832; rate[6][8] = 0.635025; - rate[6][9] = 0.141320; rate[6][10] = 0.172579; - rate[6][11] = 2.867580; rate[6][12] = 0.353912; - rate[6][13] = 0.092310; rate[6][14] = 0.755791; - rate[6][15] = 0.782467; rate[6][16] = 0.914814; - rate[6][17] = 0.172682; rate[6][18] = 0.217549; - rate[6][19] = 0.655045; - - rate[7][8] = 0.276379; rate[7][9] = 0.034151; - rate[7][10] = 0.068651; rate[7][11] = 0.415992; - rate[7][12] = 0.194220; rate[7][13] = 0.055288; - rate[7][14] = 0.273149; rate[7][15] = 1.486700; - rate[7][16] = 0.251477; rate[7][17] = 0.374321; - rate[7][18] = 0.114187; rate[7][19] = 0.209108; - - rate[8][9] = 0.152215; rate[8][10] = 0.555096; - rate[8][11] = 0.992083; rate[8][12] = 0.450867; - rate[8][13] = 0.756080; rate[8][14] = 0.771387; - rate[8][15] = 0.822459; rate[8][16] = 0.525511; - rate[8][17] = 0.289998; rate[8][18] = 4.290350; - rate[8][19] = 0.131869; - - rate[9][10] = 3.517820; rate[9][11] = 0.360574; - rate[9][12] = 4.714220; rate[9][13] = 1.177640; - rate[9][14] = 0.111502; rate[9][15] = 0.353443; - rate[9][16] = 1.615050; rate[9][17] = 0.234326; - rate[9][18] = 0.468951; rate[9][19] = 8.659740; - - rate[10][11] = 0.287583; rate[10][12] = 5.375250; - rate[10][13] = 2.348200; rate[10][14] = 0.462018; - rate[10][15] = 0.382421; rate[10][16] = 0.364222; - rate[10][17] = 0.740259; rate[10][18] = 0.443205; - rate[10][19] = 1.997370; - - rate[11][12] = 1.032220; rate[11][13] = 0.098843; - rate[11][14] = 0.619503; rate[11][15] = 1.073780; - rate[11][16] = 1.537920; rate[11][17] = 0.152232; - rate[11][18] = 0.147411; rate[11][19] = 0.342012; - - rate[12][13] = 1.320870; rate[12][14] = 0.194864; - rate[12][15] = 0.556353; rate[12][16] = 1.681970; - rate[12][17] = 0.570369; rate[12][18] = 0.473810; - rate[12][19] = 2.282020; - - rate[13][14] = 0.179896; rate[13][15] = 0.606814; - rate[13][16] = 0.191467; rate[13][17] = 1.699780; - rate[13][18] = 7.154480; rate[13][19] = 0.725096; - - rate[14][15] = 1.786490; rate[14][16] = 0.885349; - rate[14][17] = 0.156619; rate[14][18] = 0.239607; - rate[14][19] = 0.351250; - - rate[15][16] = 4.847130; rate[15][17] = 0.578784; - rate[15][18] = 0.872519; rate[15][19] = 0.258861; - - rate[16][17] = 0.126678; rate[16][18] = 0.325490; - rate[16][19] = 1.547670; - - rate[17][18] = 2.763540; rate[17][19] = 0.409817; - - rate[18][19] = 0.347826; - - setEmpiricalRates(rate, "ARNDCQEGHILKMFPSTWYV"); - - double[] f = new double[n]; - f[0] = 0.0866; - f[1] = 0.0440; - f[2] = 0.0391; - f[3] = 0.0570; - f[4] = 0.0193; - f[5] = 0.0367; - f[6] = 0.0581; - f[7] = 0.0833; - f[8] = 0.0244; - f[9] = 0.0485; - f[10] = 0.0862; - f[11] = 0.0620; - f[12] = 0.0195; - f[13] = 0.0384; - f[14] = 0.0458; - f[15] = 0.0695; - f[16] = 0.0610; - f[17] = 0.0144; - f[18] = 0.0353; - f[19] = 0.0709; - setEmpiricalFrequencies(f, "ARNDCQEGHILKMFPSTWYV"); - } - - @Override - public Citation.Category getCategory() { - return Citation.Category.SUBSTITUTION_MODELS; - } - - @Override - public String getDescription() { - return "WAG amino acid substitution model"; - } - - @Override - public List getCitations() { - return Collections.singletonList(CITATION); - } - - public static Citation CITATION = new Citation( - new Author[]{ - new Author("S", "Whelan"), - new Author("N", "Goldman") - }, - "A General Empirical Model of Protein Evolution Derived from Multiple Protein Families Using a Maximum-Likelihood Approach", - 2001, - "Mol Biol Evol", - 18, - 691, 699, - Citation.Status.PUBLISHED - ); -} diff --git a/src/dr/oldevomodel/substmodel/YangCodonModel.java b/src/dr/oldevomodel/substmodel/YangCodonModel.java deleted file mode 100644 index 1c552e4cec..0000000000 --- a/src/dr/oldevomodel/substmodel/YangCodonModel.java +++ /dev/null @@ -1,367 +0,0 @@ -/* - * YangCodonModel.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.substmodel; - -import dr.evolution.datatype.AminoAcids; -import dr.evolution.datatype.Codons; -import dr.evolution.datatype.Nucleotides; -import dr.oldevomodelxml.substmodel.YangCodonModelParser; -import dr.inference.model.Parameter; -import dr.inference.model.Statistic; - -/** - * Yang model of codon evolution - * - * - * @author Andrew Rambaut - * @author Alexei Drummond - */ -public class YangCodonModel extends AbstractCodonModel { - /** kappa */ - protected Parameter kappaParameter; - - /** omega */ - protected Parameter omegaParameter; - - protected byte[] rateMap; - - /** - * Constructor - */ - public YangCodonModel(Codons codonDataType, - Parameter omegaParameter, - Parameter kappaParameter, - FrequencyModel freqModel) - { - super(YangCodonModelParser.YANG_CODON_MODEL, codonDataType, freqModel); - - this.omegaParameter = omegaParameter; - addVariable(omegaParameter); - omegaParameter.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, 0.0, - omegaParameter.getDimension())); - - this.kappaParameter = kappaParameter; - addVariable(kappaParameter); - kappaParameter.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, 0.0, - kappaParameter.getDimension())); - - constructRateMap(); - - addStatistic(synonymousRateStatistic); - } - - /** - * set kappa - */ - public void setKappa(double kappa) { - kappaParameter.setParameterValue(0, kappa); - updateMatrix = true; - } - - /** - * @return kappa - */ - public double getKappa() { return kappaParameter.getParameterValue(0); } - - /** - * set dN/dS - */ - public void setOmega(double omega) { - omegaParameter.setParameterValue(0, omega); - updateMatrix = true; - } - - - /** - * @return dN/dS - */ - public double getOmega() { return omegaParameter.getParameterValue(0); } - - public double getSynonymousRate() { - double k = getKappa(); - double o = getOmega(); - return ((31.0 * k) + 36.0) / ((31.0 * k) + 36.0 + (138.0 * o) + (58.0 * o * k)); - } - - public double getNonSynonymousRate() { - return 0; - } - - /** - * setup substitution matrix - */ - public void setupRelativeRates() - { - double kappa = getKappa(); - double omega = getOmega(); - for (int i = 0; i < rateCount; i++) { - switch (rateMap[i]) { - case 0: relativeRates[i] = 0.0; break; // codon changes in more than one codon position - case 1: relativeRates[i] = kappa; break; // synonymous transition - case 2: relativeRates[i] = 1.0; break; // synonymous transversion - case 3: relativeRates[i] = kappa * omega; break;// non-synonymous transition - case 4: relativeRates[i] = omega; break; // non-synonymous transversion - } - } - - - } - - /** - * Construct a map of the rate classes in the rate matrix using the current - * genetic code. Classes: - * 0: codon changes in more than one codon position (or stop codons) - * 1: synonymous transition - * 2: synonymous transversion - * 3: non-synonymous transition - * 4: non-synonymous transversion - */ - protected void constructRateMap() - { - int u, v, i1, j1, k1, i2, j2, k2; - byte rateClass; - int[] codon; - int cs1, cs2, aa1, aa2; - - int i = 0; - - rateMap = new byte[rateCount]; - - for (u = 0; u < stateCount; u++) { - - codon = codonDataType.getTripletStates(u); - i1 = codon[0]; - j1 = codon[1]; - k1 = codon[2]; - - cs1 = codonDataType.getState(i1, j1, k1); - aa1 = geneticCode.getAminoAcidState(codonDataType.getCanonicalState(cs1)); - - for (v = u + 1; v < stateCount; v++) { - - codon = codonDataType.getTripletStates(v); - i2 = codon[0]; - j2 = codon[1]; - k2 = codon[2]; - - cs2 = codonDataType.getState(i2, j2, k2); - aa2 = geneticCode.getAminoAcidState(codonDataType.getCanonicalState(cs2)); - - rateClass = -1; - if (i1 != i2) { - if ( (i1 == 0 && i2 == 2) || (i1 == 2 && i2 == 0) || // A <-> G - (i1 == 1 && i2 == 3) || (i1 == 3 && i2 == 1) ) { // C <-> T - rateClass = 1; // Transition at position 1 - } else { - rateClass = 2; // Transversion at position 1 - } - } - if (j1 != j2) { - if (rateClass == -1) { - if ( (j1 == 0 && j2 == 2) || (j1 == 2 && j2 == 0) || // A <-> G - (j1 == 1 && j2 == 3) || (j1 == 3 && j2 == 1) ) { // C <-> T - rateClass = 1; // Transition - } else { - rateClass = 2; // Transversion - } - } else - rateClass = 0; // Codon changes at more than one position - } - if (k1 != k2) { - if (rateClass == -1) { - if ( (k1 == 0 && k2 == 2) || (k1 == 2 && k2 == 0) || // A <-> G - (k1 == 1 && k2 == 3) || (k1 == 3 && k2 == 1) ) { // C <-> T - rateClass = 1; // Transition - } else { - rateClass = 2; // Transversion - } - } else - rateClass = 0; // Codon changes at more than one position - } - - if (rateClass != 0) { - if (aa1 != aa2) { - rateClass += 2; // Is a non-synonymous change - } - } - - rateMap[i] = rateClass; - i++; - } - - } - } - - public void printRateMap() - { - int u, v, i1, j1, k1, i2, j2, k2; - byte rateClass; - int[] codon; - int cs1, cs2, aa1, aa2; - - System.out.print("\t"); - for (v = 0; v < stateCount; v++) { - codon = codonDataType.getTripletStates(v); - i2 = codon[0]; - j2 = codon[1]; - k2 = codon[2]; - - System.out.print("\t" + Nucleotides.INSTANCE.getChar(i2)); - System.out.print(Nucleotides.INSTANCE.getChar(j2)); - System.out.print(Nucleotides.INSTANCE.getChar(k2)); - } - System.out.println(); - - System.out.print("\t"); - for (v = 0; v < stateCount; v++) { - codon = codonDataType.getTripletStates(v); - i2 = codon[0]; - j2 = codon[1]; - k2 = codon[2]; - - cs2 = codonDataType.getState(i2, j2, k2); - aa2 = geneticCode.getAminoAcidState(codonDataType.getCanonicalState(cs2)); - System.out.print("\t" + AminoAcids.INSTANCE.getChar(aa2)); - } - System.out.println(); - - for (u = 0; u < stateCount; u++) { - - codon = codonDataType.getTripletStates(u); - i1 = codon[0]; - j1 = codon[1]; - k1 = codon[2]; - - System.out.print(Nucleotides.INSTANCE.getChar(i1)); - System.out.print(Nucleotides.INSTANCE.getChar(j1)); - System.out.print(Nucleotides.INSTANCE.getChar(k1)); - - cs1 = codonDataType.getState(i1, j1, k1); - aa1 = geneticCode.getAminoAcidState(codonDataType.getCanonicalState(cs1)); - - System.out.print("\t" + AminoAcids.INSTANCE.getChar(aa1)); - - for (v = 0; v < stateCount; v++) { - - codon = codonDataType.getTripletStates(v); - i2 = codon[0]; - j2 = codon[1]; - k2 = codon[2]; - - cs2 = codonDataType.getState(i2, j2, k2); - aa2 = geneticCode.getAminoAcidState(codonDataType.getCanonicalState(cs2)); - - rateClass = -1; - if (i1 != i2) { - if ( (i1 == 0 && i2 == 2) || (i1 == 2 && i2 == 0) || // A <-> G - (i1 == 1 && i2 == 3) || (i1 == 3 && i2 == 1) ) { // C <-> T - rateClass = 1; // Transition at position 1 - } else { - rateClass = 2; // Transversion at position 1 - } - } - if (j1 != j2) { - if (rateClass == -1) { - if ( (j1 == 0 && j2 == 2) || (j1 == 2 && j2 == 0) || // A <-> G - (j1 == 1 && j2 == 3) || (j1 == 3 && j2 == 1) ) { // C <-> T - rateClass = 1; // Transition - } else { - rateClass = 2; // Transversion - } - } else - rateClass = 0; // Codon changes at more than one position - } - if (k1 != k2) { - if (rateClass == -1) { - if ( (k1 == 0 && k2 == 2) || (k1 == 2 && k2 == 0) || // A <-> G - (k1 == 1 && k2 == 3) || (k1 == 3 && k2 == 1) ) { // C <-> T - rateClass = 1; // Transition - } else { - rateClass = 2; // Transversion - } - } else - rateClass = 0; // Codon changes at more than one position - } - - if (rateClass != 0) { - if (aa1 != aa2) { - rateClass += 2; // Is a non-synonymous change - } - } - - System.out.print("\t" + rateClass); - - } - System.out.println(); - - } - } - - // ************************************************************** - // XHTMLable IMPLEMENTATION - // ************************************************************** - - public String toXHTML() { - StringBuffer buffer = new StringBuffer(); - - buffer.append("Yang Codon Model kappa = "); - buffer.append(getKappa()); - buffer.append(", omega = "); - buffer.append(getOmega()); - - return buffer.toString(); - } - - private Statistic synonymousRateStatistic = new Statistic.Abstract() { - - public String getStatisticName() { - return "synonymousRate"; - } - - public int getDimension() { return 1; } - - public double getStatisticValue(int dim) { - return getSynonymousRate(); - } - - }; - - /* private Statistic nonsynonymousRateStatistic = new Statistic.Abstract() { - - public String getStatisticName() { - return "nonSynonymousRate"; - } - - public int getDimension() { return 1; } - - public double getStatisticValue(int dim) { - return getNonSynonymousRate(); - } - - };*/ -} diff --git a/src/dr/oldevomodel/treelikelihood/AbstractLikelihoodCore.java b/src/dr/oldevomodel/treelikelihood/AbstractLikelihoodCore.java deleted file mode 100644 index f36fdb282a..0000000000 --- a/src/dr/oldevomodel/treelikelihood/AbstractLikelihoodCore.java +++ /dev/null @@ -1,508 +0,0 @@ -/* - * AbstractLikelihoodCore.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.treelikelihood; - -import java.util.Arrays; - -/** - * AbstractLikelihoodCore - An abstract base class for LikelihoodCores - * - * @author Andrew Rambaut - */ - -@Deprecated // Switching to BEAGLE -public abstract class AbstractLikelihoodCore implements LikelihoodCore { - - protected int stateCount; - protected int nodeCount; - protected int patternCount; - protected int partialsSize; - protected int matrixSize; - protected int matrixCount; - - protected boolean integrateCategories; - - protected double[][][] partials; - - protected int[][] states; - - protected double[][][] matrices; - - protected int[] currentMatricesIndices; - protected int[] storedMatricesIndices; - protected int[] currentPartialsIndices; - protected int[] storedPartialsIndices; - - protected boolean useScaling = false; - - protected double[][][] scalingFactors; - - private double scalingThreshold = 1.0E-100; - - /** - * Constructor - * - * @param stateCount number of states - */ - public AbstractLikelihoodCore(int stateCount) { - this.stateCount = stateCount; - } - - /** - * initializes partial likelihood arrays. - * - * @param nodeCount the number of nodes in the tree - * @param patternCount the number of patterns - * @param matrixCount the number of matrices (i.e., number of categories) - * @param integrateCategories whether sites are being integrated over all matrices - */ - public void initialize(int nodeCount, int patternCount, int matrixCount, boolean integrateCategories) { - - this.nodeCount = nodeCount; - this.patternCount = patternCount; - this.matrixCount = matrixCount; - - this.integrateCategories = integrateCategories; - - if (integrateCategories) { - partialsSize = patternCount * stateCount * matrixCount; - } else { - partialsSize = patternCount * stateCount; - } - - partials = new double[2][nodeCount][]; - - currentMatricesIndices = new int[nodeCount]; - storedMatricesIndices = new int[nodeCount]; - - currentPartialsIndices = new int[nodeCount]; - storedPartialsIndices = new int[nodeCount]; - - states = new int[nodeCount][]; - - for (int i = 0; i < nodeCount; i++) { - partials[0][i] = null; - partials[1][i] = null; - - states[i] = null; - } - - matrixSize = stateCount * stateCount; - - matrices = new double[2][nodeCount][matrixCount * matrixSize]; - } - - /** - * cleans up and deallocates arrays. - */ - public void finalize() throws java.lang.Throwable { - super.finalize(); - - nodeCount = 0; - patternCount = 0; - matrixCount = 0; - - partials = null; - currentPartialsIndices = null; - storedPartialsIndices = null; - states = null; - matrices = null; - currentMatricesIndices = null; - storedMatricesIndices = null; - - scalingFactors = null; - } - - public void setUseScaling(boolean useScaling) { - this.useScaling = useScaling; - - if (useScaling) { - scalingFactors = new double[2][nodeCount][patternCount]; - } - } - - /** - * Allocates partials for a node - */ - public void createNodePartials(int nodeIndex) { - - this.partials[0][nodeIndex] = new double[partialsSize]; - this.partials[1][nodeIndex] = new double[partialsSize]; - } - - /** - * Sets partials for a node - */ - public void setNodePartials(int nodeIndex, double[] partials) { - - if (this.partials[0][nodeIndex] == null) { - createNodePartials(nodeIndex); - } - if (partials.length < partialsSize) { - int k = 0; - for (int i = 0; i < matrixCount; i++) { - System.arraycopy(partials, 0, this.partials[0][nodeIndex], k, partials.length); - k += partials.length; - } - } else { - System.arraycopy(partials, 0, this.partials[0][nodeIndex], 0, partials.length); - } - } - - /** - * Allocates states for a node - */ - public void createNodeStates(int nodeIndex) { - - this.states[nodeIndex] = new int[patternCount]; - } - - /** - * Sets states for a node - */ - public void setNodeStates(int nodeIndex, int[] states) { - - if (this.states[nodeIndex] == null) { - createNodeStates(nodeIndex); - } - System.arraycopy(states, 0, this.states[nodeIndex], 0, patternCount); - } - - /** - * Gets states for a node - */ - public void getNodeStates(int nodeIndex, int[] states) { - System.arraycopy(this.states[nodeIndex], 0, states, 0, patternCount); - } - - public void setNodeMatrixForUpdate(int nodeIndex) { - currentMatricesIndices[nodeIndex] = 1 - currentMatricesIndices[nodeIndex]; - - } - - - /** - * Sets probability matrix for a node - */ - public void setNodeMatrix(int nodeIndex, int matrixIndex, double[] matrix) { - System.arraycopy(matrix, 0, matrices[currentMatricesIndices[nodeIndex]][nodeIndex], - matrixIndex * matrixSize, matrixSize); - } - - /** - * Gets probability matrix for a node - */ - public void getNodeMatrix(int nodeIndex, int matrixIndex, double[] matrix) { - System.arraycopy(matrices[currentMatricesIndices[nodeIndex]][nodeIndex], - matrixIndex * matrixSize, matrix, 0, matrixSize); - } - - public void setNodePartialsForUpdate(int nodeIndex) { - currentPartialsIndices[nodeIndex] = 1 - currentPartialsIndices[nodeIndex]; - } - - /** - * Sets the currently updating node partials for node nodeIndex. This may - * need to repeatedly copy the partials for the different category partitions - */ - public void setCurrentNodePartials(int nodeIndex, double[] partials) { - if (partials.length < partialsSize) { - int k = 0; - for (int i = 0; i < matrixCount; i++) { - System.arraycopy(partials, 0, this.partials[currentPartialsIndices[nodeIndex]][nodeIndex], k, partials.length); - k += partials.length; - } - } else { - System.arraycopy(partials, 0, this.partials[currentPartialsIndices[nodeIndex]][nodeIndex], 0, partials.length); - } - } - - /** - * Calculates partial likelihoods at a node. - * - * @param nodeIndex1 the 'child 1' node - * @param nodeIndex2 the 'child 2' node - * @param nodeIndex3 the 'parent' node - */ - public void calculatePartials(int nodeIndex1, int nodeIndex2, int nodeIndex3) { - if (states[nodeIndex1] != null) { - if (states[nodeIndex2] != null) { - calculateStatesStatesPruning( - states[nodeIndex1], matrices[currentMatricesIndices[nodeIndex1]][nodeIndex1], - states[nodeIndex2], matrices[currentMatricesIndices[nodeIndex2]][nodeIndex2], - partials[currentPartialsIndices[nodeIndex3]][nodeIndex3]); - } else { - calculateStatesPartialsPruning(states[nodeIndex1], matrices[currentMatricesIndices[nodeIndex1]][nodeIndex1], - partials[currentPartialsIndices[nodeIndex2]][nodeIndex2], matrices[currentMatricesIndices[nodeIndex2]][nodeIndex2], - partials[currentPartialsIndices[nodeIndex3]][nodeIndex3]); - } - } else { - if (states[nodeIndex2] != null) { - calculateStatesPartialsPruning(states[nodeIndex2], matrices[currentMatricesIndices[nodeIndex2]][nodeIndex2], - partials[currentPartialsIndices[nodeIndex1]][nodeIndex1], matrices[currentMatricesIndices[nodeIndex1]][nodeIndex1], - partials[currentPartialsIndices[nodeIndex3]][nodeIndex3]); - } else { - calculatePartialsPartialsPruning(partials[currentPartialsIndices[nodeIndex1]][nodeIndex1], matrices[currentMatricesIndices[nodeIndex1]][nodeIndex1], - partials[currentPartialsIndices[nodeIndex2]][nodeIndex2], matrices[currentMatricesIndices[nodeIndex2]][nodeIndex2], - partials[currentPartialsIndices[nodeIndex3]][nodeIndex3]); - } - } - - if (useScaling) { - scalePartials(nodeIndex3); - } - -// -// int k =0; -// for (int i = 0; i < patternCount; i++) { -// double f = 0.0; -// -// for (int j = 0; j < stateCount; j++) { -// f += partials[currentPartialsIndices[nodeIndex3]][nodeIndex3][k]; -// k++; -// } -// if (f == 0.0) { -// Logger.getLogger("error").severe("A partial likelihood (node index = " + nodeIndex3 + ", pattern = "+ i +") is zero for all states."); -// } -// } - } - - /** - * Calculates partial likelihoods at a node when both children have states. - */ - protected abstract void calculateStatesStatesPruning(int[] states1, double[] matrices1, - int[] states2, double[] matrices2, - double[] partials3); - - /** - * Calculates partial likelihoods at a node when one child has states and one has partials. - */ - protected abstract void calculateStatesPartialsPruning(int[] states1, double[] matrices1, - double[] partials2, double[] matrices2, - double[] partials3); - - /** - * Calculates partial likelihoods at a node when both children have partials. - */ - protected abstract void calculatePartialsPartialsPruning(double[] partials1, double[] matrices1, - double[] partials2, double[] matrices2, - double[] partials3); - - /** - * Calculates partial likelihoods at a node. - * - * @param nodeIndex1 the 'child 1' node - * @param nodeIndex2 the 'child 2' node - * @param nodeIndex3 the 'parent' node - * @param matrixMap a map of which matrix to use for each pattern (can be null if integrating over categories) - */ - public void calculatePartials(int nodeIndex1, int nodeIndex2, int nodeIndex3, int[] matrixMap) { - if (states[nodeIndex1] != null) { - if (states[nodeIndex2] != null) { - calculateStatesStatesPruning( - states[nodeIndex1], matrices[currentMatricesIndices[nodeIndex1]][nodeIndex1], - states[nodeIndex2], matrices[currentMatricesIndices[nodeIndex2]][nodeIndex2], - partials[currentPartialsIndices[nodeIndex3]][nodeIndex3], matrixMap); - } else { - calculateStatesPartialsPruning( - states[nodeIndex1], matrices[currentMatricesIndices[nodeIndex1]][nodeIndex1], - partials[currentPartialsIndices[nodeIndex2]][nodeIndex2], matrices[currentMatricesIndices[nodeIndex2]][nodeIndex2], - partials[currentPartialsIndices[nodeIndex3]][nodeIndex3], matrixMap); - } - } else { - if (states[nodeIndex2] != null) { - calculateStatesPartialsPruning( - states[nodeIndex2], matrices[currentMatricesIndices[nodeIndex2]][nodeIndex2], - partials[currentPartialsIndices[nodeIndex1]][nodeIndex1], matrices[currentMatricesIndices[nodeIndex1]][nodeIndex1], - partials[currentPartialsIndices[nodeIndex3]][nodeIndex3], matrixMap); - } else { - calculatePartialsPartialsPruning( - partials[currentPartialsIndices[nodeIndex1]][nodeIndex1], matrices[currentMatricesIndices[nodeIndex1]][nodeIndex1], - partials[currentPartialsIndices[nodeIndex2]][nodeIndex2], matrices[currentMatricesIndices[nodeIndex2]][nodeIndex2], - partials[currentPartialsIndices[nodeIndex3]][nodeIndex3], matrixMap); - } - } - - if (useScaling) { - scalePartials(nodeIndex3); - } - } - - /** - * Calculates partial likelihoods at a node when both children have states. - */ - protected abstract void calculateStatesStatesPruning(int[] states1, double[] matrices1, - int[] states2, double[] matrices2, - double[] partials3, int[] matrixMap); - - /** - * Calculates partial likelihoods at a node when one child has states and one has partials. - */ - protected abstract void calculateStatesPartialsPruning(int[] states1, double[] matrices1, - double[] partials2, double[] matrices2, - double[] partials3, int[] matrixMap); - - /** - * Calculates partial likelihoods at a node when both children have partials. - */ - protected abstract void calculatePartialsPartialsPruning(double[] partials1, double[] matrices1, - double[] partials2, double[] matrices2, - double[] partials3, int[] matrixMap); - - - public void integratePartials(int nodeIndex, double[] proportions, double[] outPartials) { - calculateIntegratePartials(partials[currentPartialsIndices[nodeIndex]][nodeIndex], proportions, outPartials); - } - - /** - * Integrates partials across categories. - * - * @param inPartials the partials at the node to be integrated - * @param proportions the proportions of sites in each category - * @param outPartials an array into which the integrated partials will go - */ - protected abstract void calculateIntegratePartials(double[] inPartials, double[] proportions, double[] outPartials); - - /** - * Scale the partials at a given node. This uses a scaling suggested by Ziheng Yang in - * Yang (2000) J. Mol. Evol. 51: 423-432 - *

- * This function looks over the partial likelihoods for each state at each pattern - * and finds the largest. If this is less than the scalingThreshold (currently set - * to 1E-40) then it rescales the partials for that pattern by dividing by this number - * (i.e., normalizing to between 0, 1). It then stores the log of this scaling. - * This is called for every internal node after the partials are calculated so provides - * most of the performance hit. Ziheng suggests only doing this on a proportion of nodes - * but this sounded like a headache to organize (and he doesn't use the threshold idea - * which improves the performance quite a bit). - * - * @param nodeIndex - */ - protected void scalePartials(int nodeIndex) { - int u = 0; - - for (int i = 0; i < patternCount; i++) { - - double scaleFactor = 0.0; - int v = u; - for (int k = 0; k < matrixCount; k++) { - for (int j = 0; j < stateCount; j++) { - if (partials[currentPartialsIndices[nodeIndex]][nodeIndex][v] > scaleFactor) { - scaleFactor = partials[currentPartialsIndices[nodeIndex]][nodeIndex][v]; - } - v++; - } - v += (patternCount - 1) * stateCount; - } - - if (scaleFactor < scalingThreshold) { - - v = u; - for (int k = 0; k < matrixCount; k++) { - for (int j = 0; j < stateCount; j++) { - partials[currentPartialsIndices[nodeIndex]][nodeIndex][v] /= scaleFactor; - v++; - } - v += (patternCount - 1) * stateCount; - } - scalingFactors[currentPartialsIndices[nodeIndex]][nodeIndex][i] = Math.log(scaleFactor); - - } else { - scalingFactors[currentPartialsIndices[nodeIndex]][nodeIndex][i] = 0.0; - } - u += stateCount; - - - } - } - - /** - * This function returns the scaling factor for that pattern by summing over - * the log scalings used at each node. If scaling is off then this just returns - * a 0. - * - * @return the log scaling factor - */ - public double getLogScalingFactor(int pattern) { - double logScalingFactor = 0.0; - if (useScaling) { - for (int i = 0; i < nodeCount; i++) { - logScalingFactor += scalingFactors[currentPartialsIndices[i]][i][pattern]; - } - } - return logScalingFactor; - } - - public void getLogScalingFactors(int nodeIndex, double[] buffer) { - if (useScaling) { - System.arraycopy(scalingFactors[currentPartialsIndices[nodeIndex]][nodeIndex], 0, - buffer, 0, patternCount); - } else { - Arrays.fill(buffer, 0.0); - } - } - - public boolean arePartialsRescaled() { - return useScaling; - } - - /** - * Gets the partials for a particular node. - * - * @param nodeIndex the node - * @param outPartials an array into which the partials will go - */ - public void getPartials(int nodeIndex, double[] outPartials) { - double[] partials1 = partials[currentPartialsIndices[nodeIndex]][nodeIndex]; - - System.arraycopy(partials1, 0, outPartials, 0, partialsSize); - } - - /** - * Store current state - */ - public void storeState() { - - System.arraycopy(currentMatricesIndices, 0, storedMatricesIndices, 0, nodeCount); - System.arraycopy(currentPartialsIndices, 0, storedPartialsIndices, 0, nodeCount); - } - - /** - * Restore the stored state - */ - public void restoreState() { - // Rather than copying the stored stuff back, just swap the pointers... - int[] tmp1 = currentMatricesIndices; - currentMatricesIndices = storedMatricesIndices; - storedMatricesIndices = tmp1; - - int[] tmp2 = currentPartialsIndices; - currentPartialsIndices = storedPartialsIndices; - storedPartialsIndices = tmp2; - } -} diff --git a/src/dr/oldevomodel/treelikelihood/AbstractTreeLikelihood.java b/src/dr/oldevomodel/treelikelihood/AbstractTreeLikelihood.java deleted file mode 100644 index 8537c9407d..0000000000 --- a/src/dr/oldevomodel/treelikelihood/AbstractTreeLikelihood.java +++ /dev/null @@ -1,359 +0,0 @@ -/* - * AbstractTreeLikelihood.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.treelikelihood; - -import dr.evolution.alignment.PatternList; -import dr.evolution.datatype.DataType; -import dr.evolution.tree.NodeRef; -import dr.evomodel.tree.TreeModel; -import dr.inference.model.AbstractModelLikelihood; -import dr.inference.model.Model; -import dr.inference.model.Parameter; -import dr.inference.model.Variable; -import dr.xml.Reportable; - -/** - * AbstractTreeLikelihood - a base class for likelihood calculators of sites on a tree. - * - * @author Andrew Rambaut - */ - -@Deprecated // Switching to BEAGLE -public abstract class AbstractTreeLikelihood extends AbstractModelLikelihood implements Reportable { - - protected static final boolean COUNT_TOTAL_OPERATIONS = true; - - public AbstractTreeLikelihood(String name, PatternList patternList, - TreeModel treeModel) { - - super(name); - - this.patternList = patternList; - this.dataType = patternList.getDataType(); - patternCount = patternList.getPatternCount(); - stateCount = dataType.getStateCount(); - - patternWeights = patternList.getPatternWeights(); - - this.treeModel = treeModel; - addModel(treeModel); - - nodeCount = treeModel.getNodeCount(); - - updateNode = new boolean[nodeCount]; - for (int i = 0; i < nodeCount; i++) { - updateNode[i] = true; - } - - likelihoodKnown = false; - - } - - /** - * Sets the partials from a sequence in an alignment. - */ - protected final void setStates(LikelihoodCore likelihoodCore, PatternList patternList, - int sequenceIndex, int nodeIndex) { - int i; - - int[] states = new int[patternCount]; - - for (i = 0; i < patternCount; i++) { - - states[i] = patternList.getPatternState(sequenceIndex, i); - } - - likelihoodCore.setNodeStates(nodeIndex, states); - } - - public TreeModel getTreeModel() { - return treeModel; - } - - /** - * Sets the partials from a sequence in an alignment. - */ - protected final void setPartials(LikelihoodCore likelihoodCore, PatternList patternList, - int categoryCount, - int sequenceIndex, int nodeIndex) { - double[] partials = new double[patternCount * stateCount]; - - boolean[] stateSet; - - int v = 0; - for (int i = 0; i < patternCount; i++) { - - int state = patternList.getPatternState(sequenceIndex, i); - stateSet = dataType.getStateSet(state); - - for (int j = 0; j < stateCount; j++) { - if (stateSet[j]) { - partials[v] = 1.0; - } else { - partials[v] = 0.0; - } - v++; - } - } - - likelihoodCore.setNodePartials(nodeIndex, partials); - } - - /** - * Sets the partials from a sequence in an alignment. - */ - protected final void setMissingStates(LikelihoodCore likelihoodCore, int nodeIndex) { - int[] states = new int[patternCount]; - - for (int i = 0; i < patternCount; i++) { - states[i] = dataType.getGapState(); - } - - likelihoodCore.setNodeStates(nodeIndex, states); - } - - /** - * Sets the partials from a sequence in an alignment. - */ - protected final void setMissingPartials(LikelihoodCore likelihoodCore, int nodeIndex) { - double[] partials = new double[patternCount * stateCount]; - - int v = 0; - for (int i = 0; i < patternCount; i++) { - for (int j = 0; j < stateCount; j++) { - partials[v] = 1.0; - v++; - } - } - - likelihoodCore.setNodePartials(nodeIndex, partials); - } - - /** - * Set update flag for a node and its children - */ - protected void updateNode(NodeRef node) { - - updateNode[node.getNumber()] = true; - likelihoodKnown = false; - } - - /** - * Set update flag for a node and its direct children - */ - protected void updateNodeAndChildren(NodeRef node) { - updateNode[node.getNumber()] = true; - - for (int i = 0; i < treeModel.getChildCount(node); i++) { - NodeRef child = treeModel.getChild(node, i); - updateNode[child.getNumber()] = true; - } - likelihoodKnown = false; - } - - /** - * Set update flag for a node and all its descendents - */ - protected void updateNodeAndDescendents(NodeRef node) { - updateNode[node.getNumber()] = true; - - for (int i = 0; i < treeModel.getChildCount(node); i++) { - NodeRef child = treeModel.getChild(node, i); - updateNodeAndDescendents(child); - } - - likelihoodKnown = false; - } - - /** - * Set update flag for all nodes - */ - protected void updateAllNodes() { - for (int i = 0; i < nodeCount; i++) { - updateNode[i] = true; - } - likelihoodKnown = false; - } - - /** - * Set update flag for a pattern - */ - protected void updatePattern(int i) { - if (updatePattern != null) { - updatePattern[i] = true; - } - likelihoodKnown = false; - } - - /** - * Set update flag for all patterns - */ - protected void updateAllPatterns() { - if (updatePattern != null) { - for (int i = 0; i < patternCount; i++) { - updatePattern[i] = true; - } - } - likelihoodKnown = false; - } - - public final double[] getPatternWeights() { - return patternWeights; - } - - public final int getPatternCount() { - return patternCount; - } - - // ************************************************************** - // VariableListener IMPLEMENTATION - // ************************************************************** - - protected void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) { - // do nothing - } - - // ************************************************************** - // Model IMPLEMENTATION - // ************************************************************** - - protected void handleModelChangedEvent(Model model, Object object, int index) { - likelihoodKnown = false; - } - - /** - * Stores the additional state other than model components - */ - protected void storeState() { - - storedLikelihoodKnown = likelihoodKnown; - storedLogLikelihood = logLikelihood; - } - - /** - * Restore the additional stored state - */ - protected void restoreState() { - - likelihoodKnown = storedLikelihoodKnown; - logLikelihood = storedLogLikelihood; - } - - protected void acceptState() { - } // nothing to do - - // ************************************************************** - // Likelihood IMPLEMENTATION - // ************************************************************** - - public final Model getModel() { - return this; - } - - public final PatternList getPatternList() { - return patternList; - } - - public final double getLogLikelihood() { - if (!likelihoodKnown) { - logLikelihood = calculateLogLikelihood(); - likelihoodKnown = true; - } - return logLikelihood; - } - - /** - * Forces a complete recalculation of the likelihood next time getLikelihood is called - */ - public void makeDirty() { - likelihoodKnown = false; - updateAllNodes(); - updateAllPatterns(); - } - - protected abstract double calculateLogLikelihood(); - - public String getReport() { - getLogLikelihood(); - return getClass().getName() + "(" + logLikelihood + ") total operations = " + totalOperationCount; - - } - - // ************************************************************** - // INSTANCE VARIABLES - // ************************************************************** - - /** - * the tree - */ - protected TreeModel treeModel = null; - - /** - * the patternList - */ - protected PatternList patternList = null; - - protected DataType dataType = null; - - /** - * the pattern weights - */ - protected double[] patternWeights; - - /** - * the number of patterns - */ - protected int patternCount; - - /** - * the number of states in the data - */ - protected int stateCount; - - /** - * the number of nodes in the tree - */ - protected int nodeCount; - - /** - * Flags to specify which patterns are to be updated - */ - protected boolean[] updatePattern = null; - - /** - * Flags to specify which nodes are to be updated - */ - protected boolean[] updateNode; - - private double logLikelihood; - private double storedLogLikelihood; - protected boolean likelihoodKnown = false; - private boolean storedLikelihoodKnown = false; - - protected int totalOperationCount = 0; -} \ No newline at end of file diff --git a/src/dr/oldevomodel/treelikelihood/AdvancedTreeLikelihood.java b/src/dr/oldevomodel/treelikelihood/AdvancedTreeLikelihood.java deleted file mode 100644 index 9cdc458c02..0000000000 --- a/src/dr/oldevomodel/treelikelihood/AdvancedTreeLikelihood.java +++ /dev/null @@ -1,680 +0,0 @@ -/* - * AdvancedTreeLikelihood.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.treelikelihood; - -import dr.evolution.alignment.PatternList; -import dr.evolution.tree.NodeRef; -import dr.evolution.tree.Tree; -import dr.evolution.tree.TreeUtils; -import dr.evolution.util.Taxon; -import dr.evolution.util.TaxonList; -import dr.evomodel.branchratemodel.BranchRateModel; -import dr.evomodel.branchratemodel.DefaultBranchRateModel; -import dr.evomodel.tree.TreeChangedEvent; -import dr.oldevomodel.sitemodel.SiteModel; -import dr.oldevomodel.substmodel.FrequencyModel; -import dr.evomodel.tree.TreeModel; -import dr.inference.model.Likelihood; -import dr.inference.model.Model; -import dr.inference.model.Parameter; -import dr.inference.model.Variable; -import dr.xml.*; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Set; -import java.util.logging.Logger; - -/** - * AdvancedTreeLikelihood - implements a Likelihood Function for sequences on a tree. - * This one has some advanced models such as multiple site models for different clades. - * This only makes sense if those clades are being constrained to remain monophyletic. - * - * @author Andrew Rambaut - */ - -@Deprecated // Switching to BEAGLE -public class AdvancedTreeLikelihood extends AbstractTreeLikelihood { - - public static final String ADVANCED_TREE_LIKELIHOOD = "advancedTreeLikelihood"; - public static final String CLADE = "clade"; - public static final String INCLUDE_STEM = "includeStem"; - public static final String TIPS = "tips"; - public static final String DELTA = "delta"; - public static final String USE_AMBIGUITIES = "useAmbiguities"; - public static final String STORE_PARTIALS = "storePartials"; - public static final String USE_SCALING = "useScaling"; - - /** - * Constructor. - */ - public AdvancedTreeLikelihood(PatternList patternList, - TreeModel treeModel, - SiteModel siteModel, - BranchRateModel branchRateModel, - boolean useAmbiguities, - boolean useScaling) { - - super(ADVANCED_TREE_LIKELIHOOD, patternList, treeModel); - - try { - this.siteModel = siteModel; - addModel(siteModel); - - this.frequencyModel = siteModel.getFrequencyModel(); - addModel(frequencyModel); - - if (!siteModel.integrateAcrossCategories()) { - throw new RuntimeException("AdvancedTreeLikelihood can only use SiteModels that require integration across categories"); - } - - this.categoryCount = siteModel.getCategoryCount(); - - if (patternList.getDataType() instanceof dr.evolution.datatype.Nucleotides) { - - if (NativeNucleotideLikelihoodCore.isAvailable()) { - - Logger.getLogger("dr.evomodel").info("AdvancedTreeLikelihood using native nucleotide likelihood core."); - likelihoodCore = new NativeNucleotideLikelihoodCore(); - } else { - - Logger.getLogger("dr.evomodel").info("AdvancedTreeLikelihood Java nucleotide likelihood core."); - likelihoodCore = new NucleotideLikelihoodCore(); - } - - } else if (patternList.getDataType() instanceof dr.evolution.datatype.AminoAcids) { - Logger.getLogger("dr.evomodel").info("AdvancedTreeLikelihood Java amino acid likelihood core."); - likelihoodCore = new AminoAcidLikelihoodCore(); - } else if (patternList.getDataType() instanceof dr.evolution.datatype.Codons) { - Logger.getLogger("dr.evomodel").info("TreeLikelihood using Java general likelihood core"); - likelihoodCore = new GeneralLikelihoodCore(patternList.getStateCount()); - useAmbiguities = true; - } else { - Logger.getLogger("dr.evomodel").info("AdvancedTreeLikelihood using Java general likelihood core"); - likelihoodCore = new GeneralLikelihoodCore(patternList.getStateCount()); - } -// likelihoodCore = new GeneralLikelihoodCore(patternList.getStateCount()); - Logger.getLogger("dr.evomodel").info(" " + (useAmbiguities ? "Using" : "Ignoring") + " ambiguities in tree likelihood."); - Logger.getLogger("dr.evomodel").info(" Partial likelihood scaling " + (useScaling ? "on." : "off.")); - - if (branchRateModel != null) { - this.branchRateModel = branchRateModel; - Logger.getLogger("dr.evomodel").info("Branch rate model used: " + branchRateModel.getModelName()); - } else { - this.branchRateModel = new DefaultBranchRateModel(); - } - addModel(this.branchRateModel); - - probabilities = new double[stateCount * stateCount]; - - likelihoodCore.initialize(nodeCount, patternCount, categoryCount, true); - - int extNodeCount = treeModel.getExternalNodeCount(); - int intNodeCount = treeModel.getInternalNodeCount(); - - for (int i = 0; i < extNodeCount; i++) { - // Find the id of tip i in the patternList - String id = treeModel.getTaxonId(i); - int index = patternList.getTaxonIndex(id); - - if (index == -1) { - throw new TaxonList.MissingTaxonException("Taxon, " + id + ", in tree, " + treeModel.getId() + - ", is not found in patternList, " + patternList.getId()); - } - - if (useAmbiguities) { - setPartials(likelihoodCore, patternList, categoryCount, index, i); - } else { - setStates(likelihoodCore, patternList, index, i); - } - } - - for (int i = 0; i < intNodeCount; i++) { - likelihoodCore.createNodePartials(extNodeCount + i); - } - } catch (TaxonList.MissingTaxonException mte) { - throw new RuntimeException(mte.toString()); - } - - } - - /** - * Add an additional siteModel for a clade in the tree. - */ - public void addCladeSiteModel(SiteModel siteModel, - TaxonList taxonList, - boolean includeStem) throws TreeUtils.MissingTaxonException { - Logger.getLogger("dr.evomodel").info("SiteModel added for clade."); - cladeSiteModels.add(new Clade(siteModel, taxonList, includeStem)); - addModel(siteModel); - commonAncestorsKnown = true; - } - - /** - * Add an additional siteModel for the tips of the tree. - */ - public void addTipsSiteModel(SiteModel siteModel) { - Logger.getLogger("dr.evomodel").info("SiteModel added for tips."); - tipsSiteModel = siteModel; - addModel(siteModel); - } - - private void addDeltaParameter(Parameter deltaParameter, TaxonList taxa) { - this.deltaParameter = deltaParameter; - this.deltaTips = new HashSet(); - - if (taxa != null) { - boolean first = true; - StringBuffer sb = new StringBuffer("Delta parameter added for tips: {"); - for (int i = 0; i < treeModel.getExternalNodeCount(); i++) { - NodeRef node = treeModel.getExternalNode(i); - Taxon taxon = treeModel.getNodeTaxon(node); - if (taxa.getTaxonIndex(taxon) != -1) { - if (!first) { - sb.append(", "); - } else { - first = false; - } - sb.append(taxon.getId()); - deltaTips.add(node.getNumber()); - } - } - sb.append("}"); - - Logger.getLogger("dr.evomodel").info(sb.toString()); - } else { - Logger.getLogger("dr.evomodel").info("Delta parameter added for all tips."); - } - - addVariable(deltaParameter); - } - - // ************************************************************** - // VariableListener IMPLEMENTATION - // ************************************************************** - - protected final void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) { - // deltaParameter has changed... - updateAllNodes(); - super.handleVariableChangedEvent(variable, index, type); - } - - // ************************************************************** - // ModelListener IMPLEMENTATION - // ************************************************************** - - /** - * Handles model changed events from the submodels. - */ - protected void handleModelChangedEvent(Model model, Object object, int index) { - - if (model == treeModel) { - if (object instanceof TreeChangedEvent) { - - if (((TreeChangedEvent) object).isNodeChanged()) { - - updateNodeAndChildren(((TreeChangedEvent) object).getNode()); - - } else { - updateAllNodes(); - - commonAncestorsKnown = false; - - } - } - - } else if (model == branchRateModel) { - updateAllNodes(); - - } else if (model == frequencyModel) { - - updateAllNodes(); - - } else if (model instanceof SiteModel) { - - if (model == siteModel) { - - updateAllNodes(); - - } else if (model == tipsSiteModel) { - - updateAllNodes(); - - } else { - - // find the siteModel in the additional siteModel list - NodeRef node = null; - for (int i = 0, n = cladeSiteModels.size(); i < n; i++) { - Clade clade = cladeSiteModels.get(i); - - if (!commonAncestorsKnown) { - clade.findMRCA(); - } - - if (clade.getSiteModel() == model) { - node = treeModel.getNode(clade.getNode()); - } - } - commonAncestorsKnown = true; - - updateNodeAndDescendents(node); - } - - } else { - - throw new RuntimeException("Unknown componentChangedEvent"); - } - - super.handleModelChangedEvent(model, object, index); - } - - // ************************************************************** - // Model IMPLEMENTATION - // ************************************************************** - - /** - * Stores the additional state other than model components - */ - protected void storeState() { - - if (storePartials) { - likelihoodCore.storeState(); - } - super.storeState(); - - } - - /** - * Restore the additional stored state - */ - protected void restoreState() { - - if (storePartials) { - likelihoodCore.restoreState(); - } else { - updateAllNodes(); - } - - super.restoreState(); - - } - - // ************************************************************** - // Likelihood IMPLEMENTATION - // ************************************************************** - - /** - * Calculate the log likelihood of the current state. - * - * @return the log likelihood. - */ - protected double calculateLogLikelihood() { - - NodeRef root = treeModel.getRoot(); - - if (rootPartials == null) { - rootPartials = new double[patternCount * stateCount]; - } - - if (patternLogLikelihoods == null) { - patternLogLikelihoods = new double[patternCount]; - } - - if (!commonAncestorsKnown) { - for (int i = 0, n = cladeSiteModels.size(); i < n; i++) { - (cladeSiteModels.get(i)).findMRCA(); - } - commonAncestorsKnown = true; - } - - traverse(treeModel, root, siteModel); - - //******************************************************************** - // after traverse all nodes and patterns have been updated -- - //so change flags to reflect this. - for (int i = 0; i < nodeCount; i++) { - updateNode[i] = false; - } - //******************************************************************** - - double logL = 0.0; - - for (int i = 0; i < patternCount; i++) { - logL += patternLogLikelihoods[i] * patternWeights[i]; - } - - return logL; - } - - /** - * Traverse the tree calculating partial likelihoods. - * - * @return whether the partials for this node were recalculated. - */ - private boolean traverse(Tree tree, NodeRef node, SiteModel currentSiteModel) { - - boolean update = false; - - int nodeNum = node.getNumber(); - - SiteModel nextSiteModel = currentSiteModel; - - if (tipsSiteModel != null && tree.isExternal(node)) { - currentSiteModel = tipsSiteModel; - } else { - for (int i = 0, n = cladeSiteModels.size(); i < n; i++) { - Clade clade = cladeSiteModels.get(i); - if (clade.getNode() == nodeNum) { - nextSiteModel = clade.getSiteModel(); - - if (clade.includeStem()) { - currentSiteModel = nextSiteModel; - } - break; - } - } - } - - NodeRef parent = tree.getParent(node); - - // First update the transition probability matrix(ices) for this branch - if (parent != null && updateNode[nodeNum]) { - - double branchRate = branchRateModel.getBranchRate(tree, node); - - // Get the operational time of the branch - double branchTime = branchRate * (tree.getNodeHeight(parent) - tree.getNodeHeight(node)); - if (branchTime < 0.0) { - throw new RuntimeException("Negative branch length: " + branchTime); - } - - likelihoodCore.setNodeMatrixForUpdate(nodeNum); - - if (tree.isExternal(node) && deltaParameter != null && - (deltaTips.size() == 0 || deltaTips.contains(new Integer(node.getNumber())))) { - branchTime += deltaParameter.getParameterValue(0); - } - - for (int i = 0; i < categoryCount; i++) { - double branchLength = currentSiteModel.getRateForCategory(i) * branchTime; - currentSiteModel.getSubstitutionModel().getTransitionProbabilities(branchLength, probabilities); - likelihoodCore.setNodeMatrix(nodeNum, i, probabilities); - } - - update = true; - } - - // If the node is internal, update the partial likelihoods. - if (!tree.isExternal(node)) { - - int nodeCount = tree.getChildCount(node); - if (nodeCount != 2) - throw new RuntimeException("binary trees only!"); - - // Traverse down the two child nodes - NodeRef child1 = tree.getChild(node, 0); - boolean update1 = traverse(tree, child1, nextSiteModel); - - NodeRef child2 = tree.getChild(node, 1); - boolean update2 = traverse(tree, child2, nextSiteModel); - - // If either child node was updated then update this node too - if (update1 || update2) { - - int childNum1 = child1.getNumber(); - int childNum2 = child2.getNumber(); - - likelihoodCore.setNodePartialsForUpdate(nodeNum); - - likelihoodCore.calculatePartials(childNum1, childNum2, nodeNum); - - if (parent == null) { - // No parent this is the root of the tree - - // calculate the pattern likelihoods - double[] frequencies = frequencyModel.getFrequencies(); - double[] proportions = currentSiteModel.getCategoryProportions(); - - likelihoodCore.integratePartials(nodeNum, proportions, rootPartials); - likelihoodCore.calculateLogLikelihoods(rootPartials, frequencies, patternLogLikelihoods); - } - - update = true; - } - } - - return update; - - } - - /** - * The XML parser - */ - public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { - - public String getParserName() { - return ADVANCED_TREE_LIKELIHOOD; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - boolean useAmbiguities = xo.getAttribute(USE_AMBIGUITIES, false); - boolean useScaling = xo.getAttribute(USE_SCALING, false); - - PatternList patternList = (PatternList) xo.getChild(PatternList.class); - TreeModel treeModel = (TreeModel) xo.getChild(TreeModel.class); - SiteModel siteModel = (SiteModel) xo.getChild(SiteModel.class); - - BranchRateModel branchRateModel = (BranchRateModel) xo.getChild(BranchRateModel.class); - - AdvancedTreeLikelihood treeLikelihood = new AdvancedTreeLikelihood(patternList, treeModel, siteModel, - branchRateModel, useAmbiguities, - useScaling); - - if (xo.hasChildNamed(TIPS)) { - SiteModel siteModel2 = (SiteModel) xo.getElementFirstChild(TIPS); - treeLikelihood.addTipsSiteModel(siteModel2); - } - - XMLObject xoc = (XMLObject) xo.getChild(DELTA); - if (xoc != null) { - Parameter deltaParameter = (Parameter) xoc.getChild(Parameter.class); - TaxonList taxa = (TaxonList) xoc.getChild(TaxonList.class); - treeLikelihood.addDeltaParameter(deltaParameter, taxa); - } - - for (int i = 0; i < xo.getChildCount(); i++) { - if (xo.getChild(i) instanceof XMLObject) { - - xoc = (XMLObject) xo.getChild(i); - if (xoc.getName().equals(CLADE)) { - - SiteModel siteModel2 = (SiteModel) xoc.getChild(SiteModel.class); - TaxonList taxonList = (TaxonList) xoc.getChild(TaxonList.class); - - boolean includeStem = false; - - if (xoc.hasAttribute(INCLUDE_STEM)) { - includeStem = xoc.getBooleanAttribute(INCLUDE_STEM); - - if (taxonList.getTaxonCount() == 1 && !includeStem) { - throw new XMLParseException("The site model is only applied to 1 taxon and therefore must include the stem branch"); - } - } else if (taxonList.getTaxonCount() == 1) { - includeStem = true; - } - - try { - - treeLikelihood.addCladeSiteModel(siteModel2, taxonList, includeStem); - - } catch (TreeUtils.MissingTaxonException mte) { - throw new XMLParseException("Taxon, " + mte + ", in " + getParserName() + " was not found in the tree."); - } - } - - } - } - - return treeLikelihood; - } - - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - - public String getParserDescription() { - return "This element represents the likelihood of a patternlist on a tree given the site model."; - } - - public Class getReturnType() { - return Likelihood.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private final XMLSyntaxRule[] rules = { - AttributeRule.newBooleanRule(USE_AMBIGUITIES, true), - // AttributeRule.newBooleanRule(STORE_PARTIALS, true), - AttributeRule.newBooleanRule(USE_SCALING, true), - new ElementRule(TIPS, SiteModel.class, "A siteModel that will be applied only to the tips.", 0, 1), - new ElementRule(DELTA, - new XMLSyntaxRule[]{ - new ElementRule(TaxonList.class, "A set of taxa to which to apply the delta model to", 0, 1), - new ElementRule(Parameter.class, "A parameter that specifies the amount of extra substitutions per site at each tip.", 0, 1), - }, true), - new ElementRule(CLADE, - new XMLSyntaxRule[]{ - AttributeRule.newBooleanRule(INCLUDE_STEM, true, "determines whether or not the stem branch above this clade is included in the siteModel."), - new ElementRule(TaxonList.class, "A set of taxa which defines a clade to apply a different site model to"), - new ElementRule(SiteModel.class, "A siteModel that will be applied only to this clade") - }, 0, Integer.MAX_VALUE), - new ElementRule(PatternList.class), - new ElementRule(TreeModel.class), - new ElementRule(SiteModel.class), - new ElementRule(BranchRateModel.class, true) - }; - }; - - private class Clade { - Clade(SiteModel siteModel, TaxonList taxonList, boolean includeStem) throws TreeUtils.MissingTaxonException { - this.siteModel = siteModel; - this.leafSet = TreeUtils.getLeavesForTaxa(treeModel, taxonList); - this.includeStem = includeStem; - if (taxonList.getTaxonCount() == 1) { - this.includeStem = true; - } - - findMRCA(); - } - - void findMRCA() { - node = TreeUtils.getCommonAncestorNode(treeModel, leafSet).getNumber(); - } - - int getNode() { - return node; - } - - boolean includeStem() { - return includeStem; - } - - SiteModel getSiteModel() { - return this.siteModel; - } - - SiteModel siteModel; - Set leafSet; - int node; - boolean includeStem; - } - - // ************************************************************** - // INSTANCE VARIABLES - // ************************************************************** - - /** - * the frequency model for these sites - */ - protected FrequencyModel frequencyModel = null; - - /** - * the site model for these sites - */ - protected SiteModel siteModel = null; - - /** - * the branch rate model - */ - protected BranchRateModel branchRateModel = null; - - private final boolean storePartials = false; - - - /** - * the site model for the tips - */ - protected SiteModel tipsSiteModel = null; - - protected Parameter deltaParameter = null; - protected Set deltaTips = null; - - /** - * the site models for specific clades - */ - protected ArrayList cladeSiteModels = new ArrayList(); - - private boolean commonAncestorsKnown = true; - - /** - * the root partial likelihoods - */ - protected double[] rootPartials = null; - - /** - * the pattern likelihoods - */ - protected double[] patternLogLikelihoods = null; - - /** - * the number of rate categories - */ - protected int categoryCount; - - /** - * an array used to store transition probabilities - */ - protected double[] probabilities; - - /** - * the LikelihoodCore - */ - protected LikelihoodCore likelihoodCore; -} diff --git a/src/dr/oldevomodel/treelikelihood/AminoAcidLikelihoodCore.java b/src/dr/oldevomodel/treelikelihood/AminoAcidLikelihoodCore.java deleted file mode 100644 index 60d425eda9..0000000000 --- a/src/dr/oldevomodel/treelikelihood/AminoAcidLikelihoodCore.java +++ /dev/null @@ -1,570 +0,0 @@ -/* - * AminoAcidLikelihoodCore.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.treelikelihood; - -/** - * AminoAcidLikelihoodCore - An implementation of LikelihoodCore for Amino Acid data - * - * - * @author Andrew Rambaut - */ - -@Deprecated // Switching to BEAGLE -public class AminoAcidLikelihoodCore extends AbstractLikelihoodCore { - - /** - * Constructor - * - */ - public AminoAcidLikelihoodCore() { - super(20); - } - - /** - * Calculates partial likelihoods at a node when both children have states. - */ - protected void calculateStatesStatesPruning(int[] states1, double[] matrices1, - int[] states2, double[] matrices2, - double[] partials3) - { - int v = 0; - int u = 0; - for (int j = 0; j < matrixCount; j++) { - - for (int k = 0; k < patternCount; k++) { - - int w = u; - - int state1 = states1[k]; - int state2 = states2[k]; - - if (state1 < 20 && state2 < 20) { - - partials3[v] = matrices1[w + state1] * matrices2[w + state2]; - v++; w += 20; - partials3[v] = matrices1[w + state1] * matrices2[w + state2]; - v++; w += 20; - partials3[v] = matrices1[w + state1] * matrices2[w + state2]; - v++; w += 20; - partials3[v] = matrices1[w + state1] * matrices2[w + state2]; - v++; w += 20; - - partials3[v] = matrices1[w + state1] * matrices2[w + state2]; - v++; w += 20; - partials3[v] = matrices1[w + state1] * matrices2[w + state2]; - v++; w += 20; - partials3[v] = matrices1[w + state1] * matrices2[w + state2]; - v++; w += 20; - partials3[v] = matrices1[w + state1] * matrices2[w + state2]; - v++; w += 20; - - partials3[v] = matrices1[w + state1] * matrices2[w + state2]; - v++; w += 20; - partials3[v] = matrices1[w + state1] * matrices2[w + state2]; - v++; w += 20; - partials3[v] = matrices1[w + state1] * matrices2[w + state2]; - v++; w += 20; - partials3[v] = matrices1[w + state1] * matrices2[w + state2]; - v++; w += 20; - - partials3[v] = matrices1[w + state1] * matrices2[w + state2]; - v++; w += 20; - partials3[v] = matrices1[w + state1] * matrices2[w + state2]; - v++; w += 20; - partials3[v] = matrices1[w + state1] * matrices2[w + state2]; - v++; w += 20; - partials3[v] = matrices1[w + state1] * matrices2[w + state2]; - v++; w += 20; - - partials3[v] = matrices1[w + state1] * matrices2[w + state2]; - v++; w += 20; - partials3[v] = matrices1[w + state1] * matrices2[w + state2]; - v++; w += 20; - partials3[v] = matrices1[w + state1] * matrices2[w + state2]; - v++; w += 20; - partials3[v] = matrices1[w + state1] * matrices2[w + state2]; - v++; w += 20; - } else if (state1 < 20) { - // child 2 has a gap or unknown state so don't use it - - partials3[v] = matrices1[w + state1]; - v++; w += 20; - partials3[v] = matrices1[w + state1]; - v++; w += 20; - partials3[v] = matrices1[w + state1]; - v++; w += 20; - partials3[v] = matrices1[w + state1]; - v++; w += 20; - - partials3[v] = matrices1[w + state1]; - v++; w += 20; - partials3[v] = matrices1[w + state1]; - v++; w += 20; - partials3[v] = matrices1[w + state1]; - v++; w += 20; - partials3[v] = matrices1[w + state1]; - v++; w += 20; - - partials3[v] = matrices1[w + state1]; - v++; w += 20; - partials3[v] = matrices1[w + state1]; - v++; w += 20; - partials3[v] = matrices1[w + state1]; - v++; w += 20; - partials3[v] = matrices1[w + state1]; - v++; w += 20; - - partials3[v] = matrices1[w + state1]; - v++; w += 20; - partials3[v] = matrices1[w + state1]; - v++; w += 20; - partials3[v] = matrices1[w + state1]; - v++; w += 20; - partials3[v] = matrices1[w + state1]; - v++; w += 20; - - partials3[v] = matrices1[w + state1]; - v++; w += 20; - partials3[v] = matrices1[w + state1]; - v++; w += 20; - partials3[v] = matrices1[w + state1]; - v++; w += 20; - partials3[v] = matrices1[w + state1]; - v++; w += 20; - - } else if (state2 < 20) { - // child 2 has a gap or unknown state so don't use it - partials3[v] = matrices2[w + state2]; - v++; w += 20; - partials3[v] = matrices2[w + state2]; - v++; w += 20; - partials3[v] = matrices2[w + state2]; - v++; w += 20; - partials3[v] = matrices2[w + state2]; - v++; w += 20; - - partials3[v] = matrices2[w + state2]; - v++; w += 20; - partials3[v] = matrices2[w + state2]; - v++; w += 20; - partials3[v] = matrices2[w + state2]; - v++; w += 20; - partials3[v] = matrices2[w + state2]; - v++; w += 20; - - partials3[v] = matrices2[w + state2]; - v++; w += 20; - partials3[v] = matrices2[w + state2]; - v++; w += 20; - partials3[v] = matrices2[w + state2]; - v++; w += 20; - partials3[v] = matrices2[w + state2]; - v++; w += 20; - - partials3[v] = matrices2[w + state2]; - v++; w += 20; - partials3[v] = matrices2[w + state2]; - v++; w += 20; - partials3[v] = matrices2[w + state2]; - v++; w += 20; - partials3[v] = matrices2[w + state2]; - v++; w += 20; - - partials3[v] = matrices2[w + state2]; - v++; w += 20; - partials3[v] = matrices2[w + state2]; - v++; w += 20; - partials3[v] = matrices2[w + state2]; - v++; w += 20; - partials3[v] = matrices2[w + state2]; - v++; w += 20; - - } else { - // both children have a gap or unknown state so set partials to 1 - partials3[v] = 1.0; - v++; - partials3[v] = 1.0; - v++; - partials3[v] = 1.0; - v++; - partials3[v] = 1.0; - v++; - - partials3[v] = 1.0; - v++; - partials3[v] = 1.0; - v++; - partials3[v] = 1.0; - v++; - partials3[v] = 1.0; - v++; - - partials3[v] = 1.0; - v++; - partials3[v] = 1.0; - v++; - partials3[v] = 1.0; - v++; - partials3[v] = 1.0; - v++; - - partials3[v] = 1.0; - v++; - partials3[v] = 1.0; - v++; - partials3[v] = 1.0; - v++; - partials3[v] = 1.0; - v++; - - partials3[v] = 1.0; - v++; - partials3[v] = 1.0; - v++; - partials3[v] = 1.0; - v++; - partials3[v] = 1.0; - v++; - } - } - - u += matrixSize; - } - } - - /** - * Calculates partial likelihoods at a node when one child has states and one has partials. - */ - protected void calculateStatesPartialsPruning( int[] states1, double[] matrices1, - double[] partials2, double[] matrices2, - double[] partials3) - { - int u = 0; - int v = 0; - int w = 0; - int x, y; - - for (int l = 0; l < matrixCount; l++) { - for (int k = 0; k < patternCount; k++) { - - int state1 = states1[k]; - - if (state1 < 20) { - - double sum; - - x = w; - for (int i = 0; i < 20; i++) { - - y = v; - double value = matrices1[x + state1]; - sum = matrices2[x] * partials2[y]; x++; y++; - sum += matrices2[x] * partials2[y]; x++; y++; - sum += matrices2[x] * partials2[y]; x++; y++; - sum += matrices2[x] * partials2[y]; x++; y++; - sum += matrices2[x] * partials2[y]; x++; y++; - sum += matrices2[x] * partials2[y]; x++; y++; - sum += matrices2[x] * partials2[y]; x++; y++; - sum += matrices2[x] * partials2[y]; x++; y++; - sum += matrices2[x] * partials2[y]; x++; y++; - sum += matrices2[x] * partials2[y]; x++; y++; - sum += matrices2[x] * partials2[y]; x++; y++; - sum += matrices2[x] * partials2[y]; x++; y++; - sum += matrices2[x] * partials2[y]; x++; y++; - sum += matrices2[x] * partials2[y]; x++; y++; - sum += matrices2[x] * partials2[y]; x++; y++; - sum += matrices2[x] * partials2[y]; x++; y++; - sum += matrices2[x] * partials2[y]; x++; y++; - sum += matrices2[x] * partials2[y]; x++; y++; - sum += matrices2[x] * partials2[y]; x++; y++; - sum += matrices2[x] * partials2[y]; x++; y++; - partials3[u] = value * sum; - u++; - } - - v += 20; - - } else { - // Child 1 has a gap or unknown state so don't use it - - double sum; - - x = w; - for (int i = 0; i < 20; i++) { - - y = v; - sum = matrices2[x] * partials2[y]; x++; y++; - sum += matrices2[x] * partials2[y]; x++; y++; - sum += matrices2[x] * partials2[y]; x++; y++; - sum += matrices2[x] * partials2[y]; x++; y++; - sum += matrices2[x] * partials2[y]; x++; y++; - sum += matrices2[x] * partials2[y]; x++; y++; - sum += matrices2[x] * partials2[y]; x++; y++; - sum += matrices2[x] * partials2[y]; x++; y++; - sum += matrices2[x] * partials2[y]; x++; y++; - sum += matrices2[x] * partials2[y]; x++; y++; - sum += matrices2[x] * partials2[y]; x++; y++; - sum += matrices2[x] * partials2[y]; x++; y++; - sum += matrices2[x] * partials2[y]; x++; y++; - sum += matrices2[x] * partials2[y]; x++; y++; - sum += matrices2[x] * partials2[y]; x++; y++; - sum += matrices2[x] * partials2[y]; x++; y++; - sum += matrices2[x] * partials2[y]; x++; y++; - sum += matrices2[x] * partials2[y]; x++; y++; - sum += matrices2[x] * partials2[y]; x++; y++; - sum += matrices2[x] * partials2[y]; x++; y++; - partials3[u] = sum; - u++; - } - - v += 20; - } - } - - w += matrixSize; - } - } - - /** - * Calculates partial likelihoods at a node when both children have partials. - */ - protected void calculatePartialsPartialsPruning(double[] partials1, double[] matrices1, - double[] partials2, double[] matrices2, - double[] partials3) - { - - double sum1, sum2; - - int u = 0; - int v = 0; - int w = 0; - int x, y; - - for (int l = 0; l < matrixCount; l++) { - for (int k = 0; k < patternCount; k++) { - - x = w; - for (int i = 0; i < 20; i++) { - - y = v; - sum1 = matrices1[x] * partials1[y]; - sum2 = matrices2[x] * partials2[y]; x++; y++; - sum1 += matrices1[x] * partials1[y]; - sum2 += matrices2[x] * partials2[y]; x++; y++; - sum1 += matrices1[x] * partials1[y]; - sum2 += matrices2[x] * partials2[y]; x++; y++; - sum1 += matrices1[x] * partials1[y]; - sum2 += matrices2[x] * partials2[y]; x++; y++; - sum1 += matrices1[x] * partials1[y]; - sum2 += matrices2[x] * partials2[y]; x++; y++; - sum1 += matrices1[x] * partials1[y]; - sum2 += matrices2[x] * partials2[y]; x++; y++; - sum1 += matrices1[x] * partials1[y]; - sum2 += matrices2[x] * partials2[y]; x++; y++; - sum1 += matrices1[x] * partials1[y]; - sum2 += matrices2[x] * partials2[y]; x++; y++; - sum1 += matrices1[x] * partials1[y]; - sum2 += matrices2[x] * partials2[y]; x++; y++; - sum1 += matrices1[x] * partials1[y]; - sum2 += matrices2[x] * partials2[y]; x++; y++; - sum1 += matrices1[x] * partials1[y]; - sum2 += matrices2[x] * partials2[y]; x++; y++; - sum1 += matrices1[x] * partials1[y]; - sum2 += matrices2[x] * partials2[y]; x++; y++; - sum1 += matrices1[x] * partials1[y]; - sum2 += matrices2[x] * partials2[y]; x++; y++; - sum1 += matrices1[x] * partials1[y]; - sum2 += matrices2[x] * partials2[y]; x++; y++; - sum1 += matrices1[x] * partials1[y]; - sum2 += matrices2[x] * partials2[y]; x++; y++; - sum1 += matrices1[x] * partials1[y]; - sum2 += matrices2[x] * partials2[y]; x++; y++; - sum1 += matrices1[x] * partials1[y]; - sum2 += matrices2[x] * partials2[y]; x++; y++; - sum1 += matrices1[x] * partials1[y]; - sum2 += matrices2[x] * partials2[y]; x++; y++; - sum1 += matrices1[x] * partials1[y]; - sum2 += matrices2[x] * partials2[y]; x++; y++; - sum1 += matrices1[x] * partials1[y]; - sum2 += matrices2[x] * partials2[y]; x++; y++; - - partials3[u] = sum1 * sum2; - u++; - } - - v += 20; - } - - w += matrixSize; - } - - } - - - /** - * Calculates partial likelihoods at a node when both children have states. - */ - protected void calculateStatesStatesPruning(int[] states1, double[] matrices1, - int[] states2, double[] matrices2, - double[] partials3, int[] matrixMap) - { - throw new RuntimeException("calculateStatesStatesPruning not implemented using matrixMap"); - } - - /** - * Calculates partial likelihoods at a node when one child has states and one has partials. - */ - protected void calculateStatesPartialsPruning( int[] states1, double[] matrices1, - double[] partials2, double[] matrices2, - double[] partials3, int[] matrixMap) - { - throw new RuntimeException("calculateStatesStatesPruning not implemented using matrixMap"); - } - - /** - * Calculates partial likelihoods at a node when both children have partials. - */ - protected void calculatePartialsPartialsPruning(double[] partials1, double[] matrices1, - double[] partials2, double[] matrices2, - double[] partials3, int[] matrixMap) - { - throw new RuntimeException("calculateStatesStatesPruning not implemented using matrixMap"); - } - - /** - * Integrates partials across categories. - * @param inPartials the array of partials to be integrated - * @param proportions the proportions of sites in each category - * @param outPartials an array into which the partials will go - */ - public void calculateIntegratePartials(double[] inPartials, double[] proportions, double[] outPartials) - { - int u = 0; - int v = 0; - for (int k = 0; k < patternCount; k++) { - - outPartials[u] = inPartials[v] * proportions[0]; u++; v++; - outPartials[u] = inPartials[v] * proportions[0]; u++; v++; - outPartials[u] = inPartials[v] * proportions[0]; u++; v++; - outPartials[u] = inPartials[v] * proportions[0]; u++; v++; - - outPartials[u] = inPartials[v] * proportions[0]; u++; v++; - outPartials[u] = inPartials[v] * proportions[0]; u++; v++; - outPartials[u] = inPartials[v] * proportions[0]; u++; v++; - outPartials[u] = inPartials[v] * proportions[0]; u++; v++; - - outPartials[u] = inPartials[v] * proportions[0]; u++; v++; - outPartials[u] = inPartials[v] * proportions[0]; u++; v++; - outPartials[u] = inPartials[v] * proportions[0]; u++; v++; - outPartials[u] = inPartials[v] * proportions[0]; u++; v++; - - outPartials[u] = inPartials[v] * proportions[0]; u++; v++; - outPartials[u] = inPartials[v] * proportions[0]; u++; v++; - outPartials[u] = inPartials[v] * proportions[0]; u++; v++; - outPartials[u] = inPartials[v] * proportions[0]; u++; v++; - - outPartials[u] = inPartials[v] * proportions[0]; u++; v++; - outPartials[u] = inPartials[v] * proportions[0]; u++; v++; - outPartials[u] = inPartials[v] * proportions[0]; u++; v++; - outPartials[u] = inPartials[v] * proportions[0]; u++; v++; - } - - - for (int j = 1; j < matrixCount; j++) { - u = 0; - for (int k = 0; k < patternCount; k++) { - outPartials[u] += inPartials[v] * proportions[j]; u++; v++; - outPartials[u] += inPartials[v] * proportions[j]; u++; v++; - outPartials[u] += inPartials[v] * proportions[j]; u++; v++; - outPartials[u] += inPartials[v] * proportions[j]; u++; v++; - - outPartials[u] += inPartials[v] * proportions[j]; u++; v++; - outPartials[u] += inPartials[v] * proportions[j]; u++; v++; - outPartials[u] += inPartials[v] * proportions[j]; u++; v++; - outPartials[u] += inPartials[v] * proportions[j]; u++; v++; - - outPartials[u] += inPartials[v] * proportions[j]; u++; v++; - outPartials[u] += inPartials[v] * proportions[j]; u++; v++; - outPartials[u] += inPartials[v] * proportions[j]; u++; v++; - outPartials[u] += inPartials[v] * proportions[j]; u++; v++; - - outPartials[u] += inPartials[v] * proportions[j]; u++; v++; - outPartials[u] += inPartials[v] * proportions[j]; u++; v++; - outPartials[u] += inPartials[v] * proportions[j]; u++; v++; - outPartials[u] += inPartials[v] * proportions[j]; u++; v++; - - outPartials[u] += inPartials[v] * proportions[j]; u++; v++; - outPartials[u] += inPartials[v] * proportions[j]; u++; v++; - outPartials[u] += inPartials[v] * proportions[j]; u++; v++; - outPartials[u] += inPartials[v] * proportions[j]; u++; v++; - - } - } - } - - /** - * Calculates site likelihoods at a node. - * @param partials the partials used to calculate the likelihoods - * @param frequencies an array of state frequencies - * @param outLogLikelihoods an array into which the likelihoods will go - */ - public void calculateLogLikelihoods(double[] partials, double[] frequencies, double[] outLogLikelihoods) - { - int v = 0; - for (int k = 0; k < patternCount; k++) { - - double sum = frequencies[0] * partials[v]; v++; - sum += frequencies[1] * partials[v]; v++; - sum += frequencies[2] * partials[v]; v++; - sum += frequencies[3] * partials[v]; v++; - - sum += frequencies[4] * partials[v]; v++; - sum += frequencies[5] * partials[v]; v++; - sum += frequencies[6] * partials[v]; v++; - sum += frequencies[7] * partials[v]; v++; - - sum += frequencies[8] * partials[v]; v++; - sum += frequencies[9] * partials[v]; v++; - sum += frequencies[10] * partials[v]; v++; - sum += frequencies[11] * partials[v]; v++; - - sum += frequencies[12] * partials[v]; v++; - sum += frequencies[13] * partials[v]; v++; - sum += frequencies[14] * partials[v]; v++; - sum += frequencies[15] * partials[v]; v++; - - sum += frequencies[16] * partials[v]; v++; - sum += frequencies[17] * partials[v]; v++; - sum += frequencies[18] * partials[v]; v++; - sum += frequencies[19] * partials[v]; v++; - outLogLikelihoods[k] = Math.log(sum) + getLogScalingFactor(k); - } - } - -} - diff --git a/src/dr/oldevomodel/treelikelihood/AncestralStateTreeLikelihood.java b/src/dr/oldevomodel/treelikelihood/AncestralStateTreeLikelihood.java deleted file mode 100644 index 67d8b93406..0000000000 --- a/src/dr/oldevomodel/treelikelihood/AncestralStateTreeLikelihood.java +++ /dev/null @@ -1,387 +0,0 @@ -/* - * AncestralStateTreeLikelihood.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.treelikelihood; - -import dr.evolution.alignment.PatternList; -import dr.evolution.datatype.DataType; -import dr.evolution.datatype.GeneralDataType; -import dr.evolution.tree.NodeRef; -import dr.evolution.tree.Tree; -import dr.evolution.tree.TreeTrait; -import dr.evolution.tree.TreeTraitProvider; -import dr.evomodel.branchratemodel.BranchRateModel; -import dr.oldevomodel.sitemodel.SiteModel; -import dr.evomodel.tree.TreeModel; -import dr.inference.model.Model; -import dr.math.MathUtils; - -import java.util.logging.Logger; - -/** - * @author Marc A. Suchard - */ -@Deprecated // Switching to BEAGLE -public class AncestralStateTreeLikelihood extends TreeLikelihood implements TreeTraitProvider { - public static final String STATES_KEY = "states"; - -// private boolean useExtraReconstructedStates = false; - - - /** - * Constructor. - * Now also takes a DataType so that ancestral states are printed using data codes - * - * @param patternList - - * @param treeModel - - * @param siteModel - - * @param branchRateModel - - * @param useAmbiguities - - * @param storePartials - - * @param dataType - need to provide the data-type, so that corrent data characters can be returned - * @param tag - string label for reconstruction characters in tree log - * @param forceRescaling - - * @param useMAP - perform maximum aposteriori reconstruction - * @param returnML - report integrate likelihood of tip data - */ - public AncestralStateTreeLikelihood(PatternList patternList, TreeModel treeModel, - SiteModel siteModel, BranchRateModel branchRateModel, - boolean useAmbiguities, boolean storePartials, - final DataType dataType, - final String tag, - boolean forceRescaling, - boolean useMAP, - boolean returnML) { - super(patternList, treeModel, siteModel, branchRateModel, null, useAmbiguities, false, storePartials, - false, forceRescaling); - this.dataType = dataType; - this.tag = tag; - - reconstructedStates = new int[treeModel.getNodeCount()][patternCount]; - storedReconstructedStates = new int[treeModel.getNodeCount()][patternCount]; - - this.useMAP = useMAP; - this.returnMarginalLogLikelihood = returnML; - - treeTraits.addTrait(STATES_KEY, new TreeTrait.IA() { - public String getTraitName() { - return tag; - } - - public Intent getIntent() { - return Intent.NODE; - } - - public int[] getTrait(Tree tree, NodeRef node) { - return getStatesForNode(tree,node); - } - - public String getTraitString(Tree tree, NodeRef node) { - return formattedState(getStatesForNode(tree,node), dataType); - } - }); - - if (useAmbiguities) { - Logger.getLogger("dr.evomodel.treelikelihood").info("Ancestral reconstruction using ambiguities is currently "+ - "not support without BEAGLE"); - System.exit(-1); - } - - } - - public AncestralStateTreeLikelihood(PatternList patternList, TreeModel treeModel, - SiteModel siteModel, BranchRateModel branchRateModel, - boolean useAmbiguities, boolean storePartials, - DataType dataType, - String tag, - boolean forceRescaling) { - this(patternList, treeModel, siteModel, branchRateModel, useAmbiguities, - storePartials, dataType, tag, forceRescaling, false, true); - } - - public void storeState() { - - super.storeState(); - - for (int i = 0; i < reconstructedStates.length; i++) { - System.arraycopy(reconstructedStates[i], 0, storedReconstructedStates[i], 0, reconstructedStates[i].length); - } - - storedAreStatesRedrawn = areStatesRedrawn; - storedJointLogLikelihood = jointLogLikelihood; - } - - public void restoreState() { - - super.restoreState(); - - int[][] temp = reconstructedStates; - reconstructedStates = storedReconstructedStates; - storedReconstructedStates = temp; - - areStatesRedrawn = storedAreStatesRedrawn; - jointLogLikelihood = storedJointLogLikelihood; - } - - public DataType getDataType() { - return dataType; - } - - public int[] getStatesForNode(Tree tree, NodeRef node) { - if (tree != treeModel) { - throw new RuntimeException("Can only reconstruct states on treeModel given to constructor"); - } - - if (!likelihoodKnown) { - calculateLogLikelihood(); - likelihoodKnown = true; - } - - if (!areStatesRedrawn) { - redrawAncestralStates(); - } - return reconstructedStates[node.getNumber()]; - } - - - public void redrawAncestralStates() { - jointLogLikelihood = 0; - traverseSample(treeModel, treeModel.getRoot(), null); - areStatesRedrawn = true; - } - -// private boolean checkConditioning = true; - - - protected void handleModelChangedEvent(Model model, Object object, int index) { - super.handleModelChangedEvent(model, object, index); - fireModelChanged(model); - - } - - protected double calculateLogLikelihood() { - - areStatesRedrawn = false; - double marginalLogLikelihood = super.calculateLogLikelihood(); - if (returnMarginalLogLikelihood) { - return marginalLogLikelihood; - } - // redraw states and return joint density of drawn states - redrawAncestralStates(); - return jointLogLikelihood; - } - - protected TreeTraitProvider.Helper treeTraits = new Helper(); - - public TreeTrait[] getTreeTraits() { - return treeTraits.getTreeTraits(); - } - - public TreeTrait getTreeTrait(String key) { - return treeTraits.getTreeTrait(key); - } - - - private static String formattedState(int[] state, DataType dataType) { - StringBuffer sb = new StringBuffer(); - sb.append("\""); - if (dataType instanceof GeneralDataType) { - boolean first = true; - for (int i : state) { - if (!first) { - sb.append(" "); - } else { - first = false; - } - - sb.append(dataType.getCode(i)); - } - - } else { - for (int i : state) { - sb.append(dataType.getChar(i)); - } - } - sb.append("\""); - return sb.toString(); - } - - private int drawChoice(double[] measure) { - if (useMAP) { - double max = measure[0]; - int choice = 0; - for (int i = 1; i < measure.length; i++) { - if (measure[i] > max) { - max = measure[i]; - choice = i; - } - } - return choice; - } else { - return MathUtils.randomChoicePDF(measure); - } - } - - /** - * Traverse (pre-order) the tree sampling the internal node states. - * - * @param tree - TreeModel on which to perform sampling - * @param node - current node - * @param parentState - character state of the parent node to 'node' - */ - public void traverseSample(TreeModel tree, NodeRef node, int[] parentState) { - - int nodeNum = node.getNumber(); - - NodeRef parent = tree.getParent(node); - - // This function assumes that all partial likelihoods have already been calculated - // If the node is internal, then sample its state given the state of its parent (pre-order traversal). - - double[] conditionalProbabilities = new double[stateCount]; - int[] state = new int[patternCount]; - - if (!tree.isExternal(node)) { - - if (parent == null) { - - double[] rootPartials = getRootPartials(); - - // This is the root node - for (int j = 0; j < patternCount; j++) { - - System.arraycopy(rootPartials, j * stateCount, conditionalProbabilities, 0, stateCount); - double[] frequencies = frequencyModel.getFrequencies(); - for (int i = 0; i < stateCount; i++) { - conditionalProbabilities[i] *= frequencies[i]; - } - try { - state[j] = drawChoice(conditionalProbabilities); - } catch (Error e) { - System.err.println(e.toString()); - System.err.println("Please report error to Marc"); - state[j] = 0; - } - reconstructedStates[nodeNum][j] = state[j]; - - //System.out.println("Pr(j) = " + frequencies[state[j]]); - jointLogLikelihood += Math.log(frequencies[state[j]]); - } - - } else { - - // This is an internal node, but not the root - double[] partialLikelihood = new double[stateCount * patternCount]; - if (categoryCount > 1) - throw new RuntimeException("Reconstruction not implemented for multiple categories yet."); - - likelihoodCore.getPartials(nodeNum, partialLikelihood); - -// final double branchRate = branchRateModel.getBranchRate(tree, node); -// -// // Get the operational time of the branch -// final double branchTime = branchRate * ( tree.getNodeHeight(parent) - tree.getNodeHeight(node) ); -// -// for (int i = 0; i < categoryCount; i++) { -// -// siteModel.getTransitionProbabilitiesForCategory(i, branchTime, probabilities); -// -// } -// - - - - - ((AbstractLikelihoodCore) likelihoodCore).getNodeMatrix(nodeNum, 0, probabilities); - - - for (int j = 0; j < patternCount; j++) { - - int parentIndex = parentState[j] * stateCount; - int childIndex = j * stateCount; - - for (int i = 0; i < stateCount; i++) { - conditionalProbabilities[i] = partialLikelihood[childIndex + i] * probabilities[parentIndex + i]; - } - - state[j] = drawChoice(conditionalProbabilities); - reconstructedStates[nodeNum][j] = state[j]; - - double contrib = probabilities[parentIndex + state[j]]; - //System.out.println("Pr(" + parentState[j] + ", " + state[j] + ") = " + contrib); - jointLogLikelihood += Math.log(contrib); - } - } - - // Traverse down the two child nodes - NodeRef child1 = tree.getChild(node, 0); - traverseSample(tree, child1, state); - - NodeRef child2 = tree.getChild(node, 1); - traverseSample(tree, child2, state); - } else { - - // This is an external leaf - - ((AbstractLikelihoodCore) likelihoodCore).getNodeStates(nodeNum, reconstructedStates[nodeNum]); - - // Check for ambiguity codes and sample them - - for (int j = 0; j < patternCount; j++) { - - final int thisState = reconstructedStates[nodeNum][j]; - final int parentIndex = parentState[j] * stateCount; - ((AbstractLikelihoodCore) likelihoodCore).getNodeMatrix(nodeNum, 0, probabilities); - if (dataType.isAmbiguousState(thisState)) { - - System.arraycopy(probabilities, parentIndex, conditionalProbabilities, 0, stateCount); - reconstructedStates[nodeNum][j] = drawChoice(conditionalProbabilities); - } - - double contrib = probabilities[parentIndex + reconstructedStates[nodeNum][j]]; - //System.out.println("Pr(" + parentState[j] + ", " + reconstructedStates[nodeNum][j] + ") = " + contrib); - jointLogLikelihood += Math.log(contrib); - } - } - } - - private DataType dataType; - private int[][] reconstructedStates; - private int[][] storedReconstructedStates; - - private String tag; - private boolean areStatesRedrawn = false; - private boolean storedAreStatesRedrawn = false; - - private boolean useMAP = false; - private boolean returnMarginalLogLikelihood = true; - - private double jointLogLikelihood; - private double storedJointLogLikelihood; - - -} diff --git a/src/dr/oldevomodel/treelikelihood/ArbitraryPrecisionLikelihoodCore.java b/src/dr/oldevomodel/treelikelihood/ArbitraryPrecisionLikelihoodCore.java deleted file mode 100644 index 6b9b4d22bb..0000000000 --- a/src/dr/oldevomodel/treelikelihood/ArbitraryPrecisionLikelihoodCore.java +++ /dev/null @@ -1,568 +0,0 @@ -/* - * ArbitraryPrecisionLikelihoodCore.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.treelikelihood; - -import java.math.BigDecimal; -import java.math.MathContext; - -/** - * GeneralLikelihoodCore - An implementation of LikelihoodCore for any data - * - * @author Andrew Rambaut - */ - -@Deprecated // Switching to BEAGLE -public class ArbitraryPrecisionLikelihoodCore implements LikelihoodCore { - - private MathContext precision; - - private int stateCount; - private int nodeCount; - private int patternCount; - private int partialsSize; - private int matrixSize; - private int matrixCount; - - private boolean integrateCategories; - - private BigDecimal[][][] partials; - - private int[][] states; - - private BigDecimal[][][] matrices; - - private int[] currentMatricesIndices; - private int[] storedMatricesIndices; - private int[] currentPartialsIndices; - private int[] storedPartialsIndices; - - - /** - * Constructor - * - * @param stateCount number of states - */ - public ArbitraryPrecisionLikelihoodCore(int stateCount, int precision) { - this.stateCount = stateCount; - this.precision = new MathContext(precision); - } - - /** - * initializes partial likelihood arrays. - * - * @param nodeCount the number of nodes in the tree - * @param patternCount the number of patterns - * @param matrixCount the number of matrices (i.e., number of categories) - * @param integrateCategories whether sites are being integrated over all matrices - */ - public void initialize(int nodeCount, int patternCount, int matrixCount, boolean integrateCategories) { - - this.nodeCount = nodeCount; - this.patternCount = patternCount; - this.matrixCount = matrixCount; - - this.integrateCategories = integrateCategories; - - if (integrateCategories) { - partialsSize = patternCount * stateCount * matrixCount; - } else { - partialsSize = patternCount * stateCount; - } - - partials = new BigDecimal[2][nodeCount][]; - - currentMatricesIndices = new int[nodeCount]; - storedMatricesIndices = new int[nodeCount]; - - currentPartialsIndices = new int[nodeCount]; - storedPartialsIndices = new int[nodeCount]; - - states = new int[nodeCount][]; - - for (int i = 0; i < nodeCount; i++) { - partials[0][i] = null; - partials[1][i] = null; - - states[i] = null; - } - - matrixSize = stateCount * stateCount; - - matrices = new BigDecimal[2][nodeCount][matrixCount * matrixSize]; - } - - /** - * cleans up and deallocates arrays. - */ - public void finalize() throws java.lang.Throwable { - super.finalize(); - - nodeCount = 0; - patternCount = 0; - matrixCount = 0; - - partials = null; - currentPartialsIndices = null; - storedPartialsIndices = null; - states = null; - matrices = null; - currentMatricesIndices = null; - storedMatricesIndices = null; - } - - /** - * Allocates partials for a node - */ - public void createNodePartials(int nodeIndex) { - - this.partials[0][nodeIndex] = new BigDecimal[partialsSize]; - this.partials[1][nodeIndex] = new BigDecimal[partialsSize]; - } - - /** - * Sets partials for a node - */ - public void setNodePartials(int nodeIndex, double[] partials) { - - if (this.partials[0][nodeIndex] == null) { - createNodePartials(nodeIndex); - } - if (partials.length < partialsSize) { - int k = 0; - for (int i = 0; i < matrixCount; i++) { - for (int j = 0; j < partials.length; j++) { - this.partials[0][nodeIndex][k] = new BigDecimal(partials[j], precision); - k++; - } - } - } else { - for (int j = 0; j < partials.length; j++) { - this.partials[0][nodeIndex][j] = new BigDecimal(partials[j], precision); - } - } - } - - /** - * Allocates states for a node - */ - public void createNodeStates(int nodeIndex) { - - this.states[nodeIndex] = new int[patternCount]; - } - - /** - * Sets states for a node - */ - public void setNodeStates(int nodeIndex, int[] states) { - - if (this.states[nodeIndex] == null) { - createNodeStates(nodeIndex); - } - System.arraycopy(states, 0, this.states[nodeIndex], 0, patternCount); - } - - /** - * Gets states for a node - */ - public void getNodeStates(int nodeIndex, int[] states) { - System.arraycopy(this.states[nodeIndex], 0, states, 0, patternCount); - } - - public void setNodeMatrixForUpdate(int nodeIndex) { - currentMatricesIndices[nodeIndex] = 1 - currentMatricesIndices[nodeIndex]; - - } - - /** - * Sets probability matrix for a node - */ - public void setNodeMatrix(int nodeIndex, int matrixIndex, double[] matrix) { - - for (int j = 0; j < matrixSize; j++) { - matrices[currentMatricesIndices[nodeIndex]][nodeIndex][(matrixIndex * matrixSize) + j] = new BigDecimal(matrix[j], precision); - } - } - - /** - * Gets probability matrix for a node - */ - public void getNodeMatrix(int nodeIndex, int matrixIndex, double[] matrix) { - for (int j = 0; j < matrixSize; j++) { - matrix[j] = matrices[currentMatricesIndices[nodeIndex]][nodeIndex][(matrixIndex * matrixSize) + j].doubleValue(); - } - } - - public void setNodePartialsForUpdate(int nodeIndex) { - currentPartialsIndices[nodeIndex] = 1 - currentPartialsIndices[nodeIndex]; - } - - /** - * Get the currently updating node partials for direct access - * - * @param nodeIndex - */ - public void setCurrentNodePartials(int nodeIndex, double[] partials) { - throw new UnsupportedOperationException("setCurrentNodePartials is not supported by ArbitraryPrecisionLikelihoodCore"); - } - - /** - * Calculates partial likelihoods at a node. - * - * @param nodeIndex1 the 'child 1' node - * @param nodeIndex2 the 'child 2' node - * @param nodeIndex3 the 'parent' node - */ - public void calculatePartials(int nodeIndex1, int nodeIndex2, int nodeIndex3) { - if (states[nodeIndex1] != null) { - if (states[nodeIndex2] != null) { - calculateStatesStatesPruning( - states[nodeIndex1], matrices[currentMatricesIndices[nodeIndex1]][nodeIndex1], - states[nodeIndex2], matrices[currentMatricesIndices[nodeIndex2]][nodeIndex2], - partials[currentPartialsIndices[nodeIndex3]][nodeIndex3]); - } else { - calculateStatesPartialsPruning(states[nodeIndex1], matrices[currentMatricesIndices[nodeIndex1]][nodeIndex1], - partials[currentPartialsIndices[nodeIndex2]][nodeIndex2], matrices[currentMatricesIndices[nodeIndex2]][nodeIndex2], - partials[currentPartialsIndices[nodeIndex3]][nodeIndex3]); - } - } else { - if (states[nodeIndex2] != null) { - calculateStatesPartialsPruning(states[nodeIndex2], matrices[currentMatricesIndices[nodeIndex2]][nodeIndex2], - partials[currentPartialsIndices[nodeIndex1]][nodeIndex1], matrices[currentMatricesIndices[nodeIndex1]][nodeIndex1], - partials[currentPartialsIndices[nodeIndex3]][nodeIndex3]); - } else { - calculatePartialsPartialsPruning(partials[currentPartialsIndices[nodeIndex1]][nodeIndex1], matrices[currentMatricesIndices[nodeIndex1]][nodeIndex1], - partials[currentPartialsIndices[nodeIndex2]][nodeIndex2], matrices[currentMatricesIndices[nodeIndex2]][nodeIndex2], - partials[currentPartialsIndices[nodeIndex3]][nodeIndex3]); - } - } - } - - /** - * Calculates partial likelihoods at a node when both children have states. - */ - private void calculateStatesStatesPruning(int[] states1, BigDecimal[] matrices1, - int[] states2, BigDecimal[] matrices2, - BigDecimal[] partials3) { - int v = 0; - - for (int l = 0; l < matrixCount; l++) { - - for (int k = 0; k < patternCount; k++) { - - int state1 = states1[k]; - int state2 = states2[k]; - - int w = l * matrixSize; - - if (state1 < stateCount && state2 < stateCount) { - - for (int i = 0; i < stateCount; i++) { - - partials3[v] = matrices1[w + state1].multiply(matrices2[w + state2], precision); - - v++; - w += stateCount; - } - - } else if (state1 < stateCount) { - // child 2 has a gap or unknown state so treat it as unknown - - for (int i = 0; i < stateCount; i++) { - - partials3[v] = matrices1[w + state1]; - - v++; - w += stateCount; - } - } else if (state2 < stateCount) { - // child 2 has a gap or unknown state so treat it as unknown - - for (int i = 0; i < stateCount; i++) { - - partials3[v] = matrices2[w + state2]; - - v++; - w += stateCount; - } - } else { - // both children have a gap or unknown state so set partials to 1 - - for (int j = 0; j < stateCount; j++) { - partials3[v] = BigDecimal.ONE; - v++; - } - } - } - } - } - - /** - * Calculates partial likelihoods at a node when one child has states and one has partials. - */ - private void calculateStatesPartialsPruning(int[] states1, BigDecimal[] matrices1, - BigDecimal[] partials2, BigDecimal[] matrices2, - BigDecimal[] partials3) { - - BigDecimal sum, tmp; - - int u = 0; - int v = 0; - - for (int l = 0; l < matrixCount; l++) { - for (int k = 0; k < patternCount; k++) { - - int state1 = states1[k]; - - int w = l * matrixSize; - - if (state1 < stateCount) { - - - for (int i = 0; i < stateCount; i++) { - - tmp = matrices1[w + state1]; - - sum = BigDecimal.ZERO; - for (int j = 0; j < stateCount; j++) { - sum = sum.add(matrices2[w].multiply(partials2[v + j], precision), precision); - w++; - } - - partials3[u] = tmp.multiply(sum, precision); - u++; - } - - v += stateCount; - } else { - // Child 1 has a gap or unknown state so don't use it - - for (int i = 0; i < stateCount; i++) { - - sum = BigDecimal.ZERO; - for (int j = 0; j < stateCount; j++) { - sum = sum.add(matrices2[w].multiply(partials2[v + j], precision), precision); - w++; - } - - partials3[u] = sum; - u++; - } - - v += stateCount; - } - } - } - } - - /** - * Calculates partial likelihoods at a node when both children have partials. - */ - private void calculatePartialsPartialsPruning(BigDecimal[] partials1, BigDecimal[] matrices1, - BigDecimal[] partials2, BigDecimal[] matrices2, - BigDecimal[] partials3) { - BigDecimal sum1, sum2; - - int u = 0; - int v = 0; - - for (int l = 0; l < matrixCount; l++) { - - for (int k = 0; k < patternCount; k++) { - - int w = l * matrixSize; - - for (int i = 0; i < stateCount; i++) { - - sum1 = sum2 = BigDecimal.ZERO; - - for (int j = 0; j < stateCount; j++) { - sum1 = sum1.add(matrices1[w].multiply(partials1[v + j], precision), precision); - sum2 = sum2.add(matrices2[w].multiply(partials2[v + j], precision), precision); - - w++; - } - - partials3[u] = sum1.multiply(sum2, precision); - u++; - } - v += stateCount; - } - } - } - - /** - * Calculates partial likelihoods at a node. - * - * @param nodeIndex1 the 'child 1' node - * @param nodeIndex2 the 'child 2' node - * @param nodeIndex3 the 'parent' node - * @param matrixMap a map of which matrix to use for each pattern (can be null if integrating over categories) - */ - public void calculatePartials(int nodeIndex1, int nodeIndex2, int nodeIndex3, int[] matrixMap) { - throw new UnsupportedOperationException("calculatePartials(int nodeIndex1, int nodeIndex2, int nodeIndex3, int[] matrixMap) is not implemented in this likelihood core"); - } - - - public void integratePartials(int nodeIndex, double[] proportions, double[] outPartials) { - throw new UnsupportedOperationException("integratePartials(int nodeIndex, double[] proportions, double[] outPartials) is not implemented in this likelihood core"); - } - - public void integratePartials(int nodeIndex, double[] proportions, BigDecimal[] outPartials) { - BigDecimal[] prop = new BigDecimal[proportions.length]; - for (int i = 0; i < proportions.length; i++) { - prop[i] = new BigDecimal(proportions[i], precision); - } - calculateIntegratePartials(partials[currentPartialsIndices[nodeIndex]][nodeIndex], prop, outPartials); - } - - /** - * Integrates partials across categories. - * - * @param inPartials the array of partials to be integrated - * @param proportions the proportions of sites in each category - * @param outPartials an array into which the partials will go - */ - private void calculateIntegratePartials(BigDecimal[] inPartials, BigDecimal[] proportions, BigDecimal[] outPartials) { - - int u = 0; - int v = 0; - for (int k = 0; k < patternCount; k++) { - - for (int i = 0; i < stateCount; i++) { - - outPartials[u] = inPartials[v].multiply(proportions[0], precision); - u++; - v++; - } - } - - - for (int l = 1; l < matrixCount; l++) { - u = 0; - - for (int k = 0; k < patternCount; k++) { - - for (int i = 0; i < stateCount; i++) { - - outPartials[u] = outPartials[u].add(inPartials[v].multiply(proportions[l], precision), precision); - u++; - v++; - } - } - } - } - - /** - * Calculates patten log likelihoods at a node. - * - * @param partials the partials used to calculate the likelihoods - * @param frequencies an array of state frequencies - * @param outLogLikelihoods an array into which the likelihoods will go - */ - public void calculateLogLikelihoods(BigDecimal[] partials, double[] frequencies, double[] outLogLikelihoods) { - BigDecimal[] freqs = new BigDecimal[frequencies.length]; - for (int i = 0; i < freqs.length; i++) { - freqs[i] = new BigDecimal(frequencies[i], precision); - } - - int v = 0; - for (int k = 0; k < patternCount; k++) { - - BigDecimal sum = BigDecimal.ZERO; - for (int i = 0; i < stateCount; i++) { - - sum = sum.add(freqs[i].multiply(partials[v], precision), precision); - v++; - } - - double scale = sum.scale(); - double value = sum.unscaledValue().doubleValue(); - - outLogLikelihoods[k] = Math.log(value) - (scale * Math.log(10)); - } - } - - public void calculateLogLikelihoods(double[] partials, double[] frequencies, double[] outLogLikelihoods) { - throw new UnsupportedOperationException("calculateLogLikelihoods(double[] partials, double[] frequencies, double[] outLogLikelihoods) is not implemented in this likelihood core"); - } - - public void setUseScaling(boolean useScaling) { - } - - public double getLogScalingFactor(int pattern) { - return 0; - } - - public boolean arePartialsRescaled() { - return false; - } - - public void getLogScalingFactors(int nodeIndex, double[] buffer) { - throw new RuntimeException("Not yet implemented."); - } - - /** - * Gets the partials for a particular node. - * - * @param nodeIndex the node - * @param outPartials an array into which the partials will go - */ - public void getPartials(int nodeIndex, double[] outPartials) { - for (int i = 0; i < outPartials.length; i++) { - outPartials[i] = partials[currentPartialsIndices[nodeIndex]][nodeIndex][i].doubleValue(); - } - } - - /** - * Store current state - */ - public void storeState() { - - System.arraycopy(currentMatricesIndices, 0, storedMatricesIndices, 0, nodeCount); - System.arraycopy(currentPartialsIndices, 0, storedPartialsIndices, 0, nodeCount); - } - - /** - * Restore the stored state - */ - public void restoreState() { - // Rather than copying the stored stuff back, just swap the pointers... - int[] tmp1 = currentMatricesIndices; - currentMatricesIndices = storedMatricesIndices; - storedMatricesIndices = tmp1; - - int[] tmp2 = currentPartialsIndices; - currentPartialsIndices = storedPartialsIndices; - storedPartialsIndices = tmp2; - } - - public void checkScaling() { - // do nothing - } - -} \ No newline at end of file diff --git a/src/dr/oldevomodel/treelikelihood/EpochTreeBranchSubstitutionModel.java b/src/dr/oldevomodel/treelikelihood/EpochTreeBranchSubstitutionModel.java deleted file mode 100644 index b18f300a42..0000000000 --- a/src/dr/oldevomodel/treelikelihood/EpochTreeBranchSubstitutionModel.java +++ /dev/null @@ -1,197 +0,0 @@ -/* - * EpochTreeBranchSubstitutionModel.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.treelikelihood; - -import dr.evolution.tree.NodeRef; -import dr.evolution.tree.Tree; -import dr.evomodel.branchratemodel.BranchRateModel; -import dr.oldevomodel.sitemodel.SiteModel; -import dr.oldevomodel.substmodel.SubstitutionModel; -import dr.inference.model.Parameter; -import dr.inference.model.Variable; -import dr.math.matrixAlgebra.Vector; - -import java.util.List; - -/** - * @author Marc A. Suchard - */ -@Deprecated // Switching to BEAGLE -public class EpochTreeBranchSubstitutionModel extends TreeBranchSubstitutionModel { - - public static final boolean DEBUG = false; - - public EpochTreeBranchSubstitutionModel(String name, - SiteModel siteModel, List substModelList, BranchRateModel branchModel, - Parameter transitionTimes) { - super(name, siteModel, null, branchModel); - this.modelList = substModelList; - - this.transitionTimesParameter = transitionTimes; - this.transitionTimes = transitionTimesParameter.getParameterValues(); - - addVariable(transitionTimes); - - for (SubstitutionModel model : modelList) - addModel(model); - - numberModels = modelList.size(); - weight = new double[numberModels]; - stateCount = modelList.get(0).getDataType().getStateCount(); - stepMatrix = new double[stateCount * stateCount]; - productMatrix = new double[stateCount * stateCount]; - resultMatrix = new double[stateCount * stateCount]; - } - - 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); - } - - private int getEpochWeights(double startTime, double endTime, double[] weights) { - - int matrixCount = 0; - final double lengthTime = endTime - startTime; - final int lastTime = numberModels - 2; - - // model 0, 1, 2, ..., K-2, K-1 - // times 0, 1, ..., K-2, - // where K = numberModels - - // First epoch: 0 -> transitionTimes[0]; - if (startTime <= transitionTimes[0]) { - if (endTime <= transitionTimes[0]) - weights[0] = 1; - else - weights[0] = (transitionTimes[0] - startTime) / lengthTime; - matrixCount++; - } else - weights[0] = 0; - - // Middle epoches: - for (int i = 1; i <= lastTime; i++) { - if (startTime <= transitionTimes[i]) { - double start = Math.max(startTime, transitionTimes[i - 1]); - double end = Math.min(endTime, transitionTimes[i]); - weights[i] = (end - start) / lengthTime; - matrixCount++; - } else - weights[i] = 0; - } - - // Last epoch: transitionTimes[K-2] -> Infinity - if (lastTime >= 0) { - if (endTime > transitionTimes[lastTime]) { - double start = Math.max(startTime, transitionTimes[lastTime]); - weights[lastTime + 1] = (endTime - start) / lengthTime; - matrixCount++; - } else - weights[lastTime + 1] = 0; - } - - if (DEBUG) { - double totalWeight = 0; - for (int i = 0; i < numberModels; i++) - totalWeight += weights[i]; - System.err.println("Start: " + startTime + " End: " + endTime + " Count: " + matrixCount + " Weight: " + totalWeight + " - " + new Vector(weights)); - if (totalWeight > 1.001) System.exit(-1); - if (totalWeight < 0.999) System.exit(-1); - } - - return matrixCount; - } - - protected final void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) { - super.handleVariableChangedEvent(variable, index, type); - - if (variable == transitionTimesParameter) { - transitionTimes = transitionTimesParameter.getParameterValues(); - fireModelChanged(variable, index); - } - } - - private List modelList; - private Parameter transitionTimesParameter; - private double[] transitionTimes; - private double[] weight; - private double[] stepMatrix; - private double[] productMatrix; - private double[] resultMatrix; - private int numberModels; - private int stateCount; - -} - diff --git a/src/dr/oldevomodel/treelikelihood/EpochTreeLikelihood.java b/src/dr/oldevomodel/treelikelihood/EpochTreeLikelihood.java deleted file mode 100644 index ecb786f01e..0000000000 --- a/src/dr/oldevomodel/treelikelihood/EpochTreeLikelihood.java +++ /dev/null @@ -1,218 +0,0 @@ -/* - * EpochTreeLikelihood.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.treelikelihood; - -import dr.evolution.alignment.PatternList; -import dr.evolution.tree.NodeRef; -import dr.evolution.tree.Tree; -import dr.evomodel.branchratemodel.BranchRateModel; -import dr.oldevomodel.sitemodel.SiteModel; -import dr.oldevomodel.substmodel.SubstitutionEpochModel; -import dr.evomodel.tipstatesmodel.TipStatesModel; -import dr.evomodel.tree.TreeModel; -import dr.oldevomodelxml.treelikelihood.TreeLikelihoodParser; -import dr.inference.model.Likelihood; -import dr.xml.*; - -import java.util.logging.Logger; - -/** - * @author Marc A. Suchard - */ -@Deprecated // Switching to BEAGLE -public class EpochTreeLikelihood extends TreeLikelihood { - public static final String LIKE_NAME = "epochTreeLikelihood"; - - public EpochTreeLikelihood(PatternList patternList, - TreeModel treeModel, - SiteModel siteModel, - BranchRateModel branchRateModel, - TipStatesModel tipStatesModel, - boolean useAmbiguities, - boolean allowMissingTaxa, - boolean storePartials, - boolean forceJavaCore) { - super(patternList, treeModel, siteModel, branchRateModel, tipStatesModel,useAmbiguities,allowMissingTaxa,storePartials,forceJavaCore, false); - - } - - - /** - * Traverse the tree calculating partial likelihoods. - * - * @return whether the partials for this node were recalculated. - */ - protected boolean traverse(Tree tree, NodeRef node) { - - boolean update = false; - - int nodeNum = node.getNumber(); - - NodeRef parent = tree.getParent(node); - - // First update the transition probability matrix(ices) for this branch - if (parent != null && updateNode[nodeNum]) { - - final double branchRate = branchRateModel.getBranchRate(tree, node); - - // Get the operational time of the branch - final double parentNodeHeight = tree.getNodeHeight(parent); - final double nodeHeight = tree.getNodeHeight(node); - final double branchTime = branchRate * (parentNodeHeight - nodeHeight); - - if (branchTime < 0.0) { - throw new RuntimeException("Negative branch length: " + branchTime); - } - - likelihoodCore.setNodeMatrixForUpdate(nodeNum); - - for (int i = 0; i < categoryCount; i++) { - - double branchLength = siteModel.getRateForCategory(i) * branchTime; - ((SubstitutionEpochModel)siteModel.getSubstitutionModel()).getTransitionProbabilities(nodeHeight, parentNodeHeight,branchLength, probabilities); - likelihoodCore.setNodeMatrix(nodeNum, i, probabilities); - } - - update = true; - } - - // If the node is internal, update the partial likelihoods. - if (!tree.isExternal(node)) { - - // Traverse down the two child nodes - NodeRef child1 = tree.getChild(node, 0); - final boolean update1 = traverse(tree, child1); - - NodeRef child2 = tree.getChild(node, 1); - final boolean update2 = traverse(tree, child2); - - // If either child node was updated then update this node too - if (update1 || update2) { - - final int childNum1 = child1.getNumber(); - final int childNum2 = child2.getNumber(); - - likelihoodCore.setNodePartialsForUpdate(nodeNum); - - if (integrateAcrossCategories) { - likelihoodCore.calculatePartials(childNum1, childNum2, nodeNum); - } else { - likelihoodCore.calculatePartials(childNum1, childNum2, nodeNum, siteCategories); - } - - if (parent == null) { - // No parent this is the root of the tree - - // calculate the pattern likelihoods - double[] frequencies = frequencyModel.getFrequencies(); - - double[] partials = getRootPartials(); - - likelihoodCore.calculateLogLikelihoods(partials, frequencies, patternLogLikelihoods); - } - - update = true; - } - } - - return update; - - } - - - /** - * The XML parser - */ - public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { - - public String getParserName() { - return LIKE_NAME; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - boolean useAmbiguities = xo.getAttribute(TreeLikelihoodParser.USE_AMBIGUITIES, false); - boolean allowMissingTaxa = xo.getAttribute(TreeLikelihoodParser.ALLOW_MISSING_TAXA, false); - boolean storePartials = xo.getAttribute(TreeLikelihoodParser.STORE_PARTIALS, true); - boolean forceJavaCore = xo.getAttribute(TreeLikelihoodParser.FORCE_JAVA_CORE, false); - - PatternList patternList = (PatternList) xo.getChild(PatternList.class); - TreeModel treeModel = (TreeModel) xo.getChild(TreeModel.class); - SiteModel siteModel = (SiteModel) xo.getChild(SiteModel.class); - - if (! (siteModel.getSubstitutionModel() instanceof SubstitutionEpochModel)) { - throw new XMLParseException("EpochTreeLikelihood only currently works with a SubstitutionEpochModel"); - } - - BranchRateModel branchRateModel = (BranchRateModel) xo.getChild(BranchRateModel.class); - - TipStatesModel tipStatesModel = (TipStatesModel) xo.getChild(TipStatesModel.class); - - Logger.getLogger("dr.evolution").info("\n ---------------------------------\nCreating EpochTreeLikelihood model."); - Logger.getLogger("dr.evolution").info("\tIf you publish results using substitution epoch likelihood, please reference" + - " Shapiro and Suchard (in preparation).\n---------------------------------\n"); - - - return new EpochTreeLikelihood( - patternList, - treeModel, - siteModel, - branchRateModel, - tipStatesModel, - useAmbiguities, allowMissingTaxa, storePartials, forceJavaCore); - } - - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - - public String getParserDescription() { - return "This element represents the likelihood of a patternlist on a tree given the site model."; - } - - public Class getReturnType() { - return Likelihood.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{ - AttributeRule.newBooleanRule(TreeLikelihoodParser.USE_AMBIGUITIES, true), - AttributeRule.newBooleanRule(TreeLikelihoodParser.ALLOW_MISSING_TAXA, true), - AttributeRule.newBooleanRule(TreeLikelihoodParser.STORE_PARTIALS, true), - AttributeRule.newBooleanRule(TreeLikelihoodParser.FORCE_JAVA_CORE, true), - new ElementRule(PatternList.class), - new ElementRule(TreeModel.class), - new ElementRule(SiteModel.class), - new ElementRule(BranchRateModel.class, true), - new ElementRule(TipStatesModel.class, true) - }; - }; - -} \ No newline at end of file diff --git a/src/dr/oldevomodel/treelikelihood/GeneralLikelihoodCore.java b/src/dr/oldevomodel/treelikelihood/GeneralLikelihoodCore.java deleted file mode 100644 index e7d0a1663e..0000000000 --- a/src/dr/oldevomodel/treelikelihood/GeneralLikelihoodCore.java +++ /dev/null @@ -1,409 +0,0 @@ -/* - * GeneralLikelihoodCore.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.treelikelihood; - -/** - * GeneralLikelihoodCore - An implementation of LikelihoodCore for any data - * - * - * @author Andrew Rambaut - */ - -@Deprecated // Switching to BEAGLE -public class GeneralLikelihoodCore extends AbstractLikelihoodCore { - - /** - * Constructor - * - * @param stateCount number of states - */ - public GeneralLikelihoodCore(int stateCount) { - super(stateCount); - } - - /** - * Calculates partial likelihoods at a node when both children have states. - */ - protected void calculateStatesStatesPruning(int[] states1, double[] matrices1, - int[] states2, double[] matrices2, - double[] partials3) - { - int v = 0; - - for (int l = 0; l < matrixCount; l++) { - - for (int k = 0; k < patternCount; k++) { - - int state1 = states1[k]; - int state2 = states2[k]; - - int w = l * matrixSize; - - if (state1 < stateCount && state2 < stateCount) { - - for (int i = 0; i < stateCount; i++) { - - partials3[v] = matrices1[w + state1] * matrices2[w + state2]; - - v++; - w += stateCount; - } - - } else if (state1 < stateCount) { - // child 2 has a gap or unknown state so treat it as unknown - - for (int i = 0; i < stateCount; i++) { - - partials3[v] = matrices1[w + state1]; - - v++; - w += stateCount; - } - } else if (state2 < stateCount) { - // child 2 has a gap or unknown state so treat it as unknown - - for (int i = 0; i < stateCount; i++) { - - partials3[v] = matrices2[w + state2]; - - v++; - w += stateCount; - } - } else { - // both children have a gap or unknown state so set partials to 1 - - for (int j = 0; j < stateCount; j++) { - partials3[v] = 1.0; - v++; - } - } - } - } - } - - /** - * Calculates partial likelihoods at a node when one child has states and one has partials. - */ - protected void calculateStatesPartialsPruning( int[] states1, double[] matrices1, - double[] partials2, double[] matrices2, - double[] partials3) - { - - double sum, tmp; - - int u = 0; - int v = 0; - - for (int l = 0; l < matrixCount; l++) { - for (int k = 0; k < patternCount; k++) { - - int state1 = states1[k]; - - int w = l * matrixSize; - - if (state1 < stateCount) { - - - for (int i = 0; i < stateCount; i++) { - - tmp = matrices1[w + state1]; - - sum = 0.0; - for (int j = 0; j < stateCount; j++) { - sum += matrices2[w] * partials2[v + j]; - w++; - } - - partials3[u] = tmp * sum; - u++; - } - - v += stateCount; - } else { - // Child 1 has a gap or unknown state so don't use it - - for (int i = 0; i < stateCount; i++) { - - sum = 0.0; - for (int j = 0; j < stateCount; j++) { - sum += matrices2[w] * partials2[v + j]; - w++; - } - - partials3[u] = sum; - u++; - } - - v += stateCount; - } - } - } - } - - /** - * Calculates partial likelihoods at a node when both children have partials. - */ - protected void calculatePartialsPartialsPruning(double[] partials1, double[] matrices1, - double[] partials2, double[] matrices2, - double[] partials3) - { - double sum1, sum2; - - int u = 0; - int v = 0; - - for (int l = 0; l < matrixCount; l++) { - - for (int k = 0; k < patternCount; k++) { - - int w = l * matrixSize; - - for (int i = 0; i < stateCount; i++) { - - sum1 = sum2 = 0.0; - - for (int j = 0; j < stateCount; j++) { - sum1 += matrices1[w] * partials1[v + j]; - sum2 += matrices2[w] * partials2[v + j]; - - w++; - } - - partials3[u] = sum1 * sum2; - u++; - } - v += stateCount; - } - } - } - - /** - * Calculates partial likelihoods at a node when both children have states. - */ - protected void calculateStatesStatesPruning(int[] states1, double[] matrices1, - int[] states2, double[] matrices2, - double[] partials3, int[] matrixMap) - { - int v = 0; - - for (int k = 0; k < patternCount; k++) { - - int state1 = states1[k]; - int state2 = states2[k]; - - int w = matrixMap[k] * matrixSize; - - if (state1 < stateCount && state2 < stateCount) { - - for (int i = 0; i < stateCount; i++) { - - partials3[v] = matrices1[w + state1] * matrices2[w + state2]; - - v++; - w += stateCount; - } - - } else if (state1 < stateCount) { - // child 2 has a gap or unknown state so treat it as unknown - - for (int i = 0; i < stateCount; i++) { - - partials3[v] = matrices1[w + state1]; - - v++; - w += stateCount; - } - } else if (state2 < stateCount) { - // child 2 has a gap or unknown state so treat it as unknown - - for (int i = 0; i < stateCount; i++) { - - partials3[v] = matrices2[w + state2]; - - v++; - w += stateCount; - } - } else { - // both children have a gap or unknown state so set partials to 1 - - for (int j = 0; j < stateCount; j++) { - partials3[v] = 1.0; - v++; - } - } - } - } - - /** - * Calculates partial likelihoods at a node when one child has states and one has partials. - */ - protected void calculateStatesPartialsPruning( int[] states1, double[] matrices1, - double[] partials2, double[] matrices2, - double[] partials3, int[] matrixMap) - { - - double sum, tmp; - - int u = 0; - int v = 0; - - for (int k = 0; k < patternCount; k++) { - - int state1 = states1[k]; - - int w = matrixMap[k] * matrixSize; - - if (state1 < stateCount) { - - for (int i = 0; i < stateCount; i++) { - - tmp = matrices1[w + state1]; - - sum = 0.0; - for (int j = 0; j < stateCount; j++) { - sum += matrices2[w] * partials2[v + j]; - w++; - } - - partials3[u] = tmp * sum; - u++; - } - - v += stateCount; - } else { - // Child 1 has a gap or unknown state so don't use it - - for (int i = 0; i < stateCount; i++) { - - sum = 0.0; - for (int j = 0; j < stateCount; j++) { - sum += matrices2[w] * partials2[v + j]; - w++; - } - - partials3[u] = sum; - u++; - } - - v += stateCount; - } - } - } - - /** - * Calculates partial likelihoods at a node when both children have partials. - */ - protected void calculatePartialsPartialsPruning(double[] partials1, double[] matrices1, - double[] partials2, double[] matrices2, - double[] partials3, int[] matrixMap) - { - double sum1, sum2; - - int u = 0; - int v = 0; - - for (int k = 0; k < patternCount; k++) { - - int w = matrixMap[k] * matrixSize; - - for (int i = 0; i < stateCount; i++) { - - sum1 = sum2 = 0.0; - - for (int j = 0; j < stateCount; j++) { - sum1 += matrices1[w] * partials1[v + j]; - sum2 += matrices2[w] * partials2[v + j]; - - w++; - } - - partials3[u] = sum1 * sum2; - u++; - } - v += stateCount; - } - } - - /** - * Integrates partials across categories. - * @param inPartials the array of partials to be integrated - * @param proportions the proportions of sites in each category - * @param outPartials an array into which the partials will go - */ - protected void calculateIntegratePartials(double[] inPartials, double[] proportions, double[] outPartials) - { - - int u = 0; - int v = 0; - for (int k = 0; k < patternCount; k++) { - - for (int i = 0; i < stateCount; i++) { - - outPartials[u] = inPartials[v] * proportions[0]; - u++; - v++; - } - } - - - for (int l = 1; l < matrixCount; l++) { - u = 0; - - for (int k = 0; k < patternCount; k++) { - - for (int i = 0; i < stateCount; i++) { - - outPartials[u] += inPartials[v] * proportions[l]; - u++; - v++; - } - } - } - } - - /** - * Calculates patten log likelihoods at a node. - * @param partials the partials used to calculate the likelihoods - * @param frequencies an array of state frequencies - * @param outLogLikelihoods an array into which the likelihoods will go - */ - public void calculateLogLikelihoods(double[] partials, double[] frequencies, double[] outLogLikelihoods) - { - int v = 0; - for (int k = 0; k < patternCount; k++) { - - double sum = 0.0; - for (int i = 0; i < stateCount; i++) { - - sum += frequencies[i] * partials[v]; - v++; - } - outLogLikelihoods[k] = Math.log(sum) + getLogScalingFactor(k); - } - } -} diff --git a/src/dr/oldevomodel/treelikelihood/HiddenLinkageLikelihood.java b/src/dr/oldevomodel/treelikelihood/HiddenLinkageLikelihood.java deleted file mode 100644 index c3a9d4e4da..0000000000 --- a/src/dr/oldevomodel/treelikelihood/HiddenLinkageLikelihood.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * HiddenLinkageLikelihood.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.treelikelihood; - -import dr.evolution.LinkedGroup; -import dr.evolution.util.Taxon; -import dr.evolution.util.TaxonList; -import dr.evomodel.tree.HiddenLinkageModel; -import dr.evomodel.tree.TreeModel; -import dr.inference.model.AbstractModelLikelihood; -import dr.inference.model.Model; -import dr.inference.model.Variable; -import dr.inference.model.Variable.ChangeType; - -import java.util.ArrayList; -import java.util.Set; - -/** - * @author Aaron Darling - */ -@Deprecated // Switching to BEAGLE -public class HiddenLinkageLikelihood extends AbstractModelLikelihood -{ - - TreeModel tree; - HiddenLinkageModel hlm; - - - public HiddenLinkageLikelihood(HiddenLinkageModel hlm, TreeModel tree) - { - super("HiddenLinkageLikelihood"); - this.hlm = hlm; - this.tree = tree; - } - - - - protected void acceptState() { - // nothing to do - } - - - - protected void handleModelChangedEvent(Model model, Object object, int index) { - // nothing to do - } - - - - protected void handleVariableChangedEvent(Variable variable, int index, - ChangeType type) { - // nothing to do - } - - - - protected void restoreState() { - // nothing to do - } - - - - protected void storeState() { - // nothing to do - } - - - - public double getLogLikelihood() { - double logL = 0; - // first check whether the reads are linked together - // according to the linkage constraints provided as data in the - // input file - ArrayList linkedGroups = hlm.getData().getConstraints(); - for( LinkedGroup lg : linkedGroups ){ - TaxonList tl = lg.getLinkedReads(); - int found = 0; - for( int l=0; l group = hlm.getGroup(l); - for(int i=0; i0){ - logL += Math.log(1.0-lg.getLinkageProbability()); - break; - } - } - } - - // then check whether the topology of reference taxa is consistent with the fixed - // reference tree topology - if(hlm.getData().getFixedReferenceTree()){ - logL += Double.NEGATIVE_INFINITY; // not yet implemented. - } - return logL; - } - - - - public Model getModel() { - return this; - } - - - - public void makeDirty() { - // nothing to do - } - -} diff --git a/src/dr/oldevomodel/treelikelihood/LikelihoodCore.java b/src/dr/oldevomodel/treelikelihood/LikelihoodCore.java deleted file mode 100644 index e08503db5d..0000000000 --- a/src/dr/oldevomodel/treelikelihood/LikelihoodCore.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * LikelihoodCore.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.treelikelihood; - -import dr.evomodel.treelikelihood.LikelihoodPartialsProvider; - -/** - * LikelihoodCore - An interface describing the core likelihood functions. - * - * @author Andrew Rambaut - */ - -@Deprecated // Switching to BEAGLE -public interface LikelihoodCore extends LikelihoodPartialsProvider { - - /** - * initializes partial likelihood arrays. - */ - void initialize(int nodeCount, int patternCount, int matrixCount, boolean integrateCategories); - - /** - * cleans up and deallocates arrays. - */ - void finalize() throws java.lang.Throwable; - - /** - * Allocates partials for a node - */ - void createNodePartials(int nodeIndex); - - /** - * Sets partials for a node - */ - void setNodePartials(int nodeIndex, double[] partials); - - /** - * Sets states for a node - */ - void setNodeStates(int nodeIndex, int[] states); - - /** - * Sets states for a node and a pattern - * Allocates states for a node - */ - void createNodeStates(int nodeIndex); - - /** - * Specify that the matrices for the given node are about to be updated - * - * @param nodeIndex - */ - void setNodeMatrixForUpdate(int nodeIndex); - - /** - * Sets probability matrix for a node - */ - void setNodeMatrix(int nodeIndex, int matrixIndex, double[] matrix); - - /** - * Specify that the partials for the given node are about to be updated - * - * @param nodeIndex - */ - void setNodePartialsForUpdate(int nodeIndex); - - /** - * Set the currently updating node partials from the array... - * - * @param nodeIndex - */ - void setCurrentNodePartials(int nodeIndex, double[] partials); - - /** - * Calculates partial likelihoods at a node using a matrixMap. - * - * @param nodeIndex1 the 'child 1' node - * @param nodeIndex2 the 'child 2' node - * @param nodeIndex3 the 'parent' node - */ - void calculatePartials(int nodeIndex1, int nodeIndex2, int nodeIndex3); - - /** - * Calculates partial likelihoods at a node using a matrixMap. - * - * @param nodeIndex1 the 'child 1' node - * @param nodeIndex2 the 'child 2' node - * @param nodeIndex3 the 'parent' node - * @param matrixMap a map of which matrix to use for each pattern - */ - void calculatePartials(int nodeIndex1, int nodeIndex2, int nodeIndex3, int[] matrixMap); - - /** - * Gets the partials for a particular node. - * - * @param nodeIndex the node - * @param outPartials an array into which the partials will go - */ - public void getPartials(int nodeIndex, double[] outPartials); - - /** - * Integrates partials across categories. - * - * @param nodeIndex the node at which to calculate the likelihoods - * @param proportions the proportions of sites in each category - * @param outPartials an array into which the partials will go - */ - void integratePartials(int nodeIndex, double[] proportions, double[] outPartials); - - /** - * Calculates pattern log likelihoods at a node. - * - * @param partials the partials used to calculate the likelihoods - * @param frequencies an array of state frequencies - * @param outLogLikelihoods an array into which the log likelihoods will go - */ - void calculateLogLikelihoods(double[] partials, double[] frequencies, double[] outLogLikelihoods); - - void setUseScaling(boolean useScaling); - - double getLogScalingFactor(int pattern); - - boolean arePartialsRescaled(); - - void getLogScalingFactors(int nodeIndex, double[] buffer); - - /** - * Store current state - */ - void storeState(); - - /** - * Restore the stored state - */ - void restoreState(); -} diff --git a/src/dr/oldevomodel/treelikelihood/MicrosatelliteSamplerTreeLikelihood.java b/src/dr/oldevomodel/treelikelihood/MicrosatelliteSamplerTreeLikelihood.java deleted file mode 100644 index 571cd68980..0000000000 --- a/src/dr/oldevomodel/treelikelihood/MicrosatelliteSamplerTreeLikelihood.java +++ /dev/null @@ -1,276 +0,0 @@ -/* - * MicrosatelliteSamplerTreeLikelihood.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.treelikelihood; - -import dr.evomodel.tree.MicrosatelliteSamplerTreeModel; -import dr.evomodel.tree.TreeChangedEvent; -import dr.evomodel.tree.TreeModel; -import dr.oldevomodel.substmodel.MicrosatelliteModel; -import dr.evomodel.branchratemodel.BranchRateModel; -import dr.evolution.tree.NodeRef; -import dr.inference.model.Model; - -import java.util.ArrayList; - -/** - * @author Chieh-Hsi Wu - * - * Treelikelihood that allows ancestral state sampling for microsatellite data. - * - */ -@Deprecated // Switching to BEAGLE -public class MicrosatelliteSamplerTreeLikelihood extends AbstractTreeLikelihood{ - - MicrosatelliteSamplerTreeModel treeMicrosatSamplerModel; - MicrosatelliteModel microsatelliteModel; - BranchRateModel branchRateModel; - double logL = 0.0; - double storedLogL = 0.0; - boolean modelChanged = false; - private ArrayList updateAllList; - private ArrayList updatedNodeList; - public MicrosatelliteSamplerTreeLikelihood(MicrosatelliteSamplerTreeModel treeMicrosatSamplerModel, - MicrosatelliteModel microsatelliteModel, - BranchRateModel branchRate){ - super("MicrosatelliteSamplerTreeLikelihood", - treeMicrosatSamplerModel.getMicrosatPattern(), - treeMicrosatSamplerModel.getTreeModel()); - this.treeMicrosatSamplerModel = treeMicrosatSamplerModel; - this.microsatelliteModel = microsatelliteModel; - this.branchRateModel = branchRate; - - updateAllList = new ArrayList(); - - for(int i = 0; i < nodeCount; i++){ - updateAllList.add(i); - } - updatedNodeList = updateAllList; - - addModel(this.branchRateModel); - addModel(this.treeMicrosatSamplerModel); - addModel(this.microsatelliteModel); - - - } - - - protected void handleModelChangedEvent(Model model, Object object, int index) { - - if(updatedNodeList == updateAllList){ - - }else if (model == treeModel) { - - if (object instanceof TreeChangedEvent) { - - if(((TreeChangedEvent) object).isTreeChanged()){ - updateAllNodes(); - } else if (((TreeChangedEvent) object).isNodeChanged()) { - // If a node event occurs the node and its two child nodes - // are flagged for updating (this will result in everything - // above being updated as well. Node events occur when a node - // is added to a branch, removed from a branch or its height or - // rate changes. - updateNodeAndChildren(((TreeChangedEvent) object).getNode()); - } else if (((TreeChangedEvent) object).isTreeChanged()) { - // Full tree events result in a complete updating of the tree likelihood - // Currently this event type is not used. - System.err.println("Full tree update event - these events currently aren't used\n" + - "so either this is in error or a new feature is using them so remove this message."); - updateAllNodes(); - } else { - // Other event types are ignored (probably trait changes). - System.err.println("Another tree event has occured (possibly a trait change)."); - } - } - - } else if (model == treeMicrosatSamplerModel){ - - if(treeMicrosatSamplerModel.areInternalNodesChanged()) { - - updateNodeAndChildren((treeMicrosatSamplerModel.getTreeModel()).getNode(index)); - treeMicrosatSamplerModel.setInternalNodesChanged(false); - } - - } else if (model == microsatelliteModel) { - if(microsatelliteModel.isModelUpdated()){ - updateAllNodes(); - } - } else if (model == branchRateModel) { - if (index == -1) { - updateAllNodes(); - } else { - updateNode(treeModel.getNode(index)); - } - } else { - throw new RuntimeException("Unknown componentChangedEvent"); - } - - modelChanged = true; - super.handleModelChangedEvent(model, object, index); - } - - - - public boolean hasModelChanged(){ - return modelChanged; - } - - /** - * Nodes are added to upadteNodeList if it is to be updated. - */ - protected void updateNodeAndChildren(NodeRef node) { - int nodeNum = node.getNumber(); - - if(!updateNode[nodeNum]){ - updateNode[nodeNum] = true; - updatedNodeList.add(nodeNum); - } - - for (int i = 0; i < treeModel.getChildCount(node); i++) { - int childNodeNum = (treeModel.getChild(node, i)).getNumber(); - if(!updateNode[childNodeNum]){ - updateNode[childNodeNum] = true; - updatedNodeList.add(childNodeNum); - } - } - likelihoodKnown = false; - } - - /** - * - * If an event requires all the nodes to be updated - * then the updateNodeList will be referenced to - * updateAllList, which is a list that contains all the node - * in the tree. - * - */ - protected void updateAllNodes() { - updatedNodeList = updateAllList; - likelihoodKnown = false; - } - - - public double calculateLogLikelihood(){ - - traverse(); - - //used for likelihood calculation. - double temp = 0.0; - double temp1 = 0.0; - double temp2 = 0.0; - - //get the number of nodes that needs to be updated. - int updateNum = updatedNodeList.size(); - - //iterate through the nodes to be updated - for(int i = 0; i < updateNum; i++){ - - //get the node number of the node to be updated - int nodeNum = updatedNodeList.get(i); - - //calculate the sum of the previous log probabilities of the nodes flagged for update - //only calculate this if the number of nodes to be updated is less than the total number of nodes in the tree and - //when there is a change in the tree. - if(modelChanged && updatedNodeList != updateAllList) - temp1 += treeMicrosatSamplerModel.getStoredLogBranchLikelihood(nodeNum); - - //the sum of the probabilities of the nodes that have been updated. - temp2 += treeMicrosatSamplerModel.getLogBranchLikelihood(nodeNum); - - //indicate that the update is complete. - updateNode[nodeNum] = false; - } - - //subtract the sum of the previous log probabilities of the updated nodes from the previous likelihood. - if(modelChanged && updatedNodeList != updateAllList) - temp = logL - temp1; - - - //add the new likelihoods of the updated node to get the current likelihood. - logL = temp + temp2; - - //indicate that the completion of calculating the likelihood after a modelChange - modelChanged = false; - - //clear the list of the nodes to be updated - updatedNodeList = new ArrayList(); - - - - return logL; - - } - - protected void storeState() { - storedLogL = logL; - - super.storeState(); - - } - - /** - * Restore the additional stored state - */ - protected void restoreState() { - logL = storedLogL; - super.restoreState(); - - } - - - private void traverse(){ - TreeModel tree = treeMicrosatSamplerModel.getTreeModel(); - - int updateNum = updatedNodeList.size(); - for(int i = 0; i < updateNum; i++){ - NodeRef node = tree.getNode(updatedNodeList.get(i)); - int nodeState = treeMicrosatSamplerModel.getNodeValue(node); - if(!tree.isRoot(node)){ - - NodeRef parent = tree.getParent(node); - int parentState = treeMicrosatSamplerModel.getNodeValue(parent); - - double branchLength = tree.getBranchLength(node)*branchRateModel.getBranchRate(tree,node); - double nodePr = microsatelliteModel.getLogOneTransitionProbabilityEntry(branchLength, parentState, nodeState); - - treeMicrosatSamplerModel.setLogBranchLikelihood(node, nodePr); - }else{ - double logEqFreq = Math.log(microsatelliteModel.getStationaryDistribution()[nodeState]); - treeMicrosatSamplerModel.setLogBranchLikelihood(node, logEqFreq); - - } - - - } - - } - - - - -} diff --git a/src/dr/oldevomodel/treelikelihood/NativeAminoAcidLikelihoodCore.java b/src/dr/oldevomodel/treelikelihood/NativeAminoAcidLikelihoodCore.java deleted file mode 100644 index 1f3794e9ba..0000000000 --- a/src/dr/oldevomodel/treelikelihood/NativeAminoAcidLikelihoodCore.java +++ /dev/null @@ -1,149 +0,0 @@ -/* - * NativeAminoAcidLikelihoodCore.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.treelikelihood; - -@Deprecated // Switching to BEAGLE -public class NativeAminoAcidLikelihoodCore extends AbstractLikelihoodCore{ - - public NativeAminoAcidLikelihoodCore() { - super(20); - } - - - protected void calculateIntegratePartials(double[] inPartials, - double[] proportions, double[] outPartials) { - nativeIntegratePartials(inPartials, proportions, patternCount, matrixCount, outPartials); - } - - protected void calculatePartialsPartialsPruning(double[] partials1, - double[] matrices1, double[] partials2, double[] matrices2, - double[] partials3) { - nativePartialsPartialsPruning(partials1, matrices1, partials2, matrices2, patternCount, matrixCount, partials3); - } - - protected void calculateStatesPartialsPruning(int[] states1, - double[] matrices1, double[] partials2, double[] matrices2, - double[] partials3) { - nativeStatesPartialsPruning(states1, matrices1, partials2, matrices2, patternCount, matrixCount, partials3); - } - - protected void calculateStatesStatesPruning(int[] states1, - double[] matrices1, int[] states2, double[] matrices2, - double[] partials3) { - - - nativeStatesStatesPruning(states1, matrices1, states2, matrices2, patternCount, matrixCount, partials3); - } - - protected void calculatePartialsPartialsPruning(double[] partials1, - double[] matrices1, double[] partials2, double[] matrices2, - double[] partials3, int[] matrixMap) { - throw new RuntimeException("not implemented using matrixMap"); - } - - protected void calculateStatesStatesPruning(int[] states1, - double[] matrices1, int[] states2, double[] matrices2, - double[] partials3, int[] matrixMap) { - throw new RuntimeException("not implemented using matrixMap"); - } - - protected void calculateStatesPartialsPruning(int[] states1, - double[] matrices1, double[] partials2, double[] matrices2, - double[] partials3, int[] matrixMap) { - throw new RuntimeException("not implemented using matrixMap"); - } - - public void calculateLogLikelihoods(double[] partials, - double[] frequencies, double[] outLogLikelihoods) { - - int v = 0; - for (int k = 0; k < patternCount; k++) { - - double sum = frequencies[0] * partials[v]; v++; - sum += frequencies[1] * partials[v]; v++; - sum += frequencies[2] * partials[v]; v++; - sum += frequencies[3] * partials[v]; v++; - - sum += frequencies[4] * partials[v]; v++; - sum += frequencies[5] * partials[v]; v++; - sum += frequencies[6] * partials[v]; v++; - sum += frequencies[7] * partials[v]; v++; - - sum += frequencies[8] * partials[v]; v++; - sum += frequencies[9] * partials[v]; v++; - sum += frequencies[10] * partials[v]; v++; - sum += frequencies[11] * partials[v]; v++; - - sum += frequencies[12] * partials[v]; v++; - sum += frequencies[13] * partials[v]; v++; - sum += frequencies[14] * partials[v]; v++; - sum += frequencies[15] * partials[v]; v++; - - sum += frequencies[16] * partials[v]; v++; - sum += frequencies[17] * partials[v]; v++; - sum += frequencies[18] * partials[v]; v++; - sum += frequencies[19] * partials[v]; v++; - outLogLikelihoods[k] = Math.log(sum) + getLogScalingFactor(k); - } - } - - public native void nativeIntegratePartials(double[] partials, double[] proportions, - int patternCount, int matrixCount, - double[] outPartials); - - protected native void nativePartialsPartialsPruning(double[] partials1, double[] matrices1, - double[] partials2, double[] matrices2, - int patternCount, int matrixCount, - double[] partials3); - - protected native void nativeStatesPartialsPruning(int[] states1, double[] matrices1, - double[] partials2, double[] matrices2, - int patternCount, int matrixCount, - double[] partials3); - - protected native void nativeStatesStatesPruning(int[] states1, double[] matrices1, - int[] states2, double[] matrices2, - int patternCount, int matrixCount, - double[] partials3); - - public static boolean isAvailable(){ - return isNativeAvailable; - } - - private static boolean isNativeAvailable = false; - - static { - try { - System.loadLibrary("AminoAcidLikelihoodCore"); - isNativeAvailable = true; - } catch (UnsatisfiedLinkError e) { - System.err.println("Using Java AminoAcid likelihood core " + e.toString()); - System.err.println("Looking for AminoAcidLikelihoodCore in " + System.getProperty("java.library.path")); - } - } -} diff --git a/src/dr/oldevomodel/treelikelihood/NativeCovarionLikelihoodCore.java b/src/dr/oldevomodel/treelikelihood/NativeCovarionLikelihoodCore.java deleted file mode 100644 index 000df45082..0000000000 --- a/src/dr/oldevomodel/treelikelihood/NativeCovarionLikelihoodCore.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * NativeCovarionLikelihoodCore.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.treelikelihood; - -@Deprecated // Switching to BEAGLE -public class NativeCovarionLikelihoodCore extends AbstractLikelihoodCore { - - public NativeCovarionLikelihoodCore() { - super(8); - } - - protected void calculateIntegratePartials(double[] inPartials, - double[] proportions, double[] outPartials) { - nativeIntegratePartials(inPartials, proportions, patternCount, matrixCount, outPartials); - } - - protected void calculatePartialsPartialsPruning(double[] partials1, - double[] matrices1, double[] partials2, double[] matrices2, - double[] partials3) { - nativePartialsPartialsPruning(partials1, matrices1, partials2, matrices2, patternCount, matrixCount, partials3); - } - - protected void calculateStatesPartialsPruning(int[] states1, - double[] matrices1, double[] partials2, double[] matrices2, - double[] partials3) { - - nativeStatesPartialsPruning(states1, matrices1, partials2, matrices2, patternCount, matrixCount, partials3); - } - - protected void calculateStatesStatesPruning(int[] states1, - double[] matrices1, int[] states2, double[] matrices2, - double[] partials3) { - - nativeStatesStatesPruning(states1, matrices1, states2, matrices2, patternCount, matrixCount, partials3); - } - - protected void calculatePartialsPartialsPruning(double[] partials1, - double[] matrices1, double[] partials2, double[] matrices2, - double[] partials3, int[] matrixMap) { - throw new RuntimeException("not implemented using matrixMap"); - } - - protected void calculateStatesStatesPruning(int[] states1, - double[] matrices1, int[] states2, double[] matrices2, - double[] partials3, int[] matrixMap) { - throw new RuntimeException("not implemented using matrixMap"); - } - - protected void calculateStatesPartialsPruning(int[] states1, - double[] matrices1, double[] partials2, double[] matrices2, - double[] partials3, int[] matrixMap) { - throw new RuntimeException("not implemented using matrixMap"); - } - - public void calculateLogLikelihoods(double[] partials, - double[] frequencies, double[] outLogLikelihoods) { - - int v = 0; - for (int k = 0; k < patternCount; k++) { - - double sum = frequencies[0] * partials[v]; - v++; - sum += frequencies[1] * partials[v]; - v++; - sum += frequencies[2] * partials[v]; - v++; - sum += frequencies[3] * partials[v]; - v++; - - sum += frequencies[4] * partials[v]; - v++; - sum += frequencies[5] * partials[v]; - v++; - sum += frequencies[6] * partials[v]; - v++; - sum += frequencies[7] * partials[v]; - v++; - - outLogLikelihoods[k] = Math.log(sum) + getLogScalingFactor(k); - } - } - - public native void nativeIntegratePartials(double[] partials, double[] proportions, - int patternCount, int matrixCount, - double[] outPartials); - - protected native void nativePartialsPartialsPruning(double[] partials1, double[] matrices1, - double[] partials2, double[] matrices2, - int patternCount, int matrixCount, - double[] partials3); - - protected native void nativeStatesPartialsPruning(int[] states1, double[] matrices1, - double[] partials2, double[] matrices2, - int patternCount, int matrixCount, - double[] partials3); - - protected native void nativeStatesStatesPruning(int[] states1, double[] matrices1, - int[] states2, double[] matrices2, - int patternCount, int matrixCount, - double[] partials3); - - public static boolean isAvailable() { - return isNativeAvailable; - } - - private static boolean isNativeAvailable = false; - - static { - try { - System.loadLibrary("CovarionLikelihoodCore"); - isNativeAvailable = true; - } catch (UnsatisfiedLinkError e) { - System.err.println("Using Java general likelihood core " + e.toString()); - } - } - -} diff --git a/src/dr/oldevomodel/treelikelihood/NativeGeneralLikelihoodCore.java b/src/dr/oldevomodel/treelikelihood/NativeGeneralLikelihoodCore.java deleted file mode 100644 index 239f09452c..0000000000 --- a/src/dr/oldevomodel/treelikelihood/NativeGeneralLikelihoodCore.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * NativeGeneralLikelihoodCore.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.treelikelihood; - -@Deprecated // Switching to BEAGLE -public class NativeGeneralLikelihoodCore extends AbstractLikelihoodCore { - - public NativeGeneralLikelihoodCore(int stateCount) { - super(stateCount); - } - - - protected void calculateIntegratePartials(double[] inPartials, - double[] proportions, double[] outPartials) { - nativeIntegratePartials(inPartials, proportions, patternCount, matrixCount, outPartials, stateCount); - } - - protected void calculatePartialsPartialsPruning(double[] partials1, - double[] matrices1, double[] partials2, double[] matrices2, - double[] partials3) { - nativePartialsPartialsPruning(partials1, matrices1, partials2, matrices2, patternCount, matrixCount, partials3, stateCount); - } - - protected void calculateStatesPartialsPruning(int[] states1, - double[] matrices1, double[] partials2, double[] matrices2, - double[] partials3) { - nativeStatesPartialsPruning(states1, matrices1, partials2, matrices2, patternCount, matrixCount, partials3, stateCount); - } - - protected void calculateStatesStatesPruning(int[] states1, - double[] matrices1, int[] states2, double[] matrices2, - double[] partials3) { - - - nativeStatesStatesPruning(states1, matrices1, states2, matrices2, patternCount, matrixCount, partials3, stateCount); - } - - protected void calculatePartialsPartialsPruning(double[] partials1, - double[] matrices1, double[] partials2, double[] matrices2, - double[] partials3, int[] matrixMap) { - throw new RuntimeException("not implemented using matrixMap"); - } - - protected void calculateStatesStatesPruning(int[] states1, - double[] matrices1, int[] states2, double[] matrices2, - double[] partials3, int[] matrixMap) { - throw new RuntimeException("not implemented using matrixMap"); - } - - protected void calculateStatesPartialsPruning(int[] states1, - double[] matrices1, double[] partials2, double[] matrices2, - double[] partials3, int[] matrixMap) { - throw new RuntimeException("not implemented using matrixMap"); - } - - public void calculateLogLikelihoods(double[] partials, - double[] frequencies, double[] outLogLikelihoods) { - int v = 0; - for (int k = 0; k < patternCount; k++) { - - double sum = 0.0; - for (int i = 0; i < stateCount; i++) { - - sum += frequencies[i] * partials[v]; - v++; - } - outLogLikelihoods[k] = Math.log(sum) + getLogScalingFactor(k); - } - } - - public native void nativeIntegratePartials(double[] partials, double[] proportions, - int patternCount, int matrixCount, - double[] outPartials, - int stateCount); - - protected native void nativePartialsPartialsPruning(double[] partials1, double[] matrices1, - double[] partials2, double[] matrices2, - int patternCount, int matrixCount, - double[] partials3, - int stateCount); - - protected native void nativeStatesPartialsPruning(int[] states1, double[] matrices1, - double[] partials2, double[] matrices2, - int patternCount, int matrixCount, - double[] partials3, - int stateCount); - - protected native void nativeStatesStatesPruning(int[] states1, double[] matrices1, - int[] states2, double[] matrices2, - int patternCount, int matrixCount, - double[] partials3, - int stateCount); - - protected native void setMode(int mode); - - public static boolean isAvailable() { - return isNativeAvailable; - } - - private static boolean isNativeAvailable = false; - - static { - try { - System.loadLibrary("GeneralLikelihoodCore"); - isNativeAvailable = true; - } catch (UnsatisfiedLinkError e) { - System.err.println("Unable to load general core"); - } - } -} \ No newline at end of file diff --git a/src/dr/oldevomodel/treelikelihood/NativeNucleotideLikelihoodCore.java b/src/dr/oldevomodel/treelikelihood/NativeNucleotideLikelihoodCore.java deleted file mode 100644 index e32246d30d..0000000000 --- a/src/dr/oldevomodel/treelikelihood/NativeNucleotideLikelihoodCore.java +++ /dev/null @@ -1,190 +0,0 @@ -/* - * NativeNucleotideLikelihoodCore.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.treelikelihood; - -import dr.app.util.OSType; - -import java.io.File; -import java.net.URISyntaxException; - -/** - * NativeNucleotideLikelihoodCore - An implementation of LikelihoodCore for nucleotides - * that calls native methods for maximum speed. The native methods should be in - * a shared library called "NucleotideLikelihoodCore" but the exact name will be system - * dependent (i.e. "libNucleotideLikelihoodCore.so" or "NucleotideLikelihoodCore.dll"). - * - * - * @author Andrew Rambaut - */ - -@Deprecated // Switching to BEAGLE -public class NativeNucleotideLikelihoodCore extends AbstractLikelihoodCore { - - /** - * Constructor - */ - public NativeNucleotideLikelihoodCore() { - - super(4); - - } - - protected void calculateStatesStatesPruning(int[] states1, double[] matrices1, - int[] states2, double[] matrices2, - double[] partials3) { - nativeStatesStatesPruning(states1, matrices1, states2, matrices2, patternCount, matrixCount, partials3); - } - - protected void calculateStatesPartialsPruning( int[] states1, double[] matrices1, - double[] partials2, double[] matrices2, - double[] partials3) { - nativeStatesPartialsPruning(states1, matrices1, partials2, matrices2, patternCount, matrixCount, partials3); - } -/* - private void out(PrintStream s, double[] a, String name) { - s.print("double " + name + "[" + a.length + "] = {"); - for( double f : a ) s.print(f + ", "); - s.println("};"); - } - */ - protected void calculatePartialsPartialsPruning(double[] partials1, double[] matrices1, - double[] partials2, double[] matrices2, - double[] partials3) { - /* if( false ) { - System.out.println("*//*nativePartialsPartialsPruning*//* int patternCount = " + - patternCount + "; int matrixCount = " + matrixCount); - out(System.out, partials1, "partials1"); - out(System.out, partials2, "partials2"); - out(System.out, partials2, "matrices1"); - out(System.out, partials2, "matrices2"); - }*/ - nativePartialsPartialsPruning(partials1, matrices1, partials2, matrices2, patternCount, matrixCount, partials3); - } - - /** - * Calculates partial likelihoods at a node when both children have states. - */ - protected void calculateStatesStatesPruning(int[] states1, double[] matrices1, - int[] states2, double[] matrices2, - double[] partials3, int[] matrixMap) - { - throw new RuntimeException("calculateStatesStatesPruning not implemented using matrixMap"); - } - - /** - * Calculates partial likelihoods at a node when one child has states and one has partials. - */ - protected void calculateStatesPartialsPruning( int[] states1, double[] matrices1, - double[] partials2, double[] matrices2, - double[] partials3, int[] matrixMap) - { - throw new RuntimeException("calculateStatesStatesPruning not implemented using matrixMap"); - } - - /** - * Calculates partial likelihoods at a node when both children have partials. - */ - protected void calculatePartialsPartialsPruning(double[] partials1, double[] matrices1, - double[] partials2, double[] matrices2, - double[] partials3, int[] matrixMap) - { - throw new RuntimeException("calculateStatesStatesPruning not implemented using matrixMap"); - } - - protected void calculateIntegratePartials(double[] inPartials, double[] proportions, double[] outPartials) - { - nativeIntegratePartials(inPartials, proportions, patternCount, matrixCount, outPartials); - } - - - /** - * Calculates partial likelihoods at a node when both children have states. - */ - protected native void nativeStatesStatesPruning( int[] states1, double[] matrices1, - int[] states2, double[] matrices2, - int patternCount, int matrixCount, - double[] partials3); - protected native void nativeStatesPartialsPruning( int[] states1, double[] matrices1, - double[] partials2, double[] matrices2, - int patternCount, int matrixCount, - double[] partials3); - protected native void nativePartialsPartialsPruning(double[] partials1, double[] matrices1, - double[] partials2, double[] matrices2, - int patternCount, int matrixCount, - double[] partials3); - public native void nativeIntegratePartials( double[] partials, double[] proportions, - int patternCount, int matrixCount, - double[] outPartials); - - public void calculateLogLikelihoods(double[] partials, double[] frequencies, double[] outLogLikelihoods) - { - int v = 0; - for (int k = 0; k < patternCount; k++) { - - double sum = frequencies[0] * partials[v]; v++; - sum += frequencies[1] * partials[v]; v++; - sum += frequencies[2] * partials[v]; v++; - sum += frequencies[3] * partials[v]; v++; - outLogLikelihoods[k] = Math.log(sum) + getLogScalingFactor(k); - } - } - - public static boolean isAvailable() { return isNativeAvailable; } - - private static boolean isNativeAvailable = false; - - static { - String currentDir = null; - try { - currentDir = new File(NativeNucleotideLikelihoodCore.class.getProtectionDomain().getCodeSource(). - getLocation().toURI()).getParent() + System.getProperty("file.separator") - + "lib" + System.getProperty("file.separator"); // get path to find lib http://code.google.com/p/beast-mcmc/issues/detail?id=203 -// System.out.println("currentDir = " + currentDir); - } catch (URISyntaxException e) { - e.printStackTrace(); - } - try { - if (OSType.isWindows()) { - System.load(currentDir + "NucleotideLikelihoodCore.dll"); - } else { - currentDir = System.getProperty("user.dir"); - System.loadLibrary("NucleotideLikelihoodCore"); - } - isNativeAvailable = true; - System.out.println("Loading native NucleotideLikelihoodCore successfully from " + currentDir); - } catch (UnsatisfiedLinkError e) { - System.err.println("Failed to load native NucleotideLikelihoodCore in : " + currentDir); - System.err.println("Using Java nucleotide likelihood core because " + e.toString()); -// System.err.println("Looking for NucleotideLikelihoodCore in java.library.path : " + System.getProperty("java.library.path")); -// System.err.println("Looking for NucleotideLikelihoodCore in user.dir : " + System.getProperty("user.dir")); - - } - - } -} - diff --git a/src/dr/oldevomodel/treelikelihood/NodePosteriorTreeLikelihood.java b/src/dr/oldevomodel/treelikelihood/NodePosteriorTreeLikelihood.java deleted file mode 100644 index d18a6b1b95..0000000000 --- a/src/dr/oldevomodel/treelikelihood/NodePosteriorTreeLikelihood.java +++ /dev/null @@ -1,291 +0,0 @@ -/* - * NodePosteriorTreeLikelihood.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.treelikelihood; - -import dr.evolution.alignment.PatternList; -import dr.evolution.tree.NodeRef; -import dr.evolution.tree.Tree; -import dr.evolution.tree.TreeTrait; -import dr.evolution.tree.TreeTraitProvider; -import dr.evomodel.branchratemodel.BranchRateModel; -import dr.oldevomodel.sitemodel.SiteModel; -import dr.oldevomodel.substmodel.SubstitutionModel; -import dr.evomodel.tipstatesmodel.TipStatesModel; -import dr.evomodel.tree.TreeModel; -import dr.oldevomodelxml.treelikelihood.TreeLikelihoodParser; -import dr.inference.model.Likelihood; -import dr.xml.*; - -/** - * Package: dr.evomodel.treelikelihood - * Description: - *

- *

- * Created by - * avaleks (alexander.alekseyenko@gmail.com) - * Date: 01-Aug-2008 - * Time: 10:36:39 - */ -@Deprecated // Switching to BEAGLE -public class NodePosteriorTreeLikelihood extends TreeLikelihood implements TreeTraitProvider { - - protected double[][] nodePosteriors; - protected double[][] forwardProbs; - protected double[] likes; - boolean posteriorsKnown; - private double[] childPartials; - private double[] partialLikelihood; - - public NodePosteriorTreeLikelihood(PatternList patternList, TreeModel treeModel, SiteModel siteModel, BranchRateModel branchRateModel, TipStatesModel tipStatesModel, boolean useAmbiguities, boolean allowMissingTaxa, boolean storePartials, boolean forceJavaCore) { - super(patternList, treeModel, siteModel, branchRateModel, tipStatesModel, useAmbiguities, allowMissingTaxa, storePartials, forceJavaCore, false); - // TreeLikelihood does not initialize the partials for tips, we'll do it ourselves - int extNodeCount = treeModel.getExternalNodeCount(); - for (int i = 0; i < extNodeCount; i++) { - String id = treeModel.getTaxonId(i); - int index = patternList.getTaxonIndex(id); - setPartials(likelihoodCore, patternList, categoryCount, index, i); - } - childPartials = new double[stateCount * patternCount]; - partialLikelihood = new double[stateCount * patternCount]; - posteriorsKnown = false; - } - - TreeTrait posteriors = new TreeTrait.DA() { - public String getTraitName() { - return "posteriors"; - } - - public Intent getIntent() { - return Intent.NODE; - } - - public double[] getTrait(Tree tree, NodeRef node) { - if (tree != treeModel) { - throw new RuntimeException("Can only calculate node posteriors on treeModel given to constructor"); - } - if (!posteriorsKnown) { - calculatePosteriors(); - } - return nodePosteriors[node.getNumber()]; - } - - }; - - public TreeTrait[] getTreeTraits() { - return new TreeTrait[] { posteriors }; - } - - public TreeTrait getTreeTrait(String key) { - // ignore the key - it must be the one they wanted, no? - return posteriors; - } - - public double[] getPosteriors(int nodeNum) { - if (!posteriorsKnown) { - calculatePosteriors(); - } - return nodePosteriors[nodeNum]; - } - - public void getNodeMatrix(int nodeNum, double[] probabilities) { - ((AbstractLikelihoodCore) likelihoodCore).getNodeMatrix(nodeNum, 0, probabilities); - } - - public void calculatePosteriors() { - int nodeCount = treeModel.getNodeCount(); - traverseForward(treeModel, treeModel.getRoot()); - for (int k = 0; k < nodeCount; ++k) { - for (int i = 0; i < patternCount; ++i) { - for (int j = 0; j < stateCount; ++j) { - nodePosteriors[k][stateCount * i + j] /= likes[i]; - } - } - } - posteriorsKnown = true; - } - - protected double calculateLogLikelihood() { - posteriorsKnown = false; - - return super.calculateLogLikelihood(); - } - - - public void traverseForward(TreeModel tree, NodeRef node) { - if (nodePosteriors == null) { - nodePosteriors = new double[tree.getNodeCount()][patternCount * stateCount]; - } - if (forwardProbs == null) { - forwardProbs = new double[tree.getNodeCount()][patternCount * stateCount]; - } - int nodeNum = node.getNumber(); - - NodeRef parent = tree.getParent(node); - - - if (parent == null) {/* this is the root */ - double[] rootFreqs = frequencyModel.getFrequencies(); - double[] rootPartials = getRootPartials(); - if (likes == null) { - likes = new double[patternCount]; - } - - for (int j = 0; j < patternCount; j++) { - System.arraycopy(rootFreqs, 0, forwardProbs[nodeNum], j * stateCount, stateCount); - likes[j] = 0.0; - for (int k = 0; k < stateCount; ++k) { - nodePosteriors[nodeNum][stateCount * j + k] = forwardProbs[nodeNum][stateCount * j + k] * rootPartials[j * stateCount + k]; - likes[j] = likes[j] + rootPartials[stateCount * j + k] * rootFreqs[k]; - } - } - - } else { /* regular internal node */ - int parentNum = parent.getNumber(); - int numChildren = tree.getChildCount(parent); - - System.arraycopy(forwardProbs[parentNum], 0, forwardProbs[nodeNum], 0, stateCount * patternCount); - - for (int child = 0; child < numChildren; ++child) { - NodeRef childNode = tree.getChild(parent, child); - int childNum = childNode.getNumber(); - if (childNum != nodeNum) { - getNodeMatrix(childNum, probabilities); - likelihoodCore.getPartials(childNum, childPartials); - accumulateMatrixMultiply(probabilities, childPartials, forwardProbs[nodeNum]); - } - } - - getNodeMatrix(nodeNum, probabilities); - likelihoodCore.getPartials(nodeNum, partialLikelihood); - - matrixMultiplyBackward(probabilities, forwardProbs[nodeNum], nodePosteriors[nodeNum]); - for (int i = 0; i < patternCount * stateCount; ++i) { - forwardProbs[nodeNum][i] = nodePosteriors[nodeNum][i]; - nodePosteriors[nodeNum][i] = nodePosteriors[nodeNum][i] * partialLikelihood[i]; - } - } - if (!tree.isExternal(node)) { /* looking at internal nodes here */ - for (int child = 0; child < tree.getChildCount(node); ++child) { - NodeRef child1 = tree.getChild(node, child); - traverseForward(tree, child1); - } - } - } - - public void accumulateMatrixMultiply(double[] probabilities, double[] partials, double[] out) { - int u = 0; - int v = 0; - - for (int k = 0; k < patternCount; ++k) { - int w = 0; - for (int i = 0; i < stateCount; ++i) { - double sum1 = 0.0; - for (int j = 0; j < stateCount; ++j) { - sum1 += probabilities[w] * partials[v + j]; - w++; - } - out[u] = sum1 * out[u]; - u++; - } - v += stateCount; - } - } - - public void matrixMultiplyBackward(double[] probabilities, double[] partials, double[] out) { - int u = 0; - int v = 0; - for (int k = 0; k < patternCount; ++k) { - for (int i = 0; i < stateCount; ++i) { - int w = i; - double sum1 = 0.0; - for (int j = 0; j < stateCount; ++j) { - sum1 += probabilities[w] * partials[v + j]; - w += stateCount; - } - out[u] = sum1; - u++; - } - v += stateCount; - } - } - - /** - * The XML parser - */ - - public static final String NODE_POSTERIOR_LIKELIHOOD = "nodePosteriorLikelihood"; - public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { - - public String getParserName() { - return NODE_POSTERIOR_LIKELIHOOD; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - boolean useAmbiguities = xo.getAttribute(TreeLikelihoodParser.USE_AMBIGUITIES, false); - boolean storePartials = xo.getAttribute(TreeLikelihoodParser.STORE_PARTIALS, true); - - PatternList patternList = (PatternList) xo.getChild(PatternList.class); - TreeModel treeModel = (TreeModel) xo.getChild(TreeModel.class); - SiteModel siteModel = (SiteModel) xo.getChild(SiteModel.class); - - BranchRateModel branchRateModel = (BranchRateModel) xo.getChild(BranchRateModel.class); - - return new NodePosteriorTreeLikelihood(patternList, treeModel, siteModel, - branchRateModel, null, useAmbiguities, false, storePartials, false); - } - - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - - public String getParserDescription() { - return "This element represents the likelihood of a patternlist on a tree given the site model."; - } - - public Class getReturnType() { - return Likelihood.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{ - AttributeRule.newBooleanRule(TreeLikelihoodParser.USE_AMBIGUITIES, true), - AttributeRule.newBooleanRule(TreeLikelihoodParser.ALLOW_MISSING_TAXA, true), - new ElementRule(PatternList.class), - new ElementRule(TreeModel.class), - new ElementRule(SiteModel.class), - new ElementRule(BranchRateModel.class, true), - new ElementRule(SubstitutionModel.class) - }; - }; - -} - diff --git a/src/dr/oldevomodel/treelikelihood/NucleotideLikelihoodCore.java b/src/dr/oldevomodel/treelikelihood/NucleotideLikelihoodCore.java deleted file mode 100644 index 13f9a50f94..0000000000 --- a/src/dr/oldevomodel/treelikelihood/NucleotideLikelihoodCore.java +++ /dev/null @@ -1,349 +0,0 @@ -/* - * NucleotideLikelihoodCore.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.treelikelihood; - -/** - * NucleotideLikelihoodCore - An implementation of LikelihoodCore optimised - * for nucleotides. - * - * - * @author Andrew Rambaut - * @author Alexei Drummond - */ - -@Deprecated // Switching to BEAGLE -public class NucleotideLikelihoodCore extends AbstractLikelihoodCore { - - /** - * Constructor - */ - public NucleotideLikelihoodCore() { - - super(4); - - } - - /** - * Calculates partial likelihoods at a node when both children have states. - */ - protected void calculateStatesStatesPruning(int[] states1, double[] matrices1, - int[] states2, double[] matrices2, - double[] partials3) - { - int v = 0; - int u = 0; - for (int j = 0; j < matrixCount; j++) { - - for (int k = 0; k < patternCount; k++) { - - int w = u; - - int state1 = states1[k]; - int state2 = states2[k]; - - if (state1 < 4 && state2 < 4) { - - partials3[v] = matrices1[w + state1] * matrices2[w + state2]; - v++; w += 4; - partials3[v] = matrices1[w + state1] * matrices2[w + state2]; - v++; w += 4; - partials3[v] = matrices1[w + state1] * matrices2[w + state2]; - v++; w += 4; - partials3[v] = matrices1[w + state1] * matrices2[w + state2]; - v++; w += 4; - - } else if (state1 < 4) { - // child 2 has a gap or unknown state so don't use it - - partials3[v] = matrices1[w + state1]; - v++; w += 4; - partials3[v] = matrices1[w + state1]; - v++; w += 4; - partials3[v] = matrices1[w + state1]; - v++; w += 4; - partials3[v] = matrices1[w + state1]; - v++; w += 4; - - } else if (state2 < 4) { - // child 2 has a gap or unknown state so don't use it - partials3[v] = matrices2[w + state2]; - v++; w += 4; - partials3[v] = matrices2[w + state2]; - v++; w += 4; - partials3[v] = matrices2[w + state2]; - v++; w += 4; - partials3[v] = matrices2[w + state2]; - v++; w += 4; - - } else { - // both children have a gap or unknown state so set partials to 1 - partials3[v] = 1.0; - v++; - partials3[v] = 1.0; - v++; - partials3[v] = 1.0; - v++; - partials3[v] = 1.0; - v++; - } - } - - u += matrixSize; - } - } - - /** - * Calculates partial likelihoods at a node when one child has states and one has partials. - */ - protected void calculateStatesPartialsPruning( int[] states1, double[] matrices1, - double[] partials2, double[] matrices2, - double[] partials3) - { - int u = 0; - int v = 0; - int w = 0; - - for (int l = 0; l < matrixCount; l++) { - for (int k = 0; k < patternCount; k++) { - - int state1 = states1[k]; - - if (state1 < 4) { - - double sum; - - sum = matrices2[w] * partials2[v]; - sum += matrices2[w + 1] * partials2[v + 1]; - sum += matrices2[w + 2] * partials2[v + 2]; - sum += matrices2[w + 3] * partials2[v + 3]; - partials3[u] = matrices1[w + state1] * sum; u++; - - sum = matrices2[w + 4] * partials2[v]; - sum += matrices2[w + 5] * partials2[v + 1]; - sum += matrices2[w + 6] * partials2[v + 2]; - sum += matrices2[w + 7] * partials2[v + 3]; - partials3[u] = matrices1[w + 4 + state1] * sum; u++; - - sum = matrices2[w + 8] * partials2[v]; - sum += matrices2[w + 9] * partials2[v + 1]; - sum += matrices2[w + 10] * partials2[v + 2]; - sum += matrices2[w + 11] * partials2[v + 3]; - partials3[u] = matrices1[w + 8 + state1] * sum; u++; - - sum = matrices2[w + 12] * partials2[v]; - sum += matrices2[w + 13] * partials2[v + 1]; - sum += matrices2[w + 14] * partials2[v + 2]; - sum += matrices2[w + 15] * partials2[v + 3]; - partials3[u] = matrices1[w + 12 + state1] * sum; u++; - - v += 4; - - } else { - // Child 1 has a gap or unknown state so don't use it - - double sum; - - sum = matrices2[w] * partials2[v]; - sum += matrices2[w + 1] * partials2[v + 1]; - sum += matrices2[w + 2] * partials2[v + 2]; - sum += matrices2[w + 3] * partials2[v + 3]; - partials3[u] = sum; u++; - - sum = matrices2[w + 4] * partials2[v]; - sum += matrices2[w + 5] * partials2[v + 1]; - sum += matrices2[w + 6] * partials2[v + 2]; - sum += matrices2[w + 7] * partials2[v + 3]; - partials3[u] = sum; u++; - - sum = matrices2[w + 8] * partials2[v]; - sum += matrices2[w + 9] * partials2[v + 1]; - sum += matrices2[w + 10] * partials2[v + 2]; - sum += matrices2[w + 11] * partials2[v + 3]; - partials3[u] = sum; u++; - - sum = matrices2[w + 12] * partials2[v]; - sum += matrices2[w + 13] * partials2[v + 1]; - sum += matrices2[w + 14] * partials2[v + 2]; - sum += matrices2[w + 15] * partials2[v + 3]; - partials3[u] = sum; u++; - - v += 4; - } - } - - w += matrixSize; - } - } - - /** - * Calculates partial likelihoods at a node when both children have partials. - */ - protected void calculatePartialsPartialsPruning(double[] partials1, double[] matrices1, - double[] partials2, double[] matrices2, - double[] partials3) - { - - double sum1, sum2; - - int u = 0; - int v = 0; - int w = 0; - - for (int l = 0; l < matrixCount; l++) { - for (int k = 0; k < patternCount; k++) { - - sum1 = matrices1[w] * partials1[v]; - sum2 = matrices2[w] * partials2[v]; - sum1 += matrices1[w + 1] * partials1[v + 1]; - sum2 += matrices2[w + 1] * partials2[v + 1]; - sum1 += matrices1[w + 2] * partials1[v + 2]; - sum2 += matrices2[w + 2] * partials2[v + 2]; - sum1 += matrices1[w + 3] * partials1[v + 3]; - sum2 += matrices2[w + 3] * partials2[v + 3]; - partials3[u] = sum1 * sum2; u++; - - sum1 = matrices1[w + 4] * partials1[v]; - sum2 = matrices2[w + 4] * partials2[v]; - sum1 += matrices1[w + 5] * partials1[v + 1]; - sum2 += matrices2[w + 5] * partials2[v + 1]; - sum1 += matrices1[w + 6] * partials1[v + 2]; - sum2 += matrices2[w + 6] * partials2[v + 2]; - sum1 += matrices1[w + 7] * partials1[v + 3]; - sum2 += matrices2[w + 7] * partials2[v + 3]; - partials3[u] = sum1 * sum2; u++; - - sum1 = matrices1[w + 8] * partials1[v]; - sum2 = matrices2[w + 8] * partials2[v]; - sum1 += matrices1[w + 9] * partials1[v + 1]; - sum2 += matrices2[w + 9] * partials2[v + 1]; - sum1 += matrices1[w + 10] * partials1[v + 2]; - sum2 += matrices2[w + 10] * partials2[v + 2]; - sum1 += matrices1[w + 11] * partials1[v + 3]; - sum2 += matrices2[w + 11] * partials2[v + 3]; - partials3[u] = sum1 * sum2; u++; - - sum1 = matrices1[w + 12] * partials1[v]; - sum2 = matrices2[w + 12] * partials2[v]; - sum1 += matrices1[w + 13] * partials1[v + 1]; - sum2 += matrices2[w + 13] * partials2[v + 1]; - sum1 += matrices1[w + 14] * partials1[v + 2]; - sum2 += matrices2[w + 14] * partials2[v + 2]; - sum1 += matrices1[w + 15] * partials1[v + 3]; - sum2 += matrices2[w + 15] * partials2[v + 3]; - partials3[u] = sum1 * sum2; u++; - - v += 4; - } - - w += matrixSize; - } - - } - - - /** - * Calculates partial likelihoods at a node when both children have states. - */ - protected void calculateStatesStatesPruning(int[] states1, double[] matrices1, - int[] states2, double[] matrices2, - double[] partials3, int[] matrixMap) - { - throw new RuntimeException("calculateStatesStatesPruning not implemented using matrixMap"); - } - - /** - * Calculates partial likelihoods at a node when one child has states and one has partials. - */ - protected void calculateStatesPartialsPruning( int[] states1, double[] matrices1, - double[] partials2, double[] matrices2, - double[] partials3, int[] matrixMap) - { - throw new RuntimeException("calculateStatesStatesPruning not implemented using matrixMap"); - } - - /** - * Calculates partial likelihoods at a node when both children have partials. - */ - protected void calculatePartialsPartialsPruning(double[] partials1, double[] matrices1, - double[] partials2, double[] matrices2, - double[] partials3, int[] matrixMap) - { - throw new RuntimeException("calculateStatesStatesPruning not implemented using matrixMap"); - } - - /** - * Integrates partials across categories. - * @param inPartials the partials at the node to be integrated - * @param proportions the proportions of sites in each category - * @param outPartials an array into which the integrated partials will go - */ - public void calculateIntegratePartials(double[] inPartials, double[] proportions, double[] outPartials) { - - int u = 0; - int v = 0; - for (int k = 0; k < patternCount; k++) { - - outPartials[u] = inPartials[v] * proportions[0]; u++; v++; - outPartials[u] = inPartials[v] * proportions[0]; u++; v++; - outPartials[u] = inPartials[v] * proportions[0]; u++; v++; - outPartials[u] = inPartials[v] * proportions[0]; u++; v++; - } - - - for (int j = 1; j < matrixCount; j++) { - u = 0; - for (int k = 0; k < patternCount; k++) { - outPartials[u] += inPartials[v] * proportions[j]; u++; v++; - outPartials[u] += inPartials[v] * proportions[j]; u++; v++; - outPartials[u] += inPartials[v] * proportions[j]; u++; v++; - outPartials[u] += inPartials[v] * proportions[j]; u++; v++; - - } - } - } - - /** - * Calculates site likelihoods at a node. - * @param partials the partials used to calculate the likelihoods - * @param frequencies an array of state frequencies - * @param outLogLikelihoods an array into which the likelihoods will go - */ - public void calculateLogLikelihoods(double[] partials, double[] frequencies, double[] outLogLikelihoods) - { - int v = 0; - for (int k = 0; k < patternCount; k++) { - double sum = frequencies[0] * partials[v]; v++; - sum += frequencies[1] * partials[v]; v++; - sum += frequencies[2] * partials[v]; v++; - sum += frequencies[3] * partials[v]; v++; - outLogLikelihoods[k] = Math.log(sum) + getLogScalingFactor(k); - } - } - -} - diff --git a/src/dr/oldevomodel/treelikelihood/PrecisionTestTreeLikelihood.java b/src/dr/oldevomodel/treelikelihood/PrecisionTestTreeLikelihood.java deleted file mode 100644 index d9bc4ce34b..0000000000 --- a/src/dr/oldevomodel/treelikelihood/PrecisionTestTreeLikelihood.java +++ /dev/null @@ -1,525 +0,0 @@ -/* - * PrecisionTestTreeLikelihood.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.treelikelihood; - -import dr.evolution.alignment.PatternList; -import dr.evolution.tree.NodeRef; -import dr.evolution.tree.Tree; -import dr.evolution.util.TaxonList; -import dr.evomodel.branchratemodel.BranchRateModel; -import dr.evomodel.branchratemodel.DefaultBranchRateModel; -import dr.evomodel.tree.TreeChangedEvent; -import dr.oldevomodel.sitemodel.SiteModel; -import dr.oldevomodel.substmodel.FrequencyModel; -import dr.evomodel.tree.TreeModel; -import dr.inference.model.Likelihood; -import dr.inference.model.Model; -import dr.xml.*; - -import java.math.BigDecimal; -import java.util.logging.Logger; - -/** - * TreeLikelihoodModel - implements a Likelihood Function for sequences on a tree. - * - * @author Andrew Rambaut - * @author Alexei Drummond - */ - -@Deprecated // Switching to BEAGLE -public class PrecisionTestTreeLikelihood extends AbstractTreeLikelihood { - - public static final String TREE_LIKELIHOOD = "precisionTestTreeLikelihood"; - public static final String USE_AMBIGUITIES = "useAmbiguities"; - public static final String ALLOW_MISSING_TAXA = "allowMissingTaxa"; - public static final String STORE_PARTIALS = "storePartials"; - public static final String USE_SCALING = "useScaling"; - public static final String FORCE_JAVA_CORE = "forceJavaCore"; - - /** - * Constructor. - */ - public PrecisionTestTreeLikelihood(PatternList patternList, - TreeModel treeModel, - SiteModel siteModel, - BranchRateModel branchRateModel, - boolean useAmbiguities, - boolean allowMissingTaxa, - boolean storePartials) { - - super(TREE_LIKELIHOOD, patternList, treeModel); - - this.storePartials = storePartials; - - try { - this.siteModel = siteModel; - addModel(siteModel); - - this.frequencyModel = siteModel.getFrequencyModel(); - addModel(frequencyModel); - - this.categoryCount = siteModel.getCategoryCount(); - - final Logger logger = Logger.getLogger("dr.evomodel"); - String coreName = "Java general"; - likelihoodCore = new GeneralLikelihoodCore(patternList.getStateCount()); - precisionLikelihoodCore = new ArbitraryPrecisionLikelihoodCore(patternList.getStateCount(), 20); - - logger.info("PrecisionTestTreeLikelihood using " + coreName + " likelihood core"); - - logger.info(" " + (useAmbiguities ? "Using" : "Ignoring") + " ambiguities in tree likelihood."); - - if (branchRateModel != null) { - this.branchRateModel = branchRateModel; - logger.info("Branch rate model used: " + branchRateModel.getModelName()); - } else { - this.branchRateModel = new DefaultBranchRateModel(); - } - addModel(this.branchRateModel); - - probabilities = new double[stateCount * stateCount]; - - likelihoodCore.initialize(nodeCount, patternCount, categoryCount, true); - precisionLikelihoodCore.initialize(nodeCount, patternCount, categoryCount, true); - - int extNodeCount = treeModel.getExternalNodeCount(); - int intNodeCount = treeModel.getInternalNodeCount(); - - for (int i = 0; i < extNodeCount; i++) { - // Find the id of tip i in the patternList - String id = treeModel.getTaxonId(i); - int index = patternList.getTaxonIndex(id); - - if (index == -1) { - if (!allowMissingTaxa) { - throw new TaxonList.MissingTaxonException("Taxon, " + id + ", in tree, " + treeModel.getId() + - ", is not found in patternList, " + patternList.getId()); - } - if (useAmbiguities) { - setMissingPartials(likelihoodCore, i); - setMissingPartials(precisionLikelihoodCore, i); - } else { - setMissingStates(likelihoodCore, i); - setMissingStates(precisionLikelihoodCore, i); - } - } else { - if (useAmbiguities) { - setPartials(likelihoodCore, patternList, categoryCount, index, i); - setPartials(precisionLikelihoodCore, patternList, categoryCount, index, i); - } else { - setStates(likelihoodCore, patternList, index, i); - setStates(precisionLikelihoodCore, patternList, index, i); - } - } - } - - for (int i = 0; i < intNodeCount; i++) { - likelihoodCore.createNodePartials(extNodeCount + i); - precisionLikelihoodCore.createNodePartials(extNodeCount + i); - } - } catch (TaxonList.MissingTaxonException mte) { - throw new RuntimeException(mte.toString()); - } - } - - // ************************************************************** - // ModelListener IMPLEMENTATION - // ************************************************************** - - /** - * Handles model changed events from the submodels. - */ - protected void handleModelChangedEvent(Model model, Object object, int index) { - - if (model == treeModel) { - if (object instanceof TreeChangedEvent) { - - if (((TreeChangedEvent) object).isNodeChanged()) { - // If a node event occurs the node and its two child nodes - // are flagged for updating (this will result in everything - // above being updated as well. Node events occur when a node - // is added to a branch, removed from a branch or its height or - // rate changes. - updateNodeAndChildren(((TreeChangedEvent) object).getNode()); - - } else if (((TreeChangedEvent) object).isTreeChanged()) { - // Full tree events result in a complete updating of the tree likelihood - // Currently this event type is not used. - System.err.println("Full tree update event - these events currently aren't used\n" + - "so either this is in error or a new feature is using them so remove this message."); - updateAllNodes(); - } else { - // Other event types are ignored (probably trait changes). - //System.err.println("Another tree event has occured (possibly a trait change)."); - } - } - - } else if (model == branchRateModel) { - if (index == -1) { - updateAllNodes(); - } else { - updateNode(treeModel.getNode(index)); - } - - } else if (model == frequencyModel) { - - updateAllNodes(); - - } else if (model instanceof SiteModel) { - - updateAllNodes(); - - } else { - - throw new RuntimeException("Unknown componentChangedEvent"); - } - - super.handleModelChangedEvent(model, object, index); - } - - // ************************************************************** - // Model IMPLEMENTATION - // ************************************************************** - - /** - * Stores the additional state other than model components - */ - protected void storeState() { - - if (storePartials) { - likelihoodCore.storeState(); - precisionLikelihoodCore.storeState(); - } - super.storeState(); - - } - - /** - * Restore the additional stored state - */ - protected void restoreState() { - - if (storePartials) { - likelihoodCore.restoreState(); - precisionLikelihoodCore.restoreState(); - } else { - updateAllNodes(); - } - - super.restoreState(); - - } - - // ************************************************************** - // Likelihood IMPLEMENTATION - // ************************************************************** - - /** - * Calculate the log likelihood of the current state. - * - * @return the log likelihood. - */ - protected double calculateLogLikelihood() { - - if (patternLogLikelihoods == null) { - patternLogLikelihoods = new double[patternCount]; - } - - if (precisionPatternLogLikelihoods == null) { - precisionPatternLogLikelihoods = new double[patternCount]; - } - - final NodeRef root = treeModel.getRoot(); - traverse(treeModel, root); - - double logL = 0.0; - - for (int i = 0; i < patternCount; i++) { - logL += patternLogLikelihoods[i] * patternWeights[i]; - } - - double precisionLogL = 0.0; - - for (int i = 0; i < patternCount; i++) { - precisionLogL += precisionPatternLogLikelihoods[i] * patternWeights[i]; - } - - if (Math.abs(logL - precisionLogL) > 1.0E-5) { - System.out.println("logL = " + logL + " precision logL = " + precisionLogL); - } - - if (logL == Double.NEGATIVE_INFINITY) { - // We probably had an underflow... turn on scaling - likelihoodCore.setUseScaling(true); - - // and try again... - updateAllNodes(); - updateAllPatterns(); - traverse(treeModel, root); - - logL = 0.0; - for (int i = 0; i < patternCount; i++) { - logL += patternLogLikelihoods[i] * patternWeights[i]; - } - - if (Math.abs(logL - precisionLogL) > 1.0E-5) { - System.out.println("scaled logL = " + logL + " precision logL = " + precisionLogL); - } - - } - - //******************************************************************** - // after traverse all nodes and patterns have been updated -- - //so change flags to reflect this. - for (int i = 0; i < nodeCount; i++) { - updateNode[i] = false; - } - //******************************************************************** - - return logL; - } - - /** - * Traverse the tree calculating partial likelihoods. - * - * @return whether the partials for this node were recalculated. - */ - private boolean traverse(Tree tree, NodeRef node) { - - boolean update = false; - - int nodeNum = node.getNumber(); - - NodeRef parent = tree.getParent(node); - - // First update the transition probability matrix(ices) for this branch - if (parent != null && updateNode[nodeNum]) { - - final double branchRate = branchRateModel.getBranchRate(tree, node); - - // Get the operational time of the branch - final double branchTime = branchRate * (tree.getNodeHeight(parent) - tree.getNodeHeight(node)); - - if (branchTime < 0.0) { - throw new RuntimeException("Negative branch length: " + branchTime); - } - - likelihoodCore.setNodeMatrixForUpdate(nodeNum); - precisionLikelihoodCore.setNodeMatrixForUpdate(nodeNum); - - for (int i = 0; i < categoryCount; i++) { - - double branchLength = siteModel.getRateForCategory(i) * branchTime; - siteModel.getSubstitutionModel().getTransitionProbabilities(branchLength, probabilities); - likelihoodCore.setNodeMatrix(nodeNum, i, probabilities); - precisionLikelihoodCore.setNodeMatrix(nodeNum, i, probabilities); - } - - update = true; - } - - // If the node is internal, update the partial likelihoods. - if (!tree.isExternal(node)) { - - // Traverse down the two child nodes - NodeRef child1 = tree.getChild(node, 0); - final boolean update1 = traverse(tree, child1); - - NodeRef child2 = tree.getChild(node, 1); - final boolean update2 = traverse(tree, child2); - - // If either child node was updated then update this node too - if (update1 || update2) { - - final int childNum1 = child1.getNumber(); - final int childNum2 = child2.getNumber(); - - likelihoodCore.setNodePartialsForUpdate(nodeNum); - precisionLikelihoodCore.setNodePartialsForUpdate(nodeNum); - - likelihoodCore.calculatePartials(childNum1, childNum2, nodeNum); - precisionLikelihoodCore.calculatePartials(childNum1, childNum2, nodeNum); - - if (parent == null) { - // No parent this is the root of the tree - - // calculate the pattern likelihoods - double[] frequencies = frequencyModel.getFrequencies(); - - double[] partials = getRootPartials(); - likelihoodCore.calculateLogLikelihoods(partials, frequencies, patternLogLikelihoods); - - BigDecimal[] precisionPartials = getPrecisionRootPartials(); - precisionLikelihoodCore.calculateLogLikelihoods(precisionPartials, frequencies, precisionPatternLogLikelihoods); - } - - update = true; - } - } - - return update; - - } - - public final double[] getRootPartials() { - if (rootPartials == null) { - rootPartials = new double[patternCount * stateCount]; - } - - int nodeNum = treeModel.getRoot().getNumber(); - // moved this call to here, because non-integrating siteModels don't need to support it - AD - double[] proportions = siteModel.getCategoryProportions(); - likelihoodCore.integratePartials(nodeNum, proportions, rootPartials); - - return rootPartials; - } - - private double[] rootPartials = null; - - public final BigDecimal[] getPrecisionRootPartials() { - if (precisionRootPartials == null) { - precisionRootPartials = new BigDecimal[patternCount * stateCount]; - } - - int nodeNum = treeModel.getRoot().getNumber(); - // moved this call to here, because non-integrating siteModels don't need to support it - AD - double[] proportions = siteModel.getCategoryProportions(); - precisionLikelihoodCore.integratePartials(nodeNum, proportions, precisionRootPartials); - - return precisionRootPartials; - } - - private BigDecimal[] precisionRootPartials = null; - - /** - * The XML parser - */ - public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { - - public String getParserName() { - return TREE_LIKELIHOOD; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - boolean useAmbiguities = xo.getAttribute(USE_AMBIGUITIES, false); - boolean allowMissingTaxa = xo.getAttribute(ALLOW_MISSING_TAXA, false); - boolean storePartials = xo.getAttribute(STORE_PARTIALS, true); - - PatternList patternList = (PatternList) xo.getChild(PatternList.class); - TreeModel treeModel = (TreeModel) xo.getChild(TreeModel.class); - SiteModel siteModel = (SiteModel) xo.getChild(SiteModel.class); - - BranchRateModel branchRateModel = (BranchRateModel) xo.getChild(BranchRateModel.class); - - return new PrecisionTestTreeLikelihood( - patternList, - treeModel, - siteModel, - branchRateModel, - useAmbiguities, allowMissingTaxa, storePartials); - } - - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - - public String getParserDescription() { - return "This element represents the likelihood of a patternlist on a tree given the site model."; - } - - public Class getReturnType() { - return Likelihood.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{ - AttributeRule.newBooleanRule(USE_AMBIGUITIES, true), - AttributeRule.newBooleanRule(ALLOW_MISSING_TAXA, true), - AttributeRule.newBooleanRule(STORE_PARTIALS, true), - new ElementRule(PatternList.class), - new ElementRule(TreeModel.class), - new ElementRule(SiteModel.class), - new ElementRule(BranchRateModel.class, true), - }; - }; - - // ************************************************************** - // INSTANCE VARIABLES - // ************************************************************** - - /** - * the frequency model for these sites - */ - protected final FrequencyModel frequencyModel; - - /** - * the site model for these sites - */ - protected final SiteModel siteModel; - - /** - * the branch rate model - */ - protected final BranchRateModel branchRateModel; - - private final boolean storePartials; - - /** - * the categories for each site - */ - protected int[] siteCategories = null; - - - /** - * the pattern likelihoods - */ - protected double[] patternLogLikelihoods = null; - /** - * the pattern likelihoods - */ - protected double[] precisionPatternLogLikelihoods = null; - - /** - * the number of rate categories - */ - protected int categoryCount; - - /** - * an array used to store transition probabilities - */ - protected double[] probabilities; - - /** - * the LikelihoodCore - */ - protected LikelihoodCore likelihoodCore; - protected ArbitraryPrecisionLikelihoodCore precisionLikelihoodCore; -} \ No newline at end of file diff --git a/src/dr/oldevomodel/treelikelihood/PurifyingGammaTreeLikelihood.java b/src/dr/oldevomodel/treelikelihood/PurifyingGammaTreeLikelihood.java deleted file mode 100644 index 377e195cc0..0000000000 --- a/src/dr/oldevomodel/treelikelihood/PurifyingGammaTreeLikelihood.java +++ /dev/null @@ -1,512 +0,0 @@ -/* - * PurifyingGammaTreeLikelihood.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.treelikelihood; - -import dr.evolution.alignment.PatternList; -import dr.evolution.tree.NodeRef; -import dr.evolution.tree.Tree; -import dr.evolution.util.TaxonList; -import dr.evomodel.tree.TreeChangedEvent; -import dr.oldevomodel.sitemodel.GammaSiteModel; -import dr.oldevomodel.sitemodel.SiteModel; -import dr.oldevomodel.substmodel.FrequencyModel; -import dr.evomodel.tree.TreeModel; -import dr.inference.model.Likelihood; -import dr.inference.model.Model; -import dr.inference.model.Parameter; -import dr.xml.*; - -/** - * PurifyingGammaTreeLikelihood - implements a Likelihood Function for sequences on a tree. - * - * @author Andrew Rambaut - */ - -@Deprecated // Switching to BEAGLE -public class PurifyingGammaTreeLikelihood extends AbstractTreeLikelihood { - - public static final String PURIFYING_GAMMA_TREE_LIKELIHOOD = "purifyingGammaTreeLikelihood"; - public static final String SUBSTITUTION_MODEL = "substitutionModel"; - public static final String HALF_LIFE = "halfLife"; - public static final String SUBSTITUTION_RATE = "substitutionRate"; - - /** - * Constructor. - */ - public PurifyingGammaTreeLikelihood(PatternList patternList, - TreeModel treeModel, - GammaSiteModel siteModel, - Parameter substitutionRateParameter, - Parameter halfLifeParameter, - boolean useAmbiguities) throws TaxonList.MissingTaxonException { - - super(PURIFYING_GAMMA_TREE_LIKELIHOOD, patternList, treeModel); - - try { - this.siteModel = siteModel; - addModel(siteModel); - - this.frequencyModel = siteModel.getFrequencyModel(); - addModel(frequencyModel); - - this.substitutionRateParameter = substitutionRateParameter; - addVariable(substitutionRateParameter); - - this.halfLifeParameter = halfLifeParameter; - addVariable(halfLifeParameter); - - this.gammaCategoryCount = siteModel.getCategoryCount(); - this.categoryCount = gammaCategoryCount; - - if (patternList.getDataType() instanceof dr.evolution.datatype.Nucleotides) { - - if (NativeNucleotideLikelihoodCore.isAvailable()) { - - System.out.println("TreeLikelihood using native nucleotide likelihood core."); - likelihoodCore = new NativeNucleotideLikelihoodCore(); - } else { - - System.out.println("TreeLikelihood using Java nucleotide likelihood core."); - likelihoodCore = new NucleotideLikelihoodCore(); - } - - } else if (patternList.getDataType() instanceof dr.evolution.datatype.AminoAcids) { - System.out.println("TreeLikelihood using Java amino acid likelihood core."); - likelihoodCore = new AminoAcidLikelihoodCore(); - } else { - System.out.println("TreeLikelihood using Java general likelihood core."); - likelihoodCore = new GeneralLikelihoodCore(patternList.getStateCount()); - } - - probabilities = new double[stateCount * stateCount]; - - likelihoodCore.initialize(nodeCount, patternCount, categoryCount, true); - - int extNodeCount = treeModel.getExternalNodeCount(); - int intNodeCount = treeModel.getInternalNodeCount(); - - for (int i = 0; i < extNodeCount; i++) { - // Find the id of tip i in the patternList - String id = treeModel.getTaxonId(i); - int index = patternList.getTaxonIndex(id); - - if (index == -1) { - throw new TaxonList.MissingTaxonException("Taxon, " + id + ", in tree, " + treeModel.getId() + - ", is not found in patternList, " + patternList.getId()); - } - - if (useAmbiguities) { - setPartials(likelihoodCore, patternList, categoryCount, index, i); - } else { - setStates(likelihoodCore, patternList, index, i); - } - } - - for (int i = 0; i < intNodeCount; i++) { - likelihoodCore.createNodePartials(extNodeCount + i); - } - } catch (TaxonList.MissingTaxonException mte) { - throw new RuntimeException(mte.toString()); - } - - } - - // ************************************************************** - // ModelListener IMPLEMENTATION - // ************************************************************** - - /** - * Handles model changed events from the submodels. - */ - protected void handleModelChangedEvent(Model model, Object object, int index) { - - if (model == treeModel) { - if (object instanceof TreeChangedEvent) { - - if (((TreeChangedEvent) object).isNodeChanged()) { - - updateNodeAndChildren(((TreeChangedEvent) object).getNode()); - - } else { - updateAllNodes(); - - } - } - } else if (model == frequencyModel) { - - updateAllNodes(); - - } else if (model instanceof SiteModel) { - - updateAllNodes(); - - } else { - - throw new RuntimeException("Unknown componentChangedEvent"); - } - - super.handleModelChangedEvent(model, object, index); - } - - - // ************************************************************** - // Model IMPLEMENTATION - // ************************************************************** - - public void handleParameterChangedEvent(Parameter parameter, int index) { - if (parameter == substitutionRateParameter || parameter == halfLifeParameter) { - - updateAllNodes(); - } - } - - /** - * Stores the additional state other than model components - */ - protected void storeState() { - - likelihoodCore.storeState(); - super.storeState(); - - } - - /** - * Restore the additional stored state - */ - protected void restoreState() { - - likelihoodCore.restoreState(); - super.restoreState(); - - } - - // ************************************************************** - // Likelihood IMPLEMENTATION - // ************************************************************** - - /** - * Calculate the log likelihood of the current state. - * - * @return the log likelihood. - */ - protected double calculateLogLikelihood() { - - final NodeRef root = treeModel.getRoot(); - - if (rootPartials == null) { - rootPartials = new double[patternCount * stateCount]; - } - - if (patternLogLikelihoods == null) { - patternLogLikelihoods = new double[patternCount]; - } - - if (gammaCategoryRates == null) { - gammaCategoryRates = new double[gammaCategoryCount]; - } - - for (int i = 0; i < gammaCategoryCount; i++) { - gammaCategoryRates[i] = siteModel.getRateForCategory(i); - } - - final double mu = siteModel.getMutationRateParameter().getParameterValue(0); - final double k = substitutionRateParameter.getParameterValue(0); - final double lambda = Math.log(2) / halfLifeParameter.getParameterValue(0); - - if (nodeTimes == null) { - nodeTimes = new double[treeModel.getNodeCount()]; - } - - calculateNodeTimes(treeModel, root); - - traverse(treeModel, root, mu, k, lambda); - - //******************************************************************** - // after traverse all nodes and patterns have been updated -- - //so change flags to reflect this. - for (int i = 0; i < nodeCount; i++) { - updateNode[i] = false; - } - //******************************************************************** - - double logL = 0.0; - - for (int i = 0; i < patternCount; i++) { - logL += patternLogLikelihoods[i] * patternWeights[i]; - } - - if (Double.isNaN(logL)) { - throw new RuntimeException("Likelihood NaN"); - } - - return logL; - } - - /** - * Traverse the tree calculating partial likelihoods. - * - * @return whether the partials for this node were recalculated. - */ - private double calculateNodeTimes(TreeModel tree, NodeRef node) { - - NodeRef parent = tree.getParent(node); - - double time0 = 0.0; - - // If the node is internal, update the partial likelihoods. - if (!tree.isExternal(node)) { - - // Traverse down the two child nodes - NodeRef child1 = tree.getChild(node, 0); - double t1 = calculateNodeTimes(tree, child1); - - NodeRef child2 = tree.getChild(node, 1); - double t2 = calculateNodeTimes(tree, child2); - - time0 = (t1 + t2) / 2.0; - } - - // don't bother if you are at the root because rate at root is ignored - if (parent == null) return 0.0; - - double branchTime = tree.getNodeHeight(parent) - tree.getNodeHeight(node); - double time1 = time0 + branchTime; - - nodeTimes[node.getNumber()] = time0; - - return time1; - } - - private double rateIntegral(double time, double mu, double k, double lambda) { - return (k * time) - (((mu - k) / lambda) * (Math.exp(-lambda * time) - 1.0)); - } - - /** - * Traverse the tree calculating partial likelihoods. - * - * @return whether the partials for this node were recalculated. - */ - private boolean traverse(Tree tree, NodeRef node, double mu, double k, double lambda) { - - boolean update = false; - - final int nodeNum = node.getNumber(); - - NodeRef parent = tree.getParent(node); - - // First update the transition probability matrix(ices) for this branch - if (parent != null && updateNode[nodeNum]) { - - double time0 = nodeTimes[node.getNumber()]; - double branchTime = tree.getNodeHeight(parent) - tree.getNodeHeight(node); - double time1 = time0 + branchTime; - - // *************************************************************** - - for (int i = 0; i < categoryCount; i++) { - - double branchLength = rateIntegral(time1, mu, k * gammaCategoryRates[i], lambda); - - if (time0 > 0.0) { - branchLength -= rateIntegral(time0, mu, k * gammaCategoryRates[i], lambda); - } - - siteModel.getTransitionProbabilities(branchLength, probabilities); - likelihoodCore.setNodeMatrix(nodeNum, i, probabilities); - } - - update = true; - } - - // If the node is internal, update the partial likelihoods. - if (!tree.isExternal(node)) { - - // Traverse down the two child nodes - NodeRef child1 = tree.getChild(node, 0); - boolean update1 = traverse(tree, child1, mu, k, lambda); - - NodeRef child2 = tree.getChild(node, 1); - boolean update2 = traverse(tree, child2, mu, k, lambda); - - // If either child node was updated then update this node too - if (update1 || update2) { - - int childNum1 = child1.getNumber(); - int childNum2 = child2.getNumber(); - - likelihoodCore.calculatePartials(childNum1, childNum2, nodeNum); - - if (parent == null) { - // No parent this is the root of the tree - - // calculate the pattern likelihoods - double[] frequencies = frequencyModel.getFrequencies(); - - // moved this call to here, because non-integrating siteModels don't need to support it - AD - double[] proportions = siteModel.getCategoryProportions(); - likelihoodCore.integratePartials(nodeNum, proportions, rootPartials); - - likelihoodCore.calculateLogLikelihoods(rootPartials, frequencies, patternLogLikelihoods); - } - - update = true; - } - } - - return update; - - } - - // ************************************************************** - // XMLElement IMPLEMENTATION - // ************************************************************** - - public org.w3c.dom.Element createElement(org.w3c.dom.Document d) { - throw new RuntimeException("createElement not implemented"); - } - - - /** - * The XML parser - */ - public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { - - public String getParserName() { - return PURIFYING_GAMMA_TREE_LIKELIHOOD; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - XMLObject cxo = (XMLObject) xo.getChild(SUBSTITUTION_RATE); - Parameter substitutionRateParam = (Parameter) cxo.getChild(Parameter.class); - - cxo = (XMLObject) xo.getChild(HALF_LIFE); - Parameter halfLifeParam = (Parameter) cxo.getChild(Parameter.class); - - PatternList patternList = (PatternList) xo.getChild(PatternList.class); - TreeModel treeModel = (TreeModel) xo.getChild(TreeModel.class); - GammaSiteModel siteModel = (GammaSiteModel) xo.getChild(GammaSiteModel.class); - - try { - return new PurifyingGammaTreeLikelihood(patternList, treeModel, siteModel, substitutionRateParam, halfLifeParam, false); - } catch (TaxonList.MissingTaxonException e) { - throw new XMLParseException(e.toString()); - } - } - - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - - public String getParserDescription() { - return "This element represents the likelihood of a patternlist on a tree given the site model."; - } - - public Class getReturnType() { - return Likelihood.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{ - new ElementRule(SUBSTITUTION_RATE, new XMLSyntaxRule[]{ - new ElementRule(Parameter.class) - }), - new ElementRule(HALF_LIFE, new XMLSyntaxRule[]{ - new ElementRule(Parameter.class) - }), - new ElementRule(PatternList.class), - new ElementRule(TreeModel.class), - new ElementRule(GammaSiteModel.class) - }; - }; - - // ************************************************************** - // INSTANCE VARIABLES - // ************************************************************** - - /** - * the frequency model for these sites - */ - protected FrequencyModel frequencyModel = null; - - /** - * the site model for these sites - */ - protected GammaSiteModel siteModel = null; - - protected Parameter substitutionRateParameter = null; - protected Parameter halfLifeParameter = null; - - private double[] nodeTimes = null; - - /** - * the root partial likelihoods - */ - protected double[] branchRates = null; - - /** - * the categories for each site - */ - protected int[] siteCategories = null; - - /** - * the root partial likelihoods - */ - protected double[] rootPartials = null; - - /** - * the pattern likelihoods - */ - protected double[] patternLogLikelihoods = null; - - /** - * the pattern likelihoods - */ - protected double[] gammaCategoryRates = null; - /** - * the number of rate categories - */ - protected int gammaCategoryCount; - - /** - * the number of rate categories - */ - protected int categoryCount; - - /** - * an array used to store transition probabilities - */ - protected double[] probabilities; - - /** - * the LikelihoodCore - */ - protected LikelihoodCore likelihoodCore; -} \ No newline at end of file diff --git a/src/dr/oldevomodel/treelikelihood/PurifyingTreeLikelihood.java b/src/dr/oldevomodel/treelikelihood/PurifyingTreeLikelihood.java deleted file mode 100644 index 77497aa718..0000000000 --- a/src/dr/oldevomodel/treelikelihood/PurifyingTreeLikelihood.java +++ /dev/null @@ -1,535 +0,0 @@ -/* - * PurifyingTreeLikelihood.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.treelikelihood; - -import dr.evolution.alignment.PatternList; -import dr.evolution.tree.NodeRef; -import dr.evolution.tree.Tree; -import dr.evolution.util.TaxonList; -import dr.evomodel.tree.TreeChangedEvent; -import dr.oldevomodel.sitemodel.SiteModel; -import dr.oldevomodel.substmodel.FrequencyModel; -import dr.evomodel.tree.TreeModel; -import dr.inference.model.Likelihood; -import dr.inference.model.Model; -import dr.inference.model.Parameter; -import dr.xml.*; - -/** - * PurifyingTreeLikelihood - implements a Likelihood Function for sequences on a tree. - * - * - * @author Andrew Rambaut - */ - -@Deprecated // Switching to BEAGLE -public class PurifyingTreeLikelihood extends AbstractTreeLikelihood { - - public static final String PURIFYING_TREE_LIKELIHOOD = "purifyingTreeLikelihood"; - public static final String HALF_LIFE = "halfLife"; - public static final String PROPORTION = "proportion"; - public static final String AVERAGE = "average"; - - /** - * Constructor. - */ - public PurifyingTreeLikelihood( PatternList patternList, - TreeModel treeModel, - SiteModel siteModel, - Parameter proportionParameter, - Parameter lambdaParameter, - boolean useAmbiguities, - boolean useAveraging ) throws TaxonList.MissingTaxonException - { - - super(PURIFYING_TREE_LIKELIHOOD, patternList, treeModel); - - this.useAveraging = useAveraging; - - try { - this.siteModel = siteModel; - addModel(siteModel); - - this.frequencyModel = siteModel.getFrequencyModel(); - addModel(frequencyModel); - - this.proportionParameter = proportionParameter; - addVariable(proportionParameter); - - this.lambdaParameter = lambdaParameter; - addVariable(lambdaParameter); - - integrateAcrossCategories = siteModel.integrateAcrossCategories(); - - this.categoryCount = siteModel.getCategoryCount(); - - if (integrateAcrossCategories) { - if (patternList.getDataType() instanceof dr.evolution.datatype.Nucleotides) { - - if (NativeNucleotideLikelihoodCore.isAvailable()) { - - System.out.println("TreeLikelihood using native nucleotide likelihood core."); - likelihoodCore = new NativeNucleotideLikelihoodCore(); - } else { - - System.out.println("TreeLikelihood using Java nucleotide likelihood core."); - likelihoodCore = new NucleotideLikelihoodCore(); - } - - } else if (patternList.getDataType() instanceof dr.evolution.datatype.AminoAcids) { - System.out.println("TreeLikelihood using Java amino acid likelihood core."); - likelihoodCore = new AminoAcidLikelihoodCore(); - } else { - System.out.println("TreeLikelihood using Java general likelihood core."); - likelihoodCore = new GeneralLikelihoodCore(patternList.getStateCount()); - } - } else { - System.out.println("TreeLikelihood using Java general likelihood core."); - likelihoodCore = new GeneralLikelihoodCore(patternList.getStateCount()); - } - - probabilities = new double[stateCount * stateCount]; - - likelihoodCore.initialize(nodeCount, patternCount, categoryCount, integrateAcrossCategories); - - int extNodeCount = treeModel.getExternalNodeCount(); - int intNodeCount = treeModel.getInternalNodeCount(); - - for (int i = 0; i < extNodeCount; i++) { - // Find the id of tip i in the patternList - String id = treeModel.getTaxonId(i); - int index = patternList.getTaxonIndex(id); - - if (index == -1) { - throw new TaxonList.MissingTaxonException("Taxon, " + id + ", in tree, " + treeModel.getId() + - ", is not found in patternList, " + patternList.getId()); - } - - if (useAmbiguities) { - setPartials(likelihoodCore, patternList, categoryCount, index, i); - } else { - setStates(likelihoodCore, patternList, index, i); - } - } - - for (int i = 0; i < intNodeCount; i++) { - likelihoodCore.createNodePartials(extNodeCount + i); - } - } catch (TaxonList.MissingTaxonException mte) { - throw new RuntimeException(mte.toString()); - } - - } - - // ************************************************************** - // ModelListener IMPLEMENTATION - // ************************************************************** - - /** - * Handles model changed events from the submodels. - */ - protected void handleModelChangedEvent(Model model, Object object, int index) { - - if (model == treeModel) { - if (object instanceof TreeChangedEvent) { - - if (((TreeChangedEvent)object).isNodeChanged()) { - - updateNodeAndChildren(((TreeChangedEvent)object).getNode()); - - } else { - updateAllNodes(); - - } - } - - updateRates = true; - - } else if (model == frequencyModel) { - - updateAllNodes(); - - } else if (model instanceof SiteModel) { - - updateAllNodes(); - - } else { - - throw new RuntimeException("Unknown componentChangedEvent"); - } - - super.handleModelChangedEvent(model, object, index); - } - - - // ************************************************************** - // Model IMPLEMENTATION - // ************************************************************** - - public void handleParameterChangedEvent(Parameter parameter, int index) { - // mu has changed - if (parameter == proportionParameter || parameter == lambdaParameter) { - - updateRates = true; - updateAllNodes(); - } - } - - /** - * Stores the additional state other than model components - */ - protected void storeState() { - - likelihoodCore.storeState(); - super.storeState(); - - } - - /** - * Restore the additional stored state - */ - protected void restoreState() { - - likelihoodCore.restoreState(); - super.restoreState(); - - } - - // ************************************************************** - // Likelihood IMPLEMENTATION - // ************************************************************** - - /** - * Calculate the log likelihood of the current state. - * @return the log likelihood. - */ - protected double calculateLogLikelihood() { - - NodeRef root = treeModel.getRoot(); - - if (rootPartials == null) { - rootPartials = new double[patternCount * stateCount]; - } - - if (patternLogLikelihoods == null) { - patternLogLikelihoods = new double[patternCount]; - } - - if (!integrateAcrossCategories) { - if (siteCategories == null) { - siteCategories = new int[patternCount]; - } - for (int i = 0; i < patternCount; i++) { - siteCategories[i] = siteModel.getCategoryOfSite(i); - } - } - - double p = proportionParameter.getParameterValue(0); - double lambda = Math.log(2)/lambdaParameter.getParameterValue(0); - - updateRates = true; - updateAllNodes(); - if (updateRates) { - if (nodeTimes == null) { - nodeTimes = new double[treeModel.getNodeCount()]; - } - - calculateNodeRates(treeModel, root, 1.0, p, lambda); - } - - traverse(treeModel, root); - - updateRates = false; - - //******************************************************************** - // after traverse all nodes and patterns have been updated -- - //so change flags to reflect this. - for (int i = 0; i < nodeCount; i++) { - updateNode[i] = false; - } - //******************************************************************** - - double logL = 0.0; - - for (int i = 0; i < patternCount; i++) { - logL += patternLogLikelihoods[i] * patternWeights[i]; - } - - if (Double.isNaN(logL)) { - throw new RuntimeException("Likelihood NaN"); - } - - return logL; - } - - /** - * Traverse the tree calculating partial likelihoods. - * @return whether the partials for this node were recalculated. - */ - private double calculateNodeRates(TreeModel tree, NodeRef node, double mu, double p, double lambda) { - - NodeRef parent = tree.getParent(node); - - double time0 = 0.0; - - // If the node is internal, update the partial likelihoods. - if (!tree.isExternal(node)) { - - // Traverse down the two child nodes - NodeRef child1 = tree.getChild(node, 0); - double t1 = calculateNodeRates(tree, child1, mu, p, lambda); - - NodeRef child2 = tree.getChild(node, 1); - double t2 = calculateNodeRates(tree, child2, mu, p, lambda); - - if (useAveraging) { - time0 = (t1 + t2) / 2.0; - } else { - // pick larger of the two - if (t1 > t2) { - time0 = t1; - } else { - time0 = t2; - } - } - } - - // don't bother if you are at the root because rate at root is ignored - if (parent == null) return 0; - - double branchTime = tree.getNodeHeight(parent) - tree.getNodeHeight(node); - double time1 = time0 + branchTime; - - double branchRate = rateIntegral(time1, mu, p, lambda); - - if (time0 > 0.0) { - branchRate -= rateIntegral(time0, mu, p, lambda); - } - - if (branchRate != tree.getNodeRate(node)) { - updateNode(node); - nodeTimes[node.getNumber()] = branchRate; - } - - return time1; - } - - private double rateIntegral(double time, double mu, double p, double lambda) { - return mu * ( (p * time) - (((1.0 - p) / lambda) * (Math.exp(-lambda * time) - 1.0))); - } - - /** - * Traverse the tree calculating partial likelihoods. - * @return whether the partials for this node were recalculated. - */ - private boolean traverse(Tree tree, NodeRef node) { - - boolean update = false; - - int nodeNum = node.getNumber(); - - NodeRef parent = tree.getParent(node); - - // First update the transition probability matrix(ices) for this branch - if (parent != null && updateNode[nodeNum]) { - - // Get the average rate over this branch - - // *************************************************************** - // Rate at nodes model - //double branchRate = (tree.getNodeRate(node) + tree.getNodeRate(parent)) / 2; - // *************************************************************** - - // *************************************************************** - // Rate at branches model - double branchTime = nodeTimes[node.getNumber()]; - // *************************************************************** - - - for (int i = 0; i < categoryCount; i++) { - double branchLength = siteModel.getRateForCategory(i) * branchTime; - siteModel.getSubstitutionModel().getTransitionProbabilities(branchLength, probabilities); - likelihoodCore.setNodeMatrix(nodeNum, i, probabilities); - } - - update = true; - } - - // If the node is internal, update the partial likelihoods. - if (!tree.isExternal(node)) { - - // Traverse down the two child nodes - NodeRef child1 = tree.getChild(node, 0); - boolean update1 = traverse(tree, child1); - - NodeRef child2 = tree.getChild(node, 1); - boolean update2 = traverse(tree, child2); - - // If either child node was updated then update this node too - if (update1 || update2) { - - int childNum1 = child1.getNumber(); - int childNum2 = child2.getNumber(); - - if (integrateAcrossCategories) { - likelihoodCore.calculatePartials(childNum1, childNum2, nodeNum); - } else { - likelihoodCore.calculatePartials(childNum1, childNum2, nodeNum, siteCategories); - } - - if (parent == null) { - // No parent this is the root of the tree - - // calculate the pattern likelihoods - double[] frequencies = frequencyModel.getFrequencies(); - - if (integrateAcrossCategories) { - - // moved this call to here, because non-integrating siteModels don't need to support it - AD - double[] proportions = siteModel.getCategoryProportions(); - likelihoodCore.integratePartials(nodeNum, proportions, rootPartials); - } else { - likelihoodCore.getPartials(nodeNum, rootPartials); - } - - likelihoodCore.calculateLogLikelihoods(rootPartials, frequencies, patternLogLikelihoods); - } - - update = true; - } - } - - return update; - - } - - // ************************************************************** - // XMLElement IMPLEMENTATION - // ************************************************************** - - public org.w3c.dom.Element createElement(org.w3c.dom.Document d) { - throw new RuntimeException("createElement not implemented"); - } - - - /** - * The XML parser - */ - public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { - - public String getParserName() { return PURIFYING_TREE_LIKELIHOOD; } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - XMLObject cxo = (XMLObject)xo.getChild(PROPORTION); - Parameter proportionParam = (Parameter)cxo.getChild(Parameter.class); - - cxo = (XMLObject)xo.getChild(HALF_LIFE); - Parameter lambdaParam = (Parameter)cxo.getChild(Parameter.class); - - PatternList patternList = (PatternList)xo.getChild(PatternList.class); - TreeModel treeModel = (TreeModel)xo.getChild(TreeModel.class); - SiteModel siteModel = (SiteModel)xo.getChild(SiteModel.class); - - boolean useAveraging = xo.getBooleanAttribute(AVERAGE); - - - try { - return new PurifyingTreeLikelihood(patternList, treeModel, siteModel, proportionParam, lambdaParam, false, useAveraging); - } catch (TaxonList.MissingTaxonException e) { - throw new XMLParseException(e.toString()); - } - } - - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - - public String getParserDescription() { - return "This element represents the likelihood of a patternlist on a tree given the site model."; - } - - public Class getReturnType() { return Likelihood.class; } - - public XMLSyntaxRule[] getSyntaxRules() { return rules; } - - private final XMLSyntaxRule[] rules = { - AttributeRule.newBooleanRule(AVERAGE, false), - new ElementRule(PROPORTION, new XMLSyntaxRule[] { - new ElementRule(Parameter.class) - }), - new ElementRule(HALF_LIFE, new XMLSyntaxRule[] { - new ElementRule(Parameter.class) - }), - new ElementRule(PatternList.class), - new ElementRule(TreeModel.class), - new ElementRule(SiteModel.class) - }; - }; - - // ************************************************************** - // INSTANCE VARIABLES - // ************************************************************** - - /** the frequency model for these sites */ - protected FrequencyModel frequencyModel = null; - - /** the site model for these sites */ - protected SiteModel siteModel = null; - - protected Parameter proportionParameter = null; - protected Parameter lambdaParameter = null; - private boolean updateRates = false; - - private double[] nodeTimes = null; - - // If true then the average of the two incoming branch lengths is used for rate function in internal branches (as opposed to longest) - private boolean useAveraging = true; - - private boolean integrateAcrossCategories = false; - - /** the root partial likelihoods */ - protected double[] branchRates = null; - - /** the categories for each site */ - protected int[] siteCategories = null; - - /** the root partial likelihoods */ - protected double[] rootPartials = null; - - /** the pattern likelihoods */ - protected double[] patternLogLikelihoods = null; - - /** the number of rate categories */ - protected int categoryCount; - - /** an array used to store transition probabilities */ - protected double[] probabilities; - - /** the LikelihoodCore */ - protected LikelihoodCore likelihoodCore; -} \ No newline at end of file diff --git a/src/dr/oldevomodel/treelikelihood/ScaleFactorsHelper.java b/src/dr/oldevomodel/treelikelihood/ScaleFactorsHelper.java deleted file mode 100644 index fea9015cf6..0000000000 --- a/src/dr/oldevomodel/treelikelihood/ScaleFactorsHelper.java +++ /dev/null @@ -1,173 +0,0 @@ -/* - * ScaleFactorsHelper.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.treelikelihood; - -import dr.evolution.tree.NodeRef; -import dr.evolution.tree.Tree; -import dr.evomodel.treelikelihood.LikelihoodScalingProvider; -import dr.inference.model.AbstractModel; -import dr.inference.model.Model; -import dr.inference.model.Parameter; -import dr.inference.model.Variable; - -import java.util.Arrays; - -/** - * @author Marc A. Suchard - */ -@Deprecated // Switching to BEAGLE -public class ScaleFactorsHelper extends AbstractModel { - - public ScaleFactorsHelper(LikelihoodScalingProvider scalingProvider, - Model treeLikelihood, - Tree treeModel, - int stateCount, - int patternCount, - int categoryCount) { - super("ScaleFactorHelper"); - this.scalingProvider = scalingProvider; - this.treeLikelihood = treeLikelihood; - this.treeModel = treeModel; - this.stateCount = stateCount; - this.patternCount = patternCount; - this.categoryCount = categoryCount; - - addModel(treeLikelihood); - } - - private double[][] scaleFactors = null; - private double[][] storedScaleFactors = null; - private boolean scaleFactorsKnown = false; - private boolean storedScaleFactorsKnown = false; - private double[] buffer = null; - - final private LikelihoodScalingProvider scalingProvider; - final private Model treeLikelihood; - final private Tree treeModel; - final private int stateCount; - final private int patternCount; - final private int categoryCount; - - private void addScaleFactors(final double[] in0, final double[] in1, final double[] in2, - double[] out, final int length) { - for (int i = 0; i < length; ++i) { - out[i] = in0[i] + in1[i] + in2[i]; - } - } - - private void traverseComputeScaleFactors(final Tree tree, final NodeRef node) { - - final int nodeNumber = node.getNumber(); - - if (tree.isExternal(node)) { - Arrays.fill(scaleFactors[nodeNumber], 0.0); - } else { - final NodeRef child0 = tree.getChild(node, 0); - final NodeRef child1 = tree.getChild(node, 1); - - traverseComputeScaleFactors(tree, child0); - traverseComputeScaleFactors(tree, child1); - - if (!tree.isExternal(child0) || !tree.isExternal(child1)) { - scalingProvider.getLogScalingFactors(nodeNumber, buffer); - addScaleFactors(scaleFactors[child0.getNumber()], scaleFactors[child1.getNumber()], - buffer, scaleFactors[nodeNumber], patternCount); - } else { - scalingProvider.getLogScalingFactors(nodeNumber, scaleFactors[nodeNumber]); - } - } - } - - private void computeScaleFactors() { - if (scaleFactors == null) { - scaleFactors = new double[treeModel.getNodeCount()][patternCount]; - storedScaleFactors = new double[treeModel.getNodeCount()][patternCount]; - } - if (buffer == null) { - buffer = new double[patternCount]; - } - traverseComputeScaleFactors(treeModel, treeModel.getRoot()); - } - - public void resetScaleFactors() { - scaleFactorsKnown = false; - } - - public void rescalePartials(final int nodeNumber, double[] partials) { - if (scalingProvider.arePartialsRescaled() && nodeNumber >= treeModel.getExternalNodeCount()) { - - if (!scaleFactorsKnown) { - computeScaleFactors(); - scaleFactorsKnown = true; - } - - int index = 0; - for (int category = 0; category < categoryCount; ++category) { - for (int pattern = 0; pattern < patternCount; ++pattern) { - final double scale = Math.exp(scaleFactors[nodeNumber][pattern]); - for (int state = 0; state < stateCount; ++state) { - partials[index] *= scale; - index++; - } - } - } - } - } - - protected void handleModelChangedEvent(Model model, Object object, int index) { -// if (model == treeLikelihood) { -// scaleFactorsKnown = false; // TODO Not all tree likelihood changes affect scale factors -// } else { -// throw new IllegalArgumentException("Illegal model argument"); -// } - } - - protected void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) { - // Do nothing - } - - protected void storeState() { -// for (int i = 0; i < scaleFactors.length; ++i) { -// System.arraycopy(scaleFactors[i], 0, storedScaleFactors[i], 0, scaleFactors[i].length); -// } -// storedScaleFactorsKnown = scaleFactorsKnown; - } - - protected void restoreState() { -// double[][] tmp = storedScaleFactors; -// storedScaleFactors = scaleFactors; -// scaleFactors = tmp; -// -// scaleFactorsKnown = storedScaleFactorsKnown; - } - - protected void acceptState() { - // Do nothing - } -} - diff --git a/src/dr/oldevomodel/treelikelihood/TreeBranchSubstitutionModel.java b/src/dr/oldevomodel/treelikelihood/TreeBranchSubstitutionModel.java deleted file mode 100644 index 818844ad50..0000000000 --- a/src/dr/oldevomodel/treelikelihood/TreeBranchSubstitutionModel.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * TreeBranchSubstitutionModel.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.treelikelihood; - -import dr.evolution.tree.NodeRef; -import dr.evolution.tree.Tree; -import dr.evomodel.branchratemodel.BranchRateModel; -import dr.oldevomodel.sitemodel.SiteModel; -import dr.oldevomodel.substmodel.SubstitutionModel; -import dr.inference.model.AbstractModel; -import dr.inference.model.Model; -import dr.inference.model.Parameter; -import dr.inference.model.Variable; - -/** - * TreeBranchSubstitutionModel - provides a model for making substitution model epoches. - * - * @author Marc A. Suchard - */ - -@Deprecated // Switching to BEAGLE -public class TreeBranchSubstitutionModel extends AbstractModel { - - public TreeBranchSubstitutionModel(String name) { - super(name); - } - - public TreeBranchSubstitutionModel(String name, SiteModel siteModel, SubstitutionModel substModel, BranchRateModel branchModel) { - super(name); - this.siteModel = siteModel; - this.substModel = substModel; - this.branchModel = branchModel; - - if (siteModel != null) - addModel(siteModel); - if (substModel != null) - addModel(substModel); - if (branchModel != null) - addModel(branchModel); - } - - public void getTransitionProbabilities(Tree tree, NodeRef node, int rateCategory, double[] probs) { - - NodeRef parent = tree.getParent(node); - - final double branchRate = branchModel.getBranchRate(tree, node); - - // Get the operational time of the branch - final double branchTime = branchRate * (tree.getNodeHeight(parent) - tree.getNodeHeight(node)); - - if (branchTime < 0.0) { - throw new RuntimeException("Negative branch length: " + branchTime); - } - - double branchLength = siteModel.getRateForCategory(rateCategory) * branchTime; - substModel.getTransitionProbabilities(branchLength, probs); - } // getTransitionProbabilities - - protected void handleModelChangedEvent(Model model, Object object, int index) { - } - - protected void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) { - } - - protected void storeState() { - } - - protected void restoreState() { - } - - protected void acceptState() { - } - - protected SiteModel siteModel; - protected SubstitutionModel substModel; - protected BranchRateModel branchModel; - -} diff --git a/src/dr/oldevomodel/treelikelihood/TreeLikelihood.java b/src/dr/oldevomodel/treelikelihood/TreeLikelihood.java deleted file mode 100644 index dca6ddac8c..0000000000 --- a/src/dr/oldevomodel/treelikelihood/TreeLikelihood.java +++ /dev/null @@ -1,651 +0,0 @@ -/* - * TreeLikelihood.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodel.treelikelihood; - -import dr.evolution.alignment.AscertainedSitePatterns; -import dr.evolution.alignment.PatternList; -import dr.evolution.alignment.SitePatterns; -import dr.evolution.datatype.DataType; -import dr.evolution.tree.NodeRef; -import dr.evolution.tree.Tree; -import dr.evolution.util.Taxon; -import dr.evolution.util.TaxonList; -import dr.evomodel.branchratemodel.BranchRateModel; -import dr.evomodel.branchratemodel.DefaultBranchRateModel; -import dr.evomodel.tree.TreeChangedEvent; -import dr.oldevomodel.sitemodel.SiteModel; -import dr.oldevomodel.substmodel.FrequencyModel; -import dr.evomodel.tipstatesmodel.TipStatesModel; -import dr.evomodel.tree.TreeModel; -import dr.oldevomodelxml.treelikelihood.TreeLikelihoodParser; -import dr.inference.model.Model; -import dr.inference.model.Statistic; - -import java.util.logging.Logger; - -/** - * TreeLikelihoodModel - implements a Likelihood Function for sequences on a tree. - * - * @author Andrew Rambaut - * @author Alexei Drummond - */ - -@Deprecated // Switching to BEAGLE -public class TreeLikelihood extends AbstractTreeLikelihood { - private static final boolean DEBUG = false; - - /** - * Constructor. - */ - public TreeLikelihood(PatternList patternList, - TreeModel treeModel, - SiteModel siteModel, - BranchRateModel branchRateModel, - TipStatesModel tipStatesModel, - boolean useAmbiguities, - boolean allowMissingTaxa, - boolean storePartials, - boolean forceJavaCore, - boolean forceRescaling) { - - super(TreeLikelihoodParser.TREE_LIKELIHOOD, patternList, treeModel); - - this.storePartials = storePartials; - - try { - this.siteModel = siteModel; - addModel(siteModel); - - this.frequencyModel = siteModel.getFrequencyModel(); - addModel(frequencyModel); - - this.tipStatesModel = tipStatesModel; - - integrateAcrossCategories = siteModel.integrateAcrossCategories(); - - this.categoryCount = siteModel.getCategoryCount(); - - final Logger logger = Logger.getLogger("dr.evomodel"); - String coreName = "Java general"; - if (integrateAcrossCategories) { - - final DataType dataType = patternList.getDataType(); - - if (dataType instanceof dr.evolution.datatype.Nucleotides) { - - if (!forceJavaCore && NativeNucleotideLikelihoodCore.isAvailable()) { - coreName = "native nucleotide"; - likelihoodCore = new NativeNucleotideLikelihoodCore(); - } else { - coreName = "Java nucleotide"; - likelihoodCore = new NucleotideLikelihoodCore(); - } - - } else if (dataType instanceof dr.evolution.datatype.AminoAcids) { - if (!forceJavaCore && NativeAminoAcidLikelihoodCore.isAvailable()) { - coreName = "native amino acid"; - likelihoodCore = new NativeAminoAcidLikelihoodCore(); - } else { - coreName = "Java amino acid"; - likelihoodCore = new AminoAcidLikelihoodCore(); - } - - // The codon core was out of date and did nothing more than the general core... - } else if (dataType instanceof dr.evolution.datatype.Codons) { - if (!forceJavaCore && NativeGeneralLikelihoodCore.isAvailable()) { - coreName = "native general"; - likelihoodCore = new NativeGeneralLikelihoodCore(patternList.getStateCount()); - } else { - coreName = "Java general"; - likelihoodCore = new GeneralLikelihoodCore(patternList.getStateCount()); - } - useAmbiguities = true; - } else { - if (!forceJavaCore && NativeGeneralLikelihoodCore.isAvailable()) { - coreName = "native general"; - likelihoodCore = new NativeGeneralLikelihoodCore(patternList.getStateCount()); - } else { - coreName = "Java general"; - likelihoodCore = new GeneralLikelihoodCore(patternList.getStateCount()); - } - } - } else { - likelihoodCore = new GeneralLikelihoodCore(patternList.getStateCount()); - } - { - final String id = getId(); - logger.info("TreeLikelihood(" + ((id != null) ? id : treeModel.getId()) + ") using " + coreName + " likelihood core"); - - logger.info(" " + (useAmbiguities ? "Using" : "Ignoring") + " ambiguities in tree likelihood."); - logger.info(" With " + patternList.getPatternCount() + " unique site patterns."); - } - - if (branchRateModel != null) { - this.branchRateModel = branchRateModel; - logger.info("Branch rate model used: " + branchRateModel.getModelName()); - } else { - this.branchRateModel = new DefaultBranchRateModel(); - } - addModel(this.branchRateModel); - - probabilities = new double[stateCount * stateCount]; - - likelihoodCore.initialize(nodeCount, patternCount, categoryCount, integrateAcrossCategories); - - int extNodeCount = treeModel.getExternalNodeCount(); - int intNodeCount = treeModel.getInternalNodeCount(); - - if (tipStatesModel != null) { - tipStatesModel.setTree(treeModel); - - tipPartials = new double[patternCount * stateCount]; - - for (int i = 0; i < extNodeCount; i++) { - // Find the id of tip i in the patternList - String id = treeModel.getTaxonId(i); - int index = patternList.getTaxonIndex(id); - - if (index == -1) { - throw new TaxonList.MissingTaxonException("Taxon, " + id + ", in tree, " + treeModel.getId() + - ", is not found in patternList, " + patternList.getId()); - } - - tipStatesModel.setStates(patternList, index, i, id); - likelihoodCore.createNodePartials(i); - } - - addModel(tipStatesModel); - } else { - for (int i = 0; i < extNodeCount; i++) { - // Find the id of tip i in the patternList - String id = treeModel.getTaxonId(i); - int index = patternList.getTaxonIndex(id); - - if (index == -1) { - if (!allowMissingTaxa) { - throw new TaxonList.MissingTaxonException("Taxon, " + id + ", in tree, " + treeModel.getId() + - ", is not found in patternList, " + patternList.getId()); - } - if (useAmbiguities) { - setMissingPartials(likelihoodCore, i); - } else { - setMissingStates(likelihoodCore, i); - } - } else { - if (useAmbiguities) { - setPartials(likelihoodCore, patternList, categoryCount, index, i); - } else { - setStates(likelihoodCore, patternList, index, i); - } - } - } - } - for (int i = 0; i < intNodeCount; i++) { - likelihoodCore.createNodePartials(extNodeCount + i); - } - - if (forceRescaling) { - likelihoodCore.setUseScaling(true); - logger.info(" Forcing use of partials rescaling."); - } - - } catch (TaxonList.MissingTaxonException mte) { - throw new RuntimeException(mte.toString()); - } - - addStatistic(new SiteLikelihoodsStatistic()); - } - - public final LikelihoodCore getLikelihoodCore() { - return likelihoodCore; - } - - // ************************************************************** - // ModelListener IMPLEMENTATION - // ************************************************************** - - /** - * Handles model changed events from the submodels. - */ - protected void handleModelChangedEvent(Model model, Object object, int index) { - - if (model == treeModel) { - if (object instanceof TreeChangedEvent) { - - if (((TreeChangedEvent) object).isNodeChanged()) { - // If a node event occurs the node and its two child nodes - // are flagged for updating (this will result in everything - // above being updated as well. Node events occur when a node - // is added to a branch, removed from a branch or its height or - // rate changes. - updateNodeAndChildren(((TreeChangedEvent) object).getNode()); - - } else if (((TreeChangedEvent) object).isTreeChanged()) { - // Full tree events result in a complete updating of the tree likelihood - updateAllNodes(); - } else { - // Other event types are ignored (probably trait changes). - //System.err.println("Another tree event has occured (possibly a trait change)."); - } - } - - } else if (model == branchRateModel) { - if (index == -1) { - updateAllNodes(); - } else { - if (DEBUG) { - if (index >= treeModel.getNodeCount()) { - throw new IllegalArgumentException("Node index out of bounds"); - } - } - updateNode(treeModel.getNode(index)); - } - - } else if (model == frequencyModel) { - - updateAllNodes(); - - } else if (model == tipStatesModel) { - if(object instanceof Taxon) - { - for(int i=0; i 0) { - out[i] = (patternLogLikelihoods[i] - ascertainmentCorrection) * patternWeights[i]; - } else { - out[i] = Double.NEGATIVE_INFINITY; - } - } - return out; - } - - /* Calculate ascertainment correction if working off of AscertainedSitePatterns - @param patternLogProbs log pattern probabilities - @return the log total probability for a pattern. - */ - protected double getAscertainmentCorrection(double[] patternLogProbs) { - if (patternList instanceof AscertainedSitePatterns) { - return ((AscertainedSitePatterns) patternList).getAscertainmentCorrection(patternLogProbs); - } else { - return 0.0; - } - } - - /** - * Check whether the scaling is still required. If the sum of all the logScalingFactors - * is zero then we simply turn off the useScaling flag. This will speed up the likelihood - * calculations when scaling is not required. - */ - public void checkScaling() { -// if (useScaling) { -// if (scalingCheckCount % 1000 == 0) { -// double totalScalingFactor = 0.0; -// for (int i = 0; i < nodeCount; i++) { -// for (int j = 0; j < patternCount; j++) { -// totalScalingFactor += scalingFactors[currentPartialsIndices[i]][i][j]; -// } -// } -// useScaling = totalScalingFactor < 0.0; -// Logger.getLogger("dr.evomodel").info("LikelihoodCore total log scaling factor: " + totalScalingFactor); -// if (!useScaling) { -// Logger.getLogger("dr.evomodel").info("LikelihoodCore scaling turned off."); -// } -// } -// scalingCheckCount++; -// } - } - - - /** - * Traverse the tree calculating partial likelihoods. - * - * @return whether the partials for this node were recalculated. - */ - protected boolean traverse(Tree tree, NodeRef node) { - - boolean update = false; - - int nodeNum = node.getNumber(); - - NodeRef parent = tree.getParent(node); - - // First update the transition probability matrix(ices) for this branch - if (parent != null && updateNode[nodeNum]) { - - final double branchRate = branchRateModel.getBranchRate(tree, node); - - // Get the operational time of the branch - final double branchTime = branchRate * (tree.getNodeHeight(parent) - tree.getNodeHeight(node)); - - if (branchTime < 0.0) { - throw new RuntimeException("Negative branch length: " + branchTime); - } - - likelihoodCore.setNodeMatrixForUpdate(nodeNum); - - for (int i = 0; i < categoryCount; i++) { - - double branchLength = siteModel.getRateForCategory(i) * branchTime; - siteModel.getSubstitutionModel().getTransitionProbabilities(branchLength, probabilities); - likelihoodCore.setNodeMatrix(nodeNum, i, probabilities); - } - - update = true; - } - - // If the node is internal, update the partial likelihoods. - if (!tree.isExternal(node)) { - - // Traverse down the two child nodes - NodeRef child1 = tree.getChild(node, 0); - final boolean update1 = traverse(tree, child1); - - NodeRef child2 = tree.getChild(node, 1); - final boolean update2 = traverse(tree, child2); - - // If either child node was updated then update this node too - if (update1 || update2) { - - final int childNum1 = child1.getNumber(); - final int childNum2 = child2.getNumber(); - - likelihoodCore.setNodePartialsForUpdate(nodeNum); - - if (integrateAcrossCategories) { - likelihoodCore.calculatePartials(childNum1, childNum2, nodeNum); - } else { - likelihoodCore.calculatePartials(childNum1, childNum2, nodeNum, siteCategories); - } - - if (COUNT_TOTAL_OPERATIONS) { - totalOperationCount ++; - } - - if (parent == null) { - // No parent this is the root of the tree - - // calculate the pattern likelihoods - double[] frequencies = frequencyModel.getFrequencies(); - - double[] partials = getRootPartials(); - - likelihoodCore.calculateLogLikelihoods(partials, frequencies, patternLogLikelihoods); - } - - update = true; - } - } - - return update; - - } - - public final double[] getRootPartials() { - if (rootPartials == null) { - rootPartials = new double[patternCount * stateCount]; - } - - int nodeNum = treeModel.getRoot().getNumber(); - if (integrateAcrossCategories) { - - // moved this call to here, because non-integrating siteModels don't need to support it - AD - double[] proportions = siteModel.getCategoryProportions(); - likelihoodCore.integratePartials(nodeNum, proportions, rootPartials); - } else { - likelihoodCore.getPartials(nodeNum, rootPartials); - } - - return rootPartials; - } - - /** - * the root partial likelihoods (a temporary array that is used - * to fetch the partials - it should not be examined directly - - * use getRootPartials() instead). - */ - private double[] rootPartials = null; - - public class SiteLikelihoodsStatistic extends Statistic.Abstract { - - public SiteLikelihoodsStatistic() { - super("siteLikelihoods"); - } - - public int getDimension() { - if (patternList instanceof SitePatterns) { - return ((SitePatterns)patternList).getSiteCount(); - } else { - return patternList.getPatternCount(); - } - } - - public String getDimensionName(int dim) { - return getTreeModel().getId() + "site-" + dim; - } - - public double getStatisticValue(int i) { - - if (patternList instanceof SitePatterns) { - int index = ((SitePatterns)patternList).getPatternIndex(i); - if( index >= 0 ) { - return patternLogLikelihoods[index] / patternWeights[index]; - } else { - return 0.0; - } - } else { - return patternList.getPatternCount(); - } - } - - } - - // ************************************************************** - // INSTANCE VARIABLES - // ************************************************************** - - /** - * the frequency model for these sites - */ - protected final FrequencyModel frequencyModel; - - /** - * the site model for these sites - */ - protected final SiteModel siteModel; - - /** - * the branch rate model - */ - protected final BranchRateModel branchRateModel; - - /** - * the tip partials model - */ - private final TipStatesModel tipStatesModel; - - private final boolean storePartials; - - protected final boolean integrateAcrossCategories; - - /** - * the categories for each site - */ - protected int[] siteCategories = null; - - - /** - * the pattern likelihoods - */ - protected double[] patternLogLikelihoods = null; - - /** - * the number of rate categories - */ - protected int categoryCount; - - /** - * an array used to transfer transition probabilities - */ - protected double[] probabilities; - - - /** - * an array used to transfer tip partials - */ - protected double[] tipPartials; - - /** - * the LikelihoodCore - */ - protected LikelihoodCore likelihoodCore; -} diff --git a/src/dr/oldevomodelxml/MSSD/ALSSiteModelParser.java b/src/dr/oldevomodelxml/MSSD/ALSSiteModelParser.java deleted file mode 100644 index ebbea276e7..0000000000 --- a/src/dr/oldevomodelxml/MSSD/ALSSiteModelParser.java +++ /dev/null @@ -1,147 +0,0 @@ -/* - * ALSSiteModelParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodelxml.MSSD; - -import dr.oldevomodel.sitemodel.GammaSiteModel; -import dr.oldevomodel.substmodel.SubstitutionModel; -import dr.inference.model.Parameter; -import dr.xml.*; - -import java.util.logging.Logger; - -/** - * This site model is a copy of SiteModelParser explicitly so that it is not overridden - * by the BEAGLE variant. This is because ALSTreeLikelihood requires a non-BEAGLE site - * model. - */ -public class ALSSiteModelParser extends AbstractXMLObjectParser { - - public static final String ALS_SITE_MODEL = "alsSiteModel"; - - public static final String SUBSTITUTION_MODEL = "substitutionModel"; - public static final String MUTATION_RATE = "mutationRate"; - public static final String SUBSTITUTION_RATE = "substitutionRate"; - public static final String RELATIVE_RATE = "relativeRate"; - public static final String GAMMA_SHAPE = "gammaShape"; - public static final String GAMMA_CATEGORIES = "gammaCategories"; - public static final String PROPORTION_INVARIANT = "proportionInvariant"; - - - public String[] getParserNames() { - return new String[]{ - getParserName(), "beast_" + getParserName() - }; - } - - public String getParserName() { - return ALS_SITE_MODEL; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - SubstitutionModel substitutionModel = (SubstitutionModel) xo.getElementFirstChild(SUBSTITUTION_MODEL); - - String msg = ""; - - Parameter muParam = null; - if (xo.hasChildNamed(SUBSTITUTION_RATE)) { - muParam = (Parameter) xo.getElementFirstChild(SUBSTITUTION_RATE); - - msg += "\n with initial substitution rate = " + muParam.getParameterValue(0); - } else if (xo.hasChildNamed(MUTATION_RATE)) { - muParam = (Parameter) xo.getElementFirstChild(MUTATION_RATE); - - msg += "\n with initial substitution rate = " + muParam.getParameterValue(0); - } else if (xo.hasChildNamed(RELATIVE_RATE)) { - muParam = (Parameter) xo.getElementFirstChild(RELATIVE_RATE); - - msg += "\n with initial relative rate = " + muParam.getParameterValue(0); - } - - Parameter shapeParam = null; - int catCount = 4; - if (xo.hasChildNamed(GAMMA_SHAPE)) { - final XMLObject cxo = xo.getChild(GAMMA_SHAPE); - catCount = cxo.getIntegerAttribute(GAMMA_CATEGORIES); - shapeParam = (Parameter) cxo.getChild(Parameter.class); - - msg += "\n " + catCount + " category discrete gamma with initial shape = " + shapeParam.getParameterValue(0); - } - - Parameter invarParam = null; - if (xo.hasChildNamed(PROPORTION_INVARIANT)) { - invarParam = (Parameter) xo.getElementFirstChild(PROPORTION_INVARIANT); - msg += "\n initial proportion of invariant sites = " + invarParam.getParameterValue(0); - } - - Logger.getLogger("dr.evomodel").info("Creating site model." + (msg.length() > 0 ? msg : "")); - - return new GammaSiteModel(substitutionModel, muParam, shapeParam, catCount, invarParam); - } - - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - - public String getParserDescription() { - return "A SiteModel that has a gamma distributed rates across sites"; - } - - public Class getReturnType() { - return GammaSiteModel.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private final XMLSyntaxRule[] rules = { - new ElementRule(SUBSTITUTION_MODEL, new XMLSyntaxRule[]{ - new ElementRule(SubstitutionModel.class) - }), - new XORRule( - new XORRule( - new ElementRule(SUBSTITUTION_RATE, new XMLSyntaxRule[]{ - new ElementRule(Parameter.class) - }), - new ElementRule(MUTATION_RATE, new XMLSyntaxRule[]{ - new ElementRule(Parameter.class) - }) - ), - new ElementRule(RELATIVE_RATE, new XMLSyntaxRule[]{ - new ElementRule(Parameter.class) - }), true - ), - new ElementRule(GAMMA_SHAPE, new XMLSyntaxRule[]{ - AttributeRule.newIntegerRule(GAMMA_CATEGORIES, true), - new ElementRule(Parameter.class) - }, true), - new ElementRule(PROPORTION_INVARIANT, new XMLSyntaxRule[]{ - new ElementRule(Parameter.class) - }, true) - }; -} diff --git a/src/dr/oldevomodelxml/MSSD/ALSTreeLikelihoodParser.java b/src/dr/oldevomodelxml/MSSD/ALSTreeLikelihoodParser.java deleted file mode 100644 index d5f582f962..0000000000 --- a/src/dr/oldevomodelxml/MSSD/ALSTreeLikelihoodParser.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * ALSTreeLikelihoodParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodelxml.MSSD; - -import dr.evolution.alignment.PatternList; -import dr.evolution.util.Taxon; -import dr.oldevomodel.MSSD.ALSTreeLikelihood; -import dr.oldevomodel.MSSD.AbstractObservationProcess; -import dr.oldevomodel.MSSD.AnyTipObservationProcess; -import dr.oldevomodel.MSSD.SingleTipObservationProcess; -import dr.evomodel.branchratemodel.BranchRateModel; -import dr.oldevomodel.sitemodel.SiteModel; -import dr.oldevomodel.substmodel.MutationDeathModel; -import dr.evomodel.tree.TreeModel; -import dr.oldevomodelxml.treelikelihood.TreeLikelihoodParser; -import dr.inference.model.Parameter; -import dr.xml.*; - -import java.util.logging.Logger; - -/** - * - */ -public class ALSTreeLikelihoodParser extends AbstractXMLObjectParser { - public static final String LIKE_NAME = "alsTreeLikelihood"; - public static final String INTEGRATE_GAIN_RATE = "integrateGainRate"; - public static final String OBSERVATION_PROCESS = "observationProcess"; - public static final String OBSERVATION_TYPE = "type"; - public static final String OBSERVATION_TAXON = "taxon"; - public static final String ANY_TIP = "anyTip"; - public final static String IMMIGRATION_RATE = "immigrationRate"; - public static final String FORCE_RESCALING = TreeLikelihoodParser.FORCE_RESCALING; - - public String getParserName() { - return LIKE_NAME; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - boolean useAmbiguities = false; - boolean storePartials = true; - if (xo.hasAttribute(TreeLikelihoodParser.USE_AMBIGUITIES)) { - useAmbiguities = xo.getBooleanAttribute(TreeLikelihoodParser.USE_AMBIGUITIES); - } - if (xo.hasAttribute(TreeLikelihoodParser.STORE_PARTIALS)) { - storePartials = xo.getBooleanAttribute(TreeLikelihoodParser.STORE_PARTIALS); - } - - boolean integrateGainRate = xo.getBooleanAttribute(INTEGRATE_GAIN_RATE); - - //AbstractObservationProcess observationProcess = (AbstractObservationProcess) xo.getChild(AbstractObservationProcess.class); - - - PatternList patternList = (PatternList) xo.getChild(PatternList.class); - TreeModel treeModel = (TreeModel) xo.getChild(TreeModel.class); - SiteModel siteModel = (SiteModel) xo.getChild(SiteModel.class); - BranchRateModel branchRateModel = (BranchRateModel) xo.getChild(BranchRateModel.class); - Parameter mu = ((MutationDeathModel) siteModel.getSubstitutionModel()).getDeathParameter(); - Parameter lam; - if (!integrateGainRate) { - lam = (Parameter) xo.getElementFirstChild(IMMIGRATION_RATE); - } else { - lam = new Parameter.Default("gainRate", 1.0, 0.001, 1.999); - } - AbstractObservationProcess observationProcess = null; - - Logger.getLogger("dr.evolution").info("\n ---------------------------------\nCreating ALSTreeLikelihood model."); - for (int i = 0; i < xo.getChildCount(); ++i) { - Object cxo = xo.getChild(i); - if (cxo instanceof XMLObject && ((XMLObject) cxo).getName().equals(OBSERVATION_PROCESS)) { - if (((XMLObject) cxo).getStringAttribute(OBSERVATION_TYPE).equals("singleTip")) { - String taxonName = ((XMLObject) cxo).getStringAttribute(OBSERVATION_TAXON); - Taxon taxon = treeModel.getTaxon(treeModel.getTaxonIndex(taxonName)); - observationProcess = new SingleTipObservationProcess(treeModel, patternList, siteModel, - branchRateModel, mu, lam, taxon); - Logger.getLogger("dr.evolution").info("All traits are assumed extant in " + taxonName); - } else { // "anyTip" observation process - observationProcess = new AnyTipObservationProcess(ANY_TIP, treeModel, patternList, - siteModel, branchRateModel, mu, lam); - Logger.getLogger("dr.evolution").info("Observed traits are assumed to be extant in at least one tip node."); - } - - observationProcess.setIntegrateGainRate(integrateGainRate); - } - } - Logger.getLogger("dr.evolution").info("\tIf you publish results using Acquisition-Loss-Mutation (ALS) Model likelihood, please reference Alekseyenko, Lee and Suchard (2008) Syst. Biol 57: 772-784.\n---------------------------------\n"); - - boolean forceRescaling = xo.getAttribute(FORCE_RESCALING, false); - -// forceRescaling = true; - - return new ALSTreeLikelihood(observationProcess, patternList, treeModel, siteModel, branchRateModel, - useAmbiguities, storePartials, forceRescaling); - } - - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - - public String getParserDescription() { - return "This element represents the likelihood of a patternlist on a tree given the site model."; - } - - public Class getReturnType() { - return ALSTreeLikelihood.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private final XMLSyntaxRule[] rules = { - AttributeRule.newBooleanRule(TreeLikelihoodParser.USE_AMBIGUITIES, true), - AttributeRule.newBooleanRule(TreeLikelihoodParser.STORE_PARTIALS, true), - AttributeRule.newBooleanRule(INTEGRATE_GAIN_RATE), - AttributeRule.newBooleanRule(FORCE_RESCALING, true), - new ElementRule(IMMIGRATION_RATE, new XMLSyntaxRule[]{new ElementRule(Parameter.class)}, true), - new ElementRule(PatternList.class), - new ElementRule(TreeModel.class), - new ElementRule(SiteModel.class), - new ElementRule(BranchRateModel.class, true), - new ElementRule(OBSERVATION_PROCESS, - new XMLSyntaxRule[]{AttributeRule.newStringRule(OBSERVATION_TYPE, false), - AttributeRule.newStringRule(OBSERVATION_TAXON, true)}) - //new ElementRule(AbstractObservationProcess.class) - }; - -} diff --git a/src/dr/oldevomodelxml/MSSD/AnyTipObservationProcessParser.java b/src/dr/oldevomodelxml/MSSD/AnyTipObservationProcessParser.java deleted file mode 100644 index 00ba173efb..0000000000 --- a/src/dr/oldevomodelxml/MSSD/AnyTipObservationProcessParser.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * AnyTipObservationProcessParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodelxml.MSSD; - -import dr.evolution.alignment.PatternList; -import dr.oldevomodel.MSSD.AnyTipObservationProcess; -import dr.evomodel.branchratemodel.BranchRateModel; -import dr.oldevomodel.sitemodel.SiteModel; -import dr.evomodel.tree.TreeModel; -import dr.inference.model.Parameter; -import dr.xml.*; - -import java.util.logging.Logger; - -/** - * - */ -public class AnyTipObservationProcessParser extends AbstractXMLObjectParser { - public static final String MODEL_NAME = "anyTipObservationProcess"; - final static String DEATH_RATE = "deathRate"; - final static String IMMIGRATION_RATE = "immigrationRate"; - - public String getParserName() { - return MODEL_NAME; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - Parameter mu = (Parameter) xo.getElementFirstChild(DEATH_RATE); - Parameter lam = (Parameter) xo.getElementFirstChild(IMMIGRATION_RATE); - TreeModel treeModel = (TreeModel) xo.getChild(TreeModel.class); - PatternList patterns = (PatternList) xo.getChild(PatternList.class); - SiteModel siteModel = (SiteModel) xo.getChild(SiteModel.class); - BranchRateModel branchRateModel = (BranchRateModel) xo.getChild(BranchRateModel.class); - Logger.getLogger("dr.evomodel.MSSD").info("Creating AnyTipObservationProcess model. Observed traits are assumed to be extant in at least one tip node. Initial mu = " + mu.getParameterValue(0) + " initial lam = " + lam.getParameterValue(0)); - - return new AnyTipObservationProcess(MODEL_NAME, treeModel, patterns, siteModel, branchRateModel, mu, lam); - } - - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - - public String getParserDescription() { - return "This element represents an instance of the AnyTipObservationProcess for ALSTreeLikelihood calculations"; - } - - public Class getReturnType() { - return AnyTipObservationProcess.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{ - new ElementRule(TreeModel.class), - new ElementRule(PatternList.class), - new ElementRule(SiteModel.class), - new ElementRule(BranchRateModel.class), - new ElementRule(DEATH_RATE, new XMLSyntaxRule[]{new ElementRule(Parameter.class)}), - new ElementRule(IMMIGRATION_RATE, new XMLSyntaxRule[]{new ElementRule(Parameter.class)}) - }; - -} diff --git a/src/dr/oldevomodelxml/MSSD/ExponentialBranchLengthTreePriorParser.java b/src/dr/oldevomodelxml/MSSD/ExponentialBranchLengthTreePriorParser.java deleted file mode 100644 index a2ebc090e0..0000000000 --- a/src/dr/oldevomodelxml/MSSD/ExponentialBranchLengthTreePriorParser.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * ExponentialBranchLengthTreePriorParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodelxml.MSSD; - -import dr.oldevomodel.MSSD.ExponentialBranchLengthTreePrior; -import dr.evomodel.tree.TreeModel; -import dr.xml.*; - -/** - * - */ -public class ExponentialBranchLengthTreePriorParser extends AbstractXMLObjectParser { - public static final String MODEL_NAME = "exponentialBranchLengthsPrior"; - - public String getParserName() { - return MODEL_NAME; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - TreeModel treeModel = (TreeModel) xo.getChild(TreeModel.class); - - return new ExponentialBranchLengthTreePrior(treeModel); - } - - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - - public String getParserDescription() { - return "This element represents a tree prior assuming " + - "exponentially distributed branch lengths."; - } - - public Class getReturnType() { - return ExponentialBranchLengthTreePrior.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{ - new ElementRule(TreeModel.class), - }; -} diff --git a/src/dr/oldevomodelxml/MSSD/SingleTipObservationProcessParser.java b/src/dr/oldevomodelxml/MSSD/SingleTipObservationProcessParser.java deleted file mode 100644 index d57b28e24c..0000000000 --- a/src/dr/oldevomodelxml/MSSD/SingleTipObservationProcessParser.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * SingleTipObservationProcessParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodelxml.MSSD; - -import dr.evolution.alignment.PatternList; -import dr.evolution.util.Taxon; -import dr.oldevomodel.MSSD.SingleTipObservationProcess; -import dr.evomodel.branchratemodel.BranchRateModel; -import dr.oldevomodel.sitemodel.SiteModel; -import dr.evomodel.tree.TreeModel; -import dr.inference.model.Parameter; -import dr.xml.*; - -import java.util.logging.Logger; - -/** - * - */ -public class SingleTipObservationProcessParser extends AbstractXMLObjectParser { - public final static String MODEL_NAME = "singleTipObservationProcess"; - - public String getParserName() { - return MODEL_NAME; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - Parameter mu = (Parameter) xo.getElementFirstChild(AnyTipObservationProcessParser.DEATH_RATE); - Parameter lam = (Parameter) xo.getElementFirstChild(AnyTipObservationProcessParser.IMMIGRATION_RATE); - TreeModel treeModel = (TreeModel) xo.getChild(TreeModel.class); - PatternList patterns = (PatternList) xo.getChild(PatternList.class); - Taxon sourceTaxon = (Taxon) xo.getChild(Taxon.class); - SiteModel siteModel = (SiteModel) xo.getChild(SiteModel.class); - BranchRateModel branchRateModel = (BranchRateModel) xo.getChild(BranchRateModel.class); - Logger.getLogger("dr.evomodel.MSSD").info("Creating SingleTipObservationProcess model. All traits are assumed extant in " + sourceTaxon.getId() + "Initial mu = " + mu.getParameterValue(0) + " initial lam = " + lam.getParameterValue(0)); - - return new SingleTipObservationProcess(treeModel, patterns, siteModel, branchRateModel, mu, lam, sourceTaxon); - } - - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - - public String getParserDescription() { - return "This element represents an instance of the SingleTipObservationProcess for ALSTreeLikelihood calculations"; - } - - public Class getReturnType() { - return SingleTipObservationProcess.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{ - new ElementRule(TreeModel.class), - new ElementRule(PatternList.class), - new ElementRule(Taxon.class), - new ElementRule(SiteModel.class), - new ElementRule(BranchRateModel.class), - new ElementRule(AnyTipObservationProcessParser.DEATH_RATE, new XMLSyntaxRule[]{new ElementRule(Parameter.class)}), - new ElementRule(AnyTipObservationProcessParser.IMMIGRATION_RATE, new XMLSyntaxRule[]{new ElementRule(Parameter.class)}) - }; -} diff --git a/src/dr/oldevomodelxml/clock/ACLikelihoodParser.java b/src/dr/oldevomodelxml/clock/ACLikelihoodParser.java deleted file mode 100644 index af7c8cfc2b..0000000000 --- a/src/dr/oldevomodelxml/clock/ACLikelihoodParser.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * ACLikelihoodParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodelxml.clock; - -import dr.oldevomodel.clock.ACLikelihood; -import dr.oldevomodel.clock.RateEvolutionLikelihood; -import dr.evomodel.tree.TreeModel; -import dr.inference.model.Parameter; -import dr.xml.*; - -/** - */ -public class ACLikelihoodParser extends AbstractXMLObjectParser { - - public static final String AC_LIKELIHOOD = "ACLikelihood"; - - public static final String VARIANCE = "variance"; - public static final String SHAPE = "shape"; - - public static final String DISTRIBUTION = "distribution"; - - public String getParserName() { - return AC_LIKELIHOOD; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - TreeModel tree = (TreeModel) xo.getChild(TreeModel.class); - - Parameter ratesParameter = (Parameter) xo.getElementFirstChild(RateEvolutionLikelihood.RATES); - - Parameter rootRate = (Parameter) xo.getElementFirstChild(RateEvolutionLikelihood.ROOTRATE); - - Parameter variance = (Parameter) xo.getElementFirstChild(VARIANCE); - - boolean isEpisodic = xo.getBooleanAttribute(RateEvolutionLikelihood.EPISODIC); - - //Distribution distributionModel = new InverseGaussianDistribution(0,1); - //Parameter distribution = (Parameter) xo.getElementFirstChild(DISTRIBUTION); - String distribution = xo.getStringAttribute(DISTRIBUTION); - - //boolean isLogSpace = xo.getAttribute(LOGSPACE, false); - - //return new ACLikelihood(tree, ratesParameter, variance, rootRate, isEpisodic, isLogSpace); - return new ACLikelihood(tree, ratesParameter, variance, rootRate, isEpisodic, distribution); - } - - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - - public String getParserDescription() { - return - "This element returns an object that can calculate the likelihood " + - "of rate changes in a tree under the assumption of " + - "distributed rate changes among lineages. " + - //"(log)normally distributed rate changes among lineages. " + - "Specifically, each branch is assumed to draw a rate from a " + - "distribution with mean of the rate in the " + - //"(log)normal distribution with mean of the rate in the " + - "parent branch and the given standard deviation (the variance can be optionally proportional to " + - "branch length)."; - } - - public Class getReturnType() { - return ACLikelihood.class; - } - - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{ - new ElementRule(TreeModel.class), - new ElementRule(RateEvolutionLikelihood.RATES, Parameter.class, "The branch rates parameter", false), - AttributeRule.newBooleanRule(RateEvolutionLikelihood.EPISODIC, false, "true if model is branch length independent, false if length-dependent."), - AttributeRule.newStringRule(DISTRIBUTION, false, "The distribution to use"), - //AttributeRule.newBooleanRule(LOGSPACE, true, "true if model considers the log of the rates."), - new ElementRule(RateEvolutionLikelihood.ROOTRATE, Parameter.class, "The root rate parameter"), - new ElementRule(VARIANCE, Parameter.class, "The standard deviation of the distribution"), - //new ElementRule(VARIANCE, Parameter.class, "The standard deviation of the (log)normal distribution"), - //new ElementRule(DISTRIBUTION, Parameter.class, "The distribution to use"), - //new ElementRule(DISTRIBUTION, ParametricDistributionModel.class, "The distribution model for rates among branches", false), - }; -} diff --git a/src/dr/oldevomodelxml/clock/UCLikelihoodParser.java b/src/dr/oldevomodelxml/clock/UCLikelihoodParser.java deleted file mode 100644 index c5bcb55018..0000000000 --- a/src/dr/oldevomodelxml/clock/UCLikelihoodParser.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * UCLikelihoodParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodelxml.clock; - -import dr.oldevomodel.clock.RateEvolutionLikelihood; -import dr.oldevomodel.clock.UCLikelihood; -import dr.evomodel.tree.TreeModel; -import dr.inference.model.Parameter; -import dr.xml.*; - -/** - */ -public class UCLikelihoodParser extends AbstractXMLObjectParser { - - public static final String UC_LIKELIHOOD = "UCLikelihood"; - - public static final String VARIANCE = "variance"; - - public String getParserName() { - return UC_LIKELIHOOD; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - TreeModel tree = (TreeModel) xo.getChild(TreeModel.class); - - Parameter ratesParameter = (Parameter) xo.getElementFirstChild(RateEvolutionLikelihood.RATES); - - Parameter rootRate = (Parameter) xo.getElementFirstChild(RateEvolutionLikelihood.ROOTRATE); - - Parameter variance = (Parameter) xo.getElementFirstChild(VARIANCE); - - - boolean isLogSpace = xo.getAttribute(RateEvolutionLikelihood.LOGSPACE, false); - - return new UCLikelihood(tree, ratesParameter, variance, rootRate, isLogSpace); - } - - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - - public String getParserDescription() { - return - "This element returns an object that can calculate the likelihood " + - "of rates in a tree under the assumption of " + - "(log)normally distributed rates. "; - } - - public Class getReturnType() { - return UCLikelihood.class; - } - - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private final XMLSyntaxRule[] rules = { - new ElementRule(TreeModel.class), - new ElementRule(RateEvolutionLikelihood.RATES, Parameter.class, "The branch rates parameter", false), - AttributeRule.newBooleanRule(RateEvolutionLikelihood.LOGSPACE, true, "true if model considers the log of the rates."), - new ElementRule(RateEvolutionLikelihood.ROOTRATE, Parameter.class, "The root rate parameter"), - new ElementRule(VARIANCE, Parameter.class, "The standard deviation of the (log)normal distribution"), - }; - -} diff --git a/src/dr/oldevomodelxml/indel/IstvanOperatorParser.java b/src/dr/oldevomodelxml/indel/IstvanOperatorParser.java deleted file mode 100644 index f5c010d01e..0000000000 --- a/src/dr/oldevomodelxml/indel/IstvanOperatorParser.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * IstvanOperatorParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodelxml.indel; - -import dr.oldevomodel.indel.IstvanOperator; -import dr.oldevomodel.indel.TKF91Likelihood; -import dr.xml.*; - -/** - * - */ -public class IstvanOperatorParser extends AbstractXMLObjectParser { - - public static final String ALIGMENT_CHUNK_OPERATOR = "alignmentChunkOperator"; - - public String getParserName() { - return ALIGMENT_CHUNK_OPERATOR; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - TKF91Likelihood likelihood = (TKF91Likelihood) xo.getChild(TKF91Likelihood.class); - double weight = xo.getDoubleAttribute("weight"); - double iP = xo.getDoubleAttribute("iP"); - double exponent = xo.getDoubleAttribute("exponent"); - double gapPenalty = xo.getDoubleAttribute("gapPenalty"); - - - return new IstvanOperator(iP, exponent, gapPenalty, weight, likelihood); - } - - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - - public String getParserDescription() { - return "This element represents an operator that re-aligns a small chunk of an alignment."; - } - - public Class getReturnType() { - return IstvanOperator.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{ - AttributeRule.newDoubleRule("weight"), - AttributeRule.newDoubleRule("iP", false, "tuning probability, values near zero resamples entire alignment and near 1.0 resamples single columns."), - AttributeRule.newDoubleRule("exponent", false, "tuning parameter, value of 1.0 samples random alignments, large values (e.g. 2.7) sample alignment peaked around 'best' alignment"), - AttributeRule.newDoubleRule("gapPenalty", false, "tuning parameter, must be negative, large values penalize gaps more in the alignment proposal."), - new ElementRule(TKF91Likelihood.class) - }; -} diff --git a/src/dr/oldevomodelxml/indel/TKF91LikelihoodParser.java b/src/dr/oldevomodelxml/indel/TKF91LikelihoodParser.java deleted file mode 100644 index e40df52f00..0000000000 --- a/src/dr/oldevomodelxml/indel/TKF91LikelihoodParser.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * TKF91LikelihoodParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodelxml.indel; - -import dr.evolution.alignment.Alignment; -import dr.oldevomodel.indel.TKF91Likelihood; -import dr.oldevomodel.indel.TKF91Model; -import dr.oldevomodel.sitemodel.GammaSiteModel; -import dr.evomodel.tree.TreeModel; -import dr.xml.*; - -/** - * - */ -public class TKF91LikelihoodParser extends AbstractXMLObjectParser { - - public static final String TKF91_LIKELIHOOD = "tkf91Likelihood"; - public static final String TKF91_DEATH = "deathRate"; - //public static final String MU = "mutationRate"; - - public String getParserName() { - return TKF91_LIKELIHOOD; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - TreeModel tree = (TreeModel) xo.getChild(TreeModel.class); - Alignment alignment = (Alignment) xo.getChild(Alignment.class); - GammaSiteModel siteModel = (GammaSiteModel) xo.getChild(GammaSiteModel.class); - TKF91Model tkfModel = (TKF91Model) xo.getChild(TKF91Model.class); - return new TKF91Likelihood(tree, alignment, siteModel, tkfModel); - } - - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - - public String getParserDescription() { - return "Returns the total likelihood of a single alignment under the TKF91 model, for a given tree. " + - "In particular all possible ancestral histories of insertions and deletions leading to the " + - "alignment of sequences at the tips are taken into account."; - } - - public Class getReturnType() { - return TKF91Likelihood.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private final XMLSyntaxRule[] rules = { - new ElementRule(TreeModel.class), - new ElementRule(Alignment.class), - new ElementRule(GammaSiteModel.class), - new ElementRule(TKF91Model.class) - }; -} diff --git a/src/dr/oldevomodelxml/indel/TKF91ModelParser.java b/src/dr/oldevomodelxml/indel/TKF91ModelParser.java deleted file mode 100644 index 9d6b97f352..0000000000 --- a/src/dr/oldevomodelxml/indel/TKF91ModelParser.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * TKF91ModelParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodelxml.indel; - -import dr.evolution.util.Units; -import dr.oldevomodel.indel.TKF91Model; -import dr.evoxml.util.XMLUnits; -import dr.inference.model.Parameter; -import dr.xml.*; - -/** - * Parses an element from an DOM document into a ConstantPopulation. - */ -public class TKF91ModelParser extends AbstractXMLObjectParser { - - public static final String TKF91_MODEL = "tkf91Model"; - public static final String TKF91_LENGTH_DIST = "lengthDistribution"; - public static final String BIRTH_RATE = "birthRate"; - public static final String DEATH_RATE = "deathRate"; - - public String getParserName() { - return TKF91_MODEL; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - Parameter lengthDistParameter = (Parameter) xo.getElementFirstChild(TKF91_LENGTH_DIST); - Parameter deathParameter = (Parameter) xo.getElementFirstChild(DEATH_RATE); - Units.Type units = XMLUnits.Utils.getUnitsAttr(xo); - - return new TKF91Model(lengthDistParameter, deathParameter, units); - } - - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - - public String getParserDescription() { - return "The TKF91 (Thorne, Kishino & Felsenstein 1991) model of insertion-deletion."; - } - - public Class getReturnType() { - return TKF91Model.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private final XMLSyntaxRule[] rules = { - new ElementRule(TKF91_LENGTH_DIST, - new XMLSyntaxRule[]{new ElementRule(Parameter.class)}), - new ElementRule(DEATH_RATE, - new XMLSyntaxRule[]{new ElementRule(Parameter.class)}), - XMLUnits.SYNTAX_RULES[0] - }; -} diff --git a/src/dr/oldevomodelxml/sitemodel/CategorySiteModelParser.java b/src/dr/oldevomodelxml/sitemodel/CategorySiteModelParser.java deleted file mode 100644 index 458344977f..0000000000 --- a/src/dr/oldevomodelxml/sitemodel/CategorySiteModelParser.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * CategorySiteModelParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodelxml.sitemodel; - -import dr.oldevomodel.sitemodel.CategorySiteModel; -import dr.oldevomodel.substmodel.SubstitutionModel; -import dr.inference.model.Parameter; -import dr.xml.*; - -/** - */ -public class CategorySiteModelParser extends AbstractXMLObjectParser { - - public static final String SITE_MODEL = "categorySiteModel"; - public static final String SUBSTITUTION_MODEL = "substitutionModel"; - public static final String MUTATION_RATE = "mutationRate"; - public static final String RATE_PARAMETER = "rates"; - public static final String CATEGORIES = "categories"; - public static final String CATEGORY_STATES = "states"; - public static final String CATEGORY_STRING = "values"; - public static final String RELATIVE_TO = "relativeTo"; - - public String getParserName() { - return SITE_MODEL; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - XMLObject cxo = xo.getChild(SUBSTITUTION_MODEL); - SubstitutionModel substitutionModel = (SubstitutionModel) cxo.getChild(SubstitutionModel.class); - - cxo = xo.getChild(MUTATION_RATE); - Parameter muParam = (Parameter) cxo.getChild(Parameter.class); - - cxo = xo.getChild(RATE_PARAMETER); - Parameter rateParam = null; - int relativeTo = 0; - if (cxo != null) { - rateParam = (Parameter) cxo.getChild(Parameter.class); - relativeTo = cxo.getIntegerAttribute(RELATIVE_TO); - } - - cxo = xo.getChild(CATEGORIES); - String categories = ""; - String states = ""; - if (cxo != null) { - categories = cxo.getStringAttribute(CATEGORY_STRING); - states = cxo.getStringAttribute(CATEGORY_STATES); - } - - return new CategorySiteModel(substitutionModel, muParam, rateParam, categories, states, relativeTo); - - } - - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - - public String getParserDescription() { - return "A SiteModel that has a gamma distributed rates across sites"; - } - - public Class getReturnType() { - return CategorySiteModel.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private final XMLSyntaxRule[] rules = { - new ElementRule(SUBSTITUTION_MODEL, new XMLSyntaxRule[]{ - new ElementRule(SubstitutionModel.class) - }), - new ElementRule(MUTATION_RATE, new XMLSyntaxRule[]{ - new ElementRule(Parameter.class) - }), - new ElementRule(RATE_PARAMETER, new XMLSyntaxRule[]{ - AttributeRule.newIntegerRule(RELATIVE_TO, true), - new ElementRule(Parameter.class) - }, true), - new ElementRule(CATEGORIES, new XMLSyntaxRule[]{ - AttributeRule.newStringRule(CATEGORY_STRING, true), - AttributeRule.newStringRule(CATEGORY_STATES, true) - }, true), - }; - -} diff --git a/src/dr/oldevomodelxml/sitemodel/DiscretizedLociRatesParser.java b/src/dr/oldevomodelxml/sitemodel/DiscretizedLociRatesParser.java deleted file mode 100644 index 7d16b8384a..0000000000 --- a/src/dr/oldevomodelxml/sitemodel/DiscretizedLociRatesParser.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * DiscretizedLociRatesParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodelxml.sitemodel; - -import dr.xml.*; -import dr.evomodel.branchratemodel.DiscretizedBranchRates; -import dr.oldevomodel.sitemodel.DiscretizedLociRates; -import dr.inference.distribution.ParametricDistributionModel; -import dr.inference.model.Parameter; -import dr.inference.model.CompoundParameter; - -import java.util.logging.Logger; - -/** - * @author Chieh-Hsi Wu - * Parser of DiscretizedLociRates - */ -public class DiscretizedLociRatesParser extends AbstractXMLObjectParser { - public final String DISCRETIZED_LOCI_RATES = "DiscretizedLociRates"; - public final String NORMALIZE = "normalize"; - public final String NORMALIZE_MEAN_LOCI_RATE_TO = "normalizeMeanLociRateTo"; - public final String RATE_CATEGORIES = "rateCategories"; - public final String CATEGORY_COUNT = "categoryCount"; - public final String LOCI_RATES = "lociRates"; - public final String DISTRIBUTION = "distribution"; - - - - public String getParserName(){ - return DISCRETIZED_LOCI_RATES; - } - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - - final boolean normalize = xo.getAttribute(NORMALIZE, false); - final double normalizeBranchRateTo = xo.getAttribute(NORMALIZE_MEAN_LOCI_RATE_TO, Double.NaN); - final int categoryCount = xo.getIntegerAttribute(CATEGORY_COUNT); - - CompoundParameter lociRates = (CompoundParameter) xo.getElementFirstChild(LOCI_RATES); - Parameter rateCategoryParameter = (Parameter) xo.getElementFirstChild(RATE_CATEGORIES); - ParametricDistributionModel distributionModel = (ParametricDistributionModel) xo.getElementFirstChild(DISTRIBUTION); - - - - Logger.getLogger("dr.evomodel").info("Using discretized loci rates model."); - Logger.getLogger("dr.evomodel").info("Number of categories: "+categoryCount); - Logger.getLogger("dr.evomodel").info(" parametric model = " + distributionModel.getModelName()); - if(normalize) { - Logger.getLogger("dr.evomodel").info(" mean rate is normalized to " + normalizeBranchRateTo); - } - - - return new DiscretizedLociRates( - lociRates, - rateCategoryParameter, - distributionModel, - normalize, - normalizeBranchRateTo, - categoryCount); - } - - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - - public String getParserDescription() { - return - "This element returns an discretized loci rate model." + - "The loci rates are drawn from a discretized parametric distribution."; - } - - public Class getReturnType() { - return DiscretizedBranchRates.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private final XMLSyntaxRule[] rules = { - AttributeRule.newBooleanRule(NORMALIZE, true, "Whether the mean rate has to be normalized to a particular value"), - AttributeRule.newDoubleRule(NORMALIZE_MEAN_LOCI_RATE_TO, true, "The mean rate to normalize to, if normalizing"), - AttributeRule.newIntegerRule(CATEGORY_COUNT, true, "The number of categories that the distribution will be divided into"), - new ElementRule(LOCI_RATES, CompoundParameter.class, "The compound parameter that contains all the loci rate parameters", false), - new ElementRule(DISTRIBUTION, ParametricDistributionModel.class, "The distribution model for rates among branches", false), - new ElementRule(RATE_CATEGORIES, Parameter.class, "The rate categories parameter", false), - }; -} diff --git a/src/dr/oldevomodelxml/sitemodel/GammaSiteBMAParser.java b/src/dr/oldevomodelxml/sitemodel/GammaSiteBMAParser.java deleted file mode 100644 index c895c99853..0000000000 --- a/src/dr/oldevomodelxml/sitemodel/GammaSiteBMAParser.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * GammaSiteBMAParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodelxml.sitemodel; - -import dr.xml.*; -import dr.oldevomodel.sitemodel.GammaSiteBMA; -import dr.oldevomodel.substmodel.SubstitutionModel; -import dr.inference.model.Parameter; -import dr.inference.model.Variable; - -/** - * @author Chieh-Hsi Wu - * - * Parser for Gamma site BMA. - * - */ -public class GammaSiteBMAParser extends AbstractXMLObjectParser { - - public static final String SUBSTITUTION_MODEL = "substitutionModel"; - public static final String MUTATION_RATE = "mutationRate"; - public static final String LOG_GAMMA_SHAPE = "logGammaShape"; - public static final String GAMMA_CATEGORIES = "gammaCategories"; - public static final String LOGIT_PROPORTION_INVARIANT = "logitProportionInvariant"; - public static final String MODEL_CHOOSE = "modelChoose"; - public static final String GAMMA_SITE_BMA = "gammaSiteBMA"; - - public String getParserName() { - return GAMMA_SITE_BMA; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - SubstitutionModel substitutionModel = (SubstitutionModel) xo.getElementFirstChild(SUBSTITUTION_MODEL); - - Parameter muParam = (Parameter) xo.getElementFirstChild(MUTATION_RATE); - - Parameter logitInvar = (Parameter) xo.getElementFirstChild(LOGIT_PROPORTION_INVARIANT); - - final XMLObject cxo = xo.getChild(LOG_GAMMA_SHAPE); - Parameter logShape = (Parameter) cxo.getChild(Parameter.class); - - int catCount = cxo.getIntegerAttribute(GAMMA_CATEGORIES); - - Variable modelChoose = (Variable) xo.getElementFirstChild(MODEL_CHOOSE); - - return new GammaSiteBMA(substitutionModel, muParam, logitInvar, logShape, catCount, modelChoose); - } - - public String getParserDescription() { - return "A SiteModel that does BMA for a gamma distributed rates across sites"; - } - - public Class getReturnType() { - return GammaSiteBMA.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private final XMLSyntaxRule[] rules = { - new ElementRule(SUBSTITUTION_MODEL, new XMLSyntaxRule[]{ - new ElementRule(SubstitutionModel.class) - }), - new ElementRule(MUTATION_RATE, new XMLSyntaxRule[]{ - new ElementRule(Parameter.class) - }), - new ElementRule(LOG_GAMMA_SHAPE, new XMLSyntaxRule[]{ - AttributeRule.newIntegerRule(GAMMA_CATEGORIES), - new ElementRule(Parameter.class) - }), - new ElementRule(LOGIT_PROPORTION_INVARIANT, new XMLSyntaxRule[]{ - new ElementRule(Parameter.class) - }), - new ElementRule(MODEL_CHOOSE, new XMLSyntaxRule[]{ - new ElementRule(Variable.class) - }) - }; - -} diff --git a/src/dr/oldevomodelxml/sitemodel/GammaSiteModelParser.java b/src/dr/oldevomodelxml/sitemodel/GammaSiteModelParser.java deleted file mode 100644 index 527a86b793..0000000000 --- a/src/dr/oldevomodelxml/sitemodel/GammaSiteModelParser.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * GammaSiteModelParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodelxml.sitemodel; - -import dr.oldevomodel.sitemodel.GammaSiteModel; -import dr.oldevomodel.sitemodel.SiteModel; -import dr.oldevomodel.substmodel.SubstitutionModel; -import dr.inference.model.Parameter; -import dr.xml.*; - -import java.util.logging.Logger; - -/** - */ -public class GammaSiteModelParser extends AbstractXMLObjectParser { - - public static final String SUBSTITUTION_MODEL = "substitutionModel"; - public static final String MUTATION_RATE = "mutationRate"; - public static final String SUBSTITUTION_RATE = "substitutionRate"; - public static final String RELATIVE_RATE = "relativeRate"; - public static final String GAMMA_SHAPE = "gammaShape"; - public static final String GAMMA_CATEGORIES = "gammaCategories"; - public static final String PROPORTION_INVARIANT = "proportionInvariant"; - - - public String[] getParserNames() { - return new String[]{ - getParserName(), "beast_" + getParserName() - }; - } - - public String getParserName() { - return SiteModel.SITE_MODEL; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - SubstitutionModel substitutionModel = (SubstitutionModel) xo.getElementFirstChild(SUBSTITUTION_MODEL); - - String msg = ""; - - Parameter muParam = null; - if (xo.hasChildNamed(SUBSTITUTION_RATE)) { - muParam = (Parameter) xo.getElementFirstChild(SUBSTITUTION_RATE); - - msg += "\n with initial substitution rate = " + muParam.getParameterValue(0); - } else if (xo.hasChildNamed(MUTATION_RATE)) { - muParam = (Parameter) xo.getElementFirstChild(MUTATION_RATE); - - msg += "\n with initial substitution rate = " + muParam.getParameterValue(0); - } else if (xo.hasChildNamed(RELATIVE_RATE)) { - muParam = (Parameter) xo.getElementFirstChild(RELATIVE_RATE); - - msg += "\n with initial relative rate = " + muParam.getParameterValue(0); - } - - Parameter shapeParam = null; - int catCount = 4; - if (xo.hasChildNamed(GAMMA_SHAPE)) { - final XMLObject cxo = xo.getChild(GAMMA_SHAPE); - catCount = cxo.getIntegerAttribute(GAMMA_CATEGORIES); - shapeParam = (Parameter) cxo.getChild(Parameter.class); - - msg += "\n " + catCount + " category discrete gamma with initial shape = " + shapeParam.getParameterValue(0); - } - - Parameter invarParam = null; - if (xo.hasChildNamed(PROPORTION_INVARIANT)) { - invarParam = (Parameter) xo.getElementFirstChild(PROPORTION_INVARIANT); - msg += "\n initial proportion of invariant sites = " + invarParam.getParameterValue(0); - } - - Logger.getLogger("dr.evomodel").info("Creating site model." + (msg.length() > 0 ? msg : "")); - - return new GammaSiteModel(substitutionModel, muParam, shapeParam, catCount, invarParam); - } - - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - - public String getParserDescription() { - return "A SiteModel that has a gamma distributed rates across sites"; - } - - public Class getReturnType() { - return GammaSiteModel.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private final XMLSyntaxRule[] rules = { - new ElementRule(SUBSTITUTION_MODEL, new XMLSyntaxRule[]{ - new ElementRule(SubstitutionModel.class) - }), - new XORRule( - new XORRule( - new ElementRule(SUBSTITUTION_RATE, new XMLSyntaxRule[]{ - new ElementRule(Parameter.class) - }), - new ElementRule(MUTATION_RATE, new XMLSyntaxRule[]{ - new ElementRule(Parameter.class) - }) - ), - new ElementRule(RELATIVE_RATE, new XMLSyntaxRule[]{ - new ElementRule(Parameter.class) - }), true - ), - new ElementRule(GAMMA_SHAPE, new XMLSyntaxRule[]{ - AttributeRule.newIntegerRule(GAMMA_CATEGORIES, true), - new ElementRule(Parameter.class) - }, true), - new ElementRule(PROPORTION_INVARIANT, new XMLSyntaxRule[]{ - new ElementRule(Parameter.class) - }, true) - }; -} diff --git a/src/dr/oldevomodelxml/sitemodel/SampleQuantileLociRatesParser.java b/src/dr/oldevomodelxml/sitemodel/SampleQuantileLociRatesParser.java deleted file mode 100644 index bcf15bad38..0000000000 --- a/src/dr/oldevomodelxml/sitemodel/SampleQuantileLociRatesParser.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * SampleQuantileLociRatesParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodelxml.sitemodel; - -import dr.xml.*; -import dr.inference.model.CompoundParameter; -import dr.inference.model.Parameter; -import dr.inference.distribution.ParametricDistributionModel; -import dr.oldevomodel.sitemodel.SampleQuantileLociRates; -import dr.evomodel.branchratemodel.DiscretizedBranchRates; - -import java.util.logging.Logger; - -/** - * @author Chieh-Hsi Wu - * Parser of SampleQuantileLociRates - */ -public class SampleQuantileLociRatesParser extends AbstractXMLObjectParser{ - public static final String SAMPLE_QUANTILE_LOCI_RATES = "SampleQuantileLociRates"; - public static final String NORMALIZE = "normalize"; - public static final String NORMALIZE_MEAN_LOCI_RATE_TO = "normalizeMeanLociRateTo"; - public static final String RATE_QUANTILES = "rateQuantiles"; - public static final String LOCI_RATES = "lociRates"; - public static final String DISTRIBUTION = "distribution"; - - - - public String getParserName(){ - return SAMPLE_QUANTILE_LOCI_RATES; - } - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - - final boolean normalize = xo.getAttribute(NORMALIZE, false); - final double normalizeBranchRateTo = xo.getAttribute(NORMALIZE_MEAN_LOCI_RATE_TO, Double.NaN); - - CompoundParameter lociRates = (CompoundParameter) xo.getElementFirstChild(LOCI_RATES); - Parameter rateQuantilesParameter = (Parameter) xo.getElementFirstChild(RATE_QUANTILES); - ParametricDistributionModel distributionModel = (ParametricDistributionModel) xo.getElementFirstChild(DISTRIBUTION); - - - - Logger.getLogger("dr.evomodel").info("Using sample quantile loci rates model."); - Logger.getLogger("dr.evomodel").info(" parametric model = " + distributionModel.getModelName()); - if(normalize) { - Logger.getLogger("dr.evomodel").info(" mean rate is normalized to " + normalizeBranchRateTo); - } - - - return new SampleQuantileLociRates( - lociRates, - rateQuantilesParameter, - distributionModel, - normalize, - normalizeBranchRateTo); - } - - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - - public String getParserDescription() { - return - "This element returns an discretized loci rate model." + - "The loci rates are drawn from a discretized parametric distribution."; - } - - public Class getReturnType() { - return DiscretizedBranchRates.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private final XMLSyntaxRule[] rules = { - AttributeRule.newBooleanRule(NORMALIZE, true, "Whether the mean rate has to be normalized to a particular value"), - AttributeRule.newDoubleRule(NORMALIZE_MEAN_LOCI_RATE_TO, true, "The mean rate to normalize to, if normalizing"), - new ElementRule(LOCI_RATES, CompoundParameter.class, "The compound parameter that contains all the loci rate parameters", false), - new ElementRule(DISTRIBUTION, ParametricDistributionModel.class, "The distribution model for rates among branches", false), - new ElementRule(RATE_QUANTILES, Parameter.class, "The rate quantiles parameter", false), - }; - -} diff --git a/src/dr/oldevomodelxml/sitemodel/SampleStateAndCategoryModelParser.java b/src/dr/oldevomodelxml/sitemodel/SampleStateAndCategoryModelParser.java deleted file mode 100644 index f471c84d20..0000000000 --- a/src/dr/oldevomodelxml/sitemodel/SampleStateAndCategoryModelParser.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * SampleStateAndCategoryModelParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodelxml.sitemodel; - -import dr.oldevomodel.sitemodel.SampleStateAndCategoryModel; -import dr.oldevomodel.substmodel.SubstitutionModel; -import dr.inference.model.Parameter; -import dr.xml.*; - -import java.util.Vector; - -/** - * - */ -public class SampleStateAndCategoryModelParser extends AbstractXMLObjectParser { - - public static final String SAMPLE_STATE_AND_CATEGORY_MODEL = "sampleStateAndCategoryModel"; - public static final String MUTATION_RATE = "mutationRate"; - public static final String CATEGORY_PARAMETER = "categoriesParameter"; - - public String getParserName() { - return SAMPLE_STATE_AND_CATEGORY_MODEL; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - XMLObject cxo = xo.getChild(MUTATION_RATE); - Parameter muParam = (Parameter) cxo.getChild(Parameter.class); - - cxo = xo.getChild(CATEGORY_PARAMETER); - Parameter catParam = (Parameter) cxo.getChild(Parameter.class); - - Vector subModels = new Vector(); - for (int i = 0; i < xo.getChildCount(); i++) { - - if (xo.getChild(i) instanceof SubstitutionModel) { - subModels.addElement(xo.getChild(i)); - } - - } - - return new SampleStateAndCategoryModel(muParam, catParam, subModels); - - } - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - - public String getParserDescription() { - return "A SiteModel that has a discrete distribution of substitution models over sites, " + - "designed for sampling of rate categories and internal states."; - } - - public Class getReturnType() { - return SampleStateAndCategoryModel.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private final XMLSyntaxRule[] rules = { - new ElementRule(MUTATION_RATE, - new XMLSyntaxRule[]{new ElementRule(Parameter.class)}), - new ElementRule(CATEGORY_PARAMETER, - new XMLSyntaxRule[]{new ElementRule(Parameter.class)}), - new ElementRule(SubstitutionModel.class, 1, Integer.MAX_VALUE) - }; - -} diff --git a/src/dr/oldevomodelxml/sitemodel/SampleStateModelParser.java b/src/dr/oldevomodelxml/sitemodel/SampleStateModelParser.java deleted file mode 100644 index 7b9d92b19a..0000000000 --- a/src/dr/oldevomodelxml/sitemodel/SampleStateModelParser.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * SampleStateModelParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodelxml.sitemodel; - -import dr.oldevomodel.sitemodel.SampleStateModel; -import dr.oldevomodel.substmodel.SubstitutionModel; -import dr.inference.model.Parameter; -import dr.xml.*; - -import java.util.Vector; - -/** - */ -public class SampleStateModelParser extends AbstractXMLObjectParser { - - public static final String SAMPLE_STATE_MODEL = "sampleStateModel"; - public static final String MUTATION_RATE = "mutationRate"; - public static final String PROPORTIONS = "proportions"; - - public String getParserName() { - return SAMPLE_STATE_MODEL; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - XMLObject cxo = xo.getChild(MUTATION_RATE); - Parameter muParam = (Parameter) cxo.getChild(Parameter.class); - - cxo = xo.getChild(PROPORTIONS); - Parameter proportionParameter = (Parameter) cxo.getChild(Parameter.class); - - Vector subModels = new Vector(); - - for (int i = 0; i < xo.getChildCount(); i++) { - if (xo.getChild(i) instanceof SubstitutionModel) { - subModels.addElement(xo.getChild(i)); - } - } - - return new SampleStateModel(muParam, proportionParameter, subModels); - } - - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - - public String getParserDescription() { - return "A SiteModel that has a discrete distribution of substitution models over sites, " + - "designed for sampling of internal states."; - } - - public Class getReturnType() { - return SampleStateModel.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private final XMLSyntaxRule[] rules = { - new ElementRule(MUTATION_RATE, - new XMLSyntaxRule[]{new ElementRule(Parameter.class)}), - new ElementRule(PROPORTIONS, - new XMLSyntaxRule[]{new ElementRule(Parameter.class)}), - new ElementRule(SubstitutionModel.class, 1, Integer.MAX_VALUE) - }; -} diff --git a/src/dr/oldevomodelxml/substmodel/AsymQuadModelParser.java b/src/dr/oldevomodelxml/substmodel/AsymQuadModelParser.java deleted file mode 100644 index e42f9a7376..0000000000 --- a/src/dr/oldevomodelxml/substmodel/AsymQuadModelParser.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * AsymQuadModelParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodelxml.substmodel; - -import dr.evolution.datatype.Microsatellite; -import dr.inference.model.ParameterParser; -import dr.oldevomodel.substmodel.AsymmetricQuadraticModel; -import dr.oldevomodel.substmodel.FrequencyModel; -import dr.inference.model.Parameter; -import dr.xml.*; - -/** - * @author Chieh-Hsi Wu - * - * Parser for Asymmetric Quadratic Model - */ -public class AsymQuadModelParser extends AbstractXMLObjectParser{ - - public static final String EXPANSION_CONSTANT = "ExpansionConstant"; - public static final String CONTRACTION_CONSTANT = "ContractionConstant"; - public static final String EXPANSION_LIN = "ExpansionLinear"; - public static final String CONTRACTION_LIN = "ContractionLinear"; - public static final String EXPANSION_QUAD = "ExpansionQuad"; - public static final String CONTRACTION_QUAD = "ContractionQuad"; - public static final String IS_SUBMODEL = "isSubmodel"; - - public String getParserName() { - return AsymmetricQuadraticModel.ASYMQUAD_MODEL; - } - - - //AbstractXMLObjectParser implementation - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - Microsatellite microsatellite = (Microsatellite) xo.getChild(Microsatellite.class); - - Parameter expanConst = processModelParameter(xo, EXPANSION_CONSTANT); - - Parameter expanLin = processModelParameter(xo, EXPANSION_LIN); - - Parameter expanQuad = processModelParameter(xo, EXPANSION_QUAD); - - Parameter contractConst = processModelParameter(xo, CONTRACTION_CONSTANT); - - Parameter contractLin = processModelParameter(xo, CONTRACTION_LIN); - - Parameter contractQuad = processModelParameter(xo, CONTRACTION_QUAD); - - //get FrequencyModel - FrequencyModel freqModel = null; - if(xo.hasChildNamed(FrequencyModelParser.FREQUENCIES)){ - freqModel = (FrequencyModel)xo.getElementFirstChild(FrequencyModelParser.FREQUENCIES); - } - - boolean isSubmodel = xo.getAttribute(IS_SUBMODEL, false); - - return new AsymmetricQuadraticModel( - microsatellite, - freqModel, - expanConst, - expanLin, - expanQuad, - contractConst, - contractLin, - contractQuad, - isSubmodel - ); - } - - private Parameter processModelParameter(XMLObject xo, - String parameterName)throws XMLParseException{ - return ParameterParser.getOptionalParameter(xo, parameterName); - } - - public String getParserDescription() { - return "This element represents an instance of the stepwise mutation model of microsatellite evolution."; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{ - new ElementRule(Microsatellite.class), - new ElementRule(FrequencyModel.class,true), - new ElementRule(EXPANSION_CONSTANT,new XMLSyntaxRule[]{new ElementRule(Parameter.class)},true), - new ElementRule(CONTRACTION_CONSTANT,new XMLSyntaxRule[]{new ElementRule(Parameter.class)},true), - new ElementRule(EXPANSION_LIN,new XMLSyntaxRule[]{new ElementRule(Parameter.class)},true), - new ElementRule(CONTRACTION_LIN,new XMLSyntaxRule[]{new ElementRule(Parameter.class)},true), - new ElementRule(EXPANSION_QUAD,new XMLSyntaxRule[]{new ElementRule(Parameter.class)},true), - new ElementRule(CONTRACTION_QUAD,new XMLSyntaxRule[]{new ElementRule(Parameter.class)},true), - AttributeRule.newBooleanRule(IS_SUBMODEL,true) - }; - - public Class getReturnType() { - return AsymmetricQuadraticModel.class; - } - - public static boolean requirePattern(){ - return true; - } -} - diff --git a/src/dr/oldevomodelxml/substmodel/BinaryCovarionModelParser.java b/src/dr/oldevomodelxml/substmodel/BinaryCovarionModelParser.java deleted file mode 100644 index a1a10d93c7..0000000000 --- a/src/dr/oldevomodelxml/substmodel/BinaryCovarionModelParser.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * BinaryCovarionModelParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodelxml.substmodel; - -import dr.evolution.datatype.TwoStateCovarion; -import dr.oldevomodel.substmodel.BinaryCovarionModel; -import dr.inference.model.Parameter; -import dr.xml.*; - -/** - * Parses an element from an DOM document into a TwoStateCovarionModel - */ -public class BinaryCovarionModelParser extends AbstractXMLObjectParser { - public static final String COVARION_MODEL = "binaryCovarionModel"; - public static final String ALPHA = "alpha"; - public static final String SWITCHING_RATE = "switchingRate"; - public static final String FREQUENCIES = "frequencies"; - public static final String HIDDEN_FREQUENCIES = "hiddenFrequencies"; - public static final String VERSION = "version"; - public static final BinaryCovarionModel.Version DEFAULT_VERSION = BinaryCovarionModel.Version.VERSION1; - - public String getParserName() { - return COVARION_MODEL; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - Parameter alphaParameter; - Parameter switchingRateParameter; - - XMLObject cxo = xo.getChild(FREQUENCIES); - Parameter frequencies = (Parameter) cxo.getChild(Parameter.class); - - cxo = xo.getChild(HIDDEN_FREQUENCIES); - Parameter hiddenFrequencies = (Parameter) cxo.getChild(Parameter.class); - - cxo = xo.getChild(ALPHA); - alphaParameter = (Parameter) cxo.getChild(Parameter.class); - - // alpha must be positive and less than 1.0 because the fast rate is normalized to 1.0 - alphaParameter.addBounds(new Parameter.DefaultBounds(1.0, 0.0, 1)); - hiddenFrequencies.addBounds(new Parameter.DefaultBounds(1.0, 0.0, hiddenFrequencies.getDimension())); - frequencies.addBounds(new Parameter.DefaultBounds(1.0, 0.0, frequencies.getDimension())); - - cxo = xo.getChild(SWITCHING_RATE); - switchingRateParameter = (Parameter) cxo.getChild(Parameter.class); - - BinaryCovarionModel.Version version = DEFAULT_VERSION; - if (xo.hasAttribute(VERSION)) { - version = BinaryCovarionModel.Version.parseFromString(xo.getStringAttribute(VERSION)); - } - - BinaryCovarionModel model = new BinaryCovarionModel(TwoStateCovarion.INSTANCE, - frequencies, hiddenFrequencies, alphaParameter, switchingRateParameter, version); - - System.out.println(model); - - return model; - } - - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - - public String getParserDescription() { - return "A covarion substitution model on binary data and a hidden rate state with two rates."; - } - - public Class getReturnType() { - return BinaryCovarionModel.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private final XMLSyntaxRule[] rules = { - new ElementRule(FREQUENCIES, Parameter.class), - new ElementRule(HIDDEN_FREQUENCIES, Parameter.class), - new ElementRule(ALPHA, - new XMLSyntaxRule[]{ - new ElementRule(Parameter.class, true)} - ), - new ElementRule(SWITCHING_RATE, - new XMLSyntaxRule[]{ - new ElementRule(Parameter.class, true)} - ), - AttributeRule.newStringRule(VERSION, true), - }; - - -} diff --git a/src/dr/oldevomodelxml/substmodel/BinarySubstitutionModelParser.java b/src/dr/oldevomodelxml/substmodel/BinarySubstitutionModelParser.java deleted file mode 100644 index 531b4ac9c6..0000000000 --- a/src/dr/oldevomodelxml/substmodel/BinarySubstitutionModelParser.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * BinarySubstitutionModelParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodelxml.substmodel; - -import dr.evolution.datatype.DataType; -import dr.evolution.datatype.TwoStates; -import dr.oldevomodel.substmodel.FrequencyModel; -import dr.oldevomodel.substmodel.GeneralSubstitutionModel; -import dr.inference.model.Parameter; -import dr.xml.*; - -/** - * @author Michael Defoin Platel - */ -public class BinarySubstitutionModelParser extends AbstractXMLObjectParser { - - public static final String BINARY_SUBSTITUTION_MODEL = "binarySubstitutionModel"; - - public String getParserName() { - return BINARY_SUBSTITUTION_MODEL; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - Parameter ratesParameter; - - XMLObject cxo = xo.getChild(GeneralSubstitutionModelParser.FREQUENCIES); - FrequencyModel freqModel = (FrequencyModel) cxo.getChild(FrequencyModel.class); - - DataType dataType = freqModel.getDataType(); - - if (dataType != TwoStates.INSTANCE) - throw new XMLParseException("Frequency model must have binary (two state) data type."); - - int relativeTo = 0; - - ratesParameter = new Parameter.Default(0); - - return new GeneralSubstitutionModel(dataType, freqModel, ratesParameter, relativeTo); - } - - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - - public String getParserDescription() { - return "A general reversible model of sequence substitution for binary data type."; - } - - public Class getReturnType() { - return GeneralSubstitutionModel.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{ - new ElementRule(GeneralSubstitutionModelParser.FREQUENCIES, FrequencyModel.class), - }; - -} diff --git a/src/dr/oldevomodelxml/substmodel/ComplexSubstitutionModelParser.java b/src/dr/oldevomodelxml/substmodel/ComplexSubstitutionModelParser.java deleted file mode 100644 index b1daff2a52..0000000000 --- a/src/dr/oldevomodelxml/substmodel/ComplexSubstitutionModelParser.java +++ /dev/null @@ -1,187 +0,0 @@ -/* - * ComplexSubstitutionModelParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodelxml.substmodel; - -import dr.evolution.datatype.DataType; -import dr.oldevomodel.substmodel.ComplexSubstitutionModel; -import dr.oldevomodel.substmodel.FrequencyModel; -import dr.oldevomodel.substmodel.SVSComplexSubstitutionModel; -import dr.evoxml.util.DataTypeUtils; -import dr.inference.model.BayesianStochasticSearchVariableSelection; -import dr.inference.model.Parameter; -import dr.xml.*; - -import java.util.logging.Logger; - -/** - */ -public class ComplexSubstitutionModelParser extends AbstractXMLObjectParser { - - public static final String COMPLEX_SUBSTITUTION_MODEL = "complexSubstitutionModel"; - public static final String RATES = "rates"; - public static final String ROOT_FREQUENCIES = "rootFrequencies"; - public static final String INDICATOR = "rateIndicator"; - public static final String RANDOMIZE = "randomizeIndicator"; - public static final String NORMALIZATION = "normalize"; - public static final String MAX_CONDITION_NUMBER = "maxConditionNumber"; - public static final String CONNECTED = "mustBeConnected"; - public static final String MAX_ITERATIONS = "maxIterations"; - public static final String CHECK_CONDITIONING = "checkConditioning"; - - public String[] getParserNames() { - return new String[]{ - getParserName(), "beast_" + getParserName() - }; - } - - public String getParserName() { - return COMPLEX_SUBSTITUTION_MODEL; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - DataType dataType = DataTypeUtils.getDataType(xo); - - if (dataType == null) dataType = (DataType) xo.getChild(DataType.class); - - XMLObject cxo = xo.getChild(RATES); - - Parameter ratesParameter = (Parameter) cxo.getChild(Parameter.class); - - int rateCount = (dataType.getStateCount() - 1) * dataType.getStateCount(); - - if (ratesParameter.getDimension() != rateCount) { - throw new XMLParseException("Rates parameter in " + getParserName() + " element should have " + (rateCount) - + " dimensions. However parameter dimension is " + ratesParameter.getDimension()); - } - - - cxo = xo.getChild(ROOT_FREQUENCIES); - FrequencyModel rootFreq = (FrequencyModel) cxo.getChild(FrequencyModel.class); - - if (dataType != rootFreq.getDataType()) { - throw new XMLParseException("Data type of " + getParserName() + " element does not match that of its rootFrequencyModel."); - } - - Parameter indicators = null; - - if (xo.hasChildNamed(INDICATOR)) { - indicators = (Parameter) ((XMLObject) xo.getChild(INDICATOR)).getChild(Parameter.class); - if (ratesParameter.getDimension() != indicators.getDimension()) - throw new XMLParseException("Rate parameter dimension must match indicator parameter dimension"); - } - - StringBuffer sb = new StringBuffer().append("Constructing a complex substitution model using\n") - .append("\tRate parameters: ").append(ratesParameter.getId()) - .append("\n").append("\tRoot frequency model: ").append(rootFreq.getId()).append("\n"); - - ComplexSubstitutionModel model; - - if (indicators == null) - model = new ComplexSubstitutionModel(xo.getId(), dataType, rootFreq, ratesParameter); - else { - - boolean randomize = xo.getAttribute(RANDOMIZE, false); - boolean connected = xo.getAttribute(CONNECTED, false); - model = new SVSComplexSubstitutionModel(xo.getId(), dataType, rootFreq, ratesParameter, indicators); - if (randomize) { - BayesianStochasticSearchVariableSelection.Utils.randomize(indicators, - dataType.getStateCount(), false); - - boolean valid = !Double.isInfinite(model.getLogLikelihood()); - if (!valid) { - throw new XMLParseException("Poor tolerance in complex substitution model. Please retry analysis using BEAGLE"); - } - } - sb.append("\tBSSVS indicators: ").append(indicators.getId()).append("\n"); - sb.append("\tGraph must be connected: ").append(connected).append("\n"); - } - - boolean doNormalization = xo.getAttribute(NORMALIZATION, true); - model.setNormalization(doNormalization); - sb.append("\tNormalized: ").append(doNormalization).append("\n"); - - boolean checkConditioning = xo.getAttribute(CHECK_CONDITIONING, true); - model.setCheckConditioning(checkConditioning); - - if (checkConditioning) { - double maxConditionNumber = xo.getAttribute(MAX_CONDITION_NUMBER, 1000); - model.setMaxConditionNumber(maxConditionNumber); - sb.append("\tMax. condition number: ").append(maxConditionNumber).append("\n"); - } - - int maxIterations = xo.getAttribute(MAX_ITERATIONS, 1000); - model.setMaxIterations(maxIterations); - sb.append("\tMax iterations: ").append(maxIterations).append("\n"); - - sb.append("\t\tPlease cite Edwards, Suchard et al. (2011)\n"); - - Logger.getLogger("dr.evomodel.substmodel").info(sb.toString()); - return model; - } - - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - - public String getParserDescription() { - return "A general reversible model of sequence substitution for any data type with stochastic variable selection."; - } - - public Class getReturnType() { - return ComplexSubstitutionModelParser.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private final XMLSyntaxRule[] rules = { - new XORRule( - new StringAttributeRule(DataType.DATA_TYPE, "The type of sequence data", - DataType.getRegisteredDataTypeNames(), false), - new ElementRule(DataType.class) - ), - AttributeRule.newBooleanRule(RANDOMIZE, true), - new ElementRule(ROOT_FREQUENCIES, FrequencyModel.class), - new ElementRule(RATES, - new XMLSyntaxRule[]{ - new ElementRule(Parameter.class)} - ), - new ElementRule(INDICATOR, - new XMLSyntaxRule[]{ - new ElementRule(Parameter.class) - }, true), - AttributeRule.newBooleanRule(NORMALIZATION, true), - AttributeRule.newDoubleRule(MAX_CONDITION_NUMBER, true), - AttributeRule.newBooleanRule(CONNECTED, true), - AttributeRule.newIntegerRule(MAX_ITERATIONS, true), - AttributeRule.newBooleanRule(CHECK_CONDITIONING, true), - }; - -} diff --git a/src/dr/oldevomodelxml/substmodel/CovarionGTRParser.java b/src/dr/oldevomodelxml/substmodel/CovarionGTRParser.java deleted file mode 100644 index 9f00f3d773..0000000000 --- a/src/dr/oldevomodelxml/substmodel/CovarionGTRParser.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * CovarionGTRParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodelxml.substmodel; - -import dr.evolution.datatype.OldHiddenNucleotides; -import dr.oldevomodel.substmodel.AbstractCovarionDNAModel; -import dr.oldevomodel.substmodel.CovarionGTR; -import dr.oldevomodel.substmodel.FrequencyModel; -import dr.inference.model.Parameter; -import dr.xml.*; - -/** - * Parses an element from an DOM document into a TwoStateCovarionModel - */ -public class CovarionGTRParser extends AbstractXMLObjectParser { - public static final String GTR_COVARION_MODEL = "gtrCovarionModel"; - - public String getParserName() { - return GTR_COVARION_MODEL; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - XMLObject cxo = xo.getChild(AbstractCovarionDNAModel.FREQUENCIES); - FrequencyModel freqModel = (FrequencyModel) cxo.getChild(FrequencyModel.class); - - OldHiddenNucleotides dataType = (OldHiddenNucleotides) freqModel.getDataType(); - - Parameter hiddenRates = (Parameter) xo.getElementFirstChild(AbstractCovarionDNAModel.HIDDEN_CLASS_RATES); - Parameter switchingRates = (Parameter) xo.getElementFirstChild(AbstractCovarionDNAModel.SWITCHING_RATES); - - Parameter rateACParameter = null; - if (xo.hasChildNamed(GTRParser.A_TO_C)) { - rateACParameter = (Parameter) xo.getElementFirstChild(GTRParser.A_TO_C); - } - Parameter rateAGParameter = null; - if (xo.hasChildNamed(GTRParser.A_TO_G)) { - rateAGParameter = (Parameter) xo.getElementFirstChild(GTRParser.A_TO_G); - } - Parameter rateATParameter = null; - if (xo.hasChildNamed(GTRParser.A_TO_T)) { - rateATParameter = (Parameter) xo.getElementFirstChild(GTRParser.A_TO_T); - } - Parameter rateCGParameter = null; - if (xo.hasChildNamed(GTRParser.C_TO_G)) { - rateCGParameter = (Parameter) xo.getElementFirstChild(GTRParser.C_TO_G); - } - Parameter rateCTParameter = null; - if (xo.hasChildNamed(GTRParser.C_TO_T)) { - rateCTParameter = (Parameter) xo.getElementFirstChild(GTRParser.C_TO_T); - } - Parameter rateGTParameter = null; - if (xo.hasChildNamed(GTRParser.G_TO_T)) { - rateGTParameter = (Parameter) xo.getElementFirstChild(GTRParser.G_TO_T); - } - - - if (dataType != freqModel.getDataType()) { - throw new XMLParseException("Data type of " + getParserName() + " element does not match that of its frequencyModel."); - } - - return new CovarionGTR( - dataType, - hiddenRates, - switchingRates, - rateACParameter, - rateAGParameter, - rateATParameter, - rateCGParameter, - rateCTParameter, - rateGTParameter, - freqModel); - } - - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - - public String getParserDescription() { - return "A covarion substitution model of langauge evolution with binary data and a hidden rate state with two rates."; - } - - public Class getReturnType() { - return CovarionGTR.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{ - new ElementRule(GTRParser.A_TO_C, Parameter.class, "relative rate of A<->C substitution", true), - new ElementRule(GTRParser.A_TO_G, Parameter.class, "relative rate of A<->G substitution", true), - new ElementRule(GTRParser.A_TO_T, Parameter.class, "relative rate of A<->T substitution", true), - new ElementRule(GTRParser.C_TO_G, Parameter.class, "relative rate of C<->G substitution", true), - new ElementRule(GTRParser.C_TO_T, Parameter.class, "relative rate of C<->T substitution", true), - new ElementRule(GTRParser.G_TO_T, Parameter.class, "relative rate of G<->T substitution", true), - new ElementRule(AbstractCovarionDNAModel.HIDDEN_CLASS_RATES, Parameter.class), - new ElementRule(AbstractCovarionDNAModel.SWITCHING_RATES, Parameter.class), - new ElementRule(AbstractCovarionDNAModel.FREQUENCIES, FrequencyModel.class), - }; - - - -} diff --git a/src/dr/oldevomodelxml/substmodel/CovarionHKYParser.java b/src/dr/oldevomodelxml/substmodel/CovarionHKYParser.java deleted file mode 100644 index 4874139416..0000000000 --- a/src/dr/oldevomodelxml/substmodel/CovarionHKYParser.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * CovarionHKYParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodelxml.substmodel; - -import dr.evolution.datatype.OldHiddenNucleotides; -import dr.oldevomodel.substmodel.AbstractCovarionDNAModel; -import dr.oldevomodel.substmodel.CovarionHKY; -import dr.oldevomodel.substmodel.FrequencyModel; -import dr.inference.model.Parameter; -import dr.xml.*; - -/** - * Parses an element from an DOM document into a DemographicModel. Recognises - * ConstantPopulation and ExponentialGrowth. - */ -public class CovarionHKYParser extends AbstractXMLObjectParser { - public static final String COVARION_HKY = "CovarionHKYModel"; - public static final String KAPPA = HKYParser.KAPPA; - - public String getParserName() { - return COVARION_HKY; - } - - public String getParserDescription() { - return "A covarion HKY model."; - } - - public Class getReturnType() { - return CovarionHKY.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{ - new ElementRule(KAPPA, new XMLSyntaxRule[]{ - new ElementRule(Parameter.class, - "A parameter representing the transition transversion bias")}), - new ElementRule(AbstractCovarionDNAModel.SWITCHING_RATES, new XMLSyntaxRule[]{ - new ElementRule(Parameter.class, - "A parameter representing the rate of change between the different classes")}), - new ElementRule(AbstractCovarionDNAModel.HIDDEN_CLASS_RATES, new XMLSyntaxRule[]{ - new ElementRule(Parameter.class, - "A parameter representing the rates of the hidden classes relative to the first hidden class.")}) - }; - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - Parameter kappaParam; - Parameter switchingRates; - Parameter hiddenClassRates; - FrequencyModel freqModel; - - kappaParam = (Parameter) xo.getElementFirstChild(KAPPA); - switchingRates = (Parameter) xo.getElementFirstChild(AbstractCovarionDNAModel.SWITCHING_RATES); - hiddenClassRates = (Parameter) xo.getElementFirstChild(AbstractCovarionDNAModel.HIDDEN_CLASS_RATES); - freqModel = (FrequencyModel) xo.getElementFirstChild(AbstractCovarionDNAModel.FREQUENCIES); - - if (!(freqModel.getDataType() instanceof OldHiddenNucleotides)) { - throw new IllegalArgumentException("Datatype must be hidden nucleotides!!"); - } - - OldHiddenNucleotides dataType = (OldHiddenNucleotides) freqModel.getDataType(); - - int hiddenStateCount = dataType.getHiddenClassCount(); - - int switchingRatesCount = hiddenStateCount * (hiddenStateCount - 1) / 2; - - if (switchingRates.getDimension() != switchingRatesCount) { - throw new IllegalArgumentException("switching rates parameter must have " + - switchingRatesCount + " dimensions, for " + hiddenStateCount + - " hidden categories"); - } - - CovarionHKY model = new CovarionHKY(dataType, kappaParam, hiddenClassRates, switchingRates, freqModel); - System.out.println(model); - return model; - } - -} diff --git a/src/dr/oldevomodelxml/substmodel/EmpiricalAminoAcidModelParser.java b/src/dr/oldevomodelxml/substmodel/EmpiricalAminoAcidModelParser.java deleted file mode 100644 index df77225f77..0000000000 --- a/src/dr/oldevomodelxml/substmodel/EmpiricalAminoAcidModelParser.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * EmpiricalAminoAcidModelParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodelxml.substmodel; - -import dr.evomodel.substmodel.*; -import dr.evomodel.substmodel.aminoacid.*; -import dr.xml.*; - -/** - * Parses an element from an DOM document into a DemographicModel. Recognises - * ConstantPopulation and ExponentialGrowth. - */ -public class EmpiricalAminoAcidModelParser extends AbstractXMLObjectParser { - - public static final String EMPIRICAL_AMINO_ACID_MODEL = "aminoAcidModel"; - public static final String FREQUENCIES = "frequencies"; - public static final String TYPE = "type"; - - - public String getParserName() { - return EMPIRICAL_AMINO_ACID_MODEL; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - FrequencyModel freqModel = null; - - if (xo.hasAttribute(FREQUENCIES)) { - XMLObject cxo = xo.getChild(FREQUENCIES); - freqModel = (FrequencyModel) cxo.getChild(FrequencyModel.class); - } - - EmpiricalRateMatrix rateMatrix = null; - - String type = xo.getStringAttribute(TYPE); - - if (type.equals(AminoAcidModelType.BLOSUM_62.getXMLName())) { - rateMatrix = Blosum62.INSTANCE; - } else if (type.equals(AminoAcidModelType.DAYHOFF.getXMLName())) { - rateMatrix = Dayhoff.INSTANCE; - } else if (type.equals(AminoAcidModelType.JTT.getXMLName())) { - rateMatrix = JTT.INSTANCE; - } else if (type.equals(AminoAcidModelType.MT_REV_24.getXMLName())) { - rateMatrix = MTREV.INSTANCE; - } else if (type.equals(AminoAcidModelType.CP_REV_45.getXMLName())) { - rateMatrix = CPREV.INSTANCE; - } else if (type.equals(AminoAcidModelType.WAG.getXMLName())) { - rateMatrix = WAG.INSTANCE; - } else if (type.equals(AminoAcidModelType.FLU.getXMLName())) { - rateMatrix = FLU.INSTANCE; - } else if (type.equals(AminoAcidModelType.LG.getXMLName())) { - rateMatrix = LG.INSTANCE; - } - - return new EmpiricalAminoAcidModel(rateMatrix, freqModel); - } - - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{ - new StringAttributeRule(TYPE, "The type of empirical amino-acid rate matrix", AminoAcidModelType.xmlNames(), false), - new ElementRule(FREQUENCIES, FrequencyModel.class, "If the frequencies are omitted than the empirical frequencies associated with the selected model are used.", true) - }; - - public String getParserDescription() { - return "An empirical amino acid substitution model."; - } - - public Class getReturnType() { - return EmpiricalAminoAcidModel.class; - } - - -} diff --git a/src/dr/oldevomodelxml/substmodel/EmpiricalCodonModelParser.java b/src/dr/oldevomodelxml/substmodel/EmpiricalCodonModelParser.java deleted file mode 100644 index 457ad9dd38..0000000000 --- a/src/dr/oldevomodelxml/substmodel/EmpiricalCodonModelParser.java +++ /dev/null @@ -1,194 +0,0 @@ -/* - * EmpiricalCodonModelParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodelxml.substmodel; - -import java.util.logging.Logger; - -import dr.evolution.datatype.Codons; -import dr.evolution.datatype.DataType; -import dr.evolution.datatype.GeneticCode; -import dr.evomodel.substmodel.*; -import dr.inference.model.Parameter; -import dr.oldevomodel.substmodel.EmpiricalCodonModel; -import dr.oldevomodel.substmodel.EmpiricalCodonRateMatrix; -import dr.oldevomodel.substmodel.FrequencyModel; -import dr.xml.*; - -/** - * XML parser for ECM - * - * @author Stefan Zoller - */ -public class EmpiricalCodonModelParser extends AbstractXMLObjectParser { - public static final String EMPIRICAL_CODON_MODEL = "empiricalCodonModel"; - public static final String EMPIRICAL_RATE_MATRIX = "empiricalRateMatrix"; - public static final String ECM_DATA_DIR = "ecmDataDir"; - public static final String ECM_DATA_MATRIX = "ecmRateFile"; - public static final String ECM_FREQ_MATRIX = "ecmFreqFile"; - public static final String OMEGA = "omega"; - public static final String KAPPATSTV = "kappaTsTv"; - public static final String MULTI_NT_CHANGE = "multiNtChange"; - public String getParserName() { return EMPIRICAL_CODON_MODEL; } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - Codons codons = Codons.UNIVERSAL; - if (xo.hasAttribute(GeneticCode.GENETIC_CODE)) { - String codeStr = xo.getStringAttribute(GeneticCode.GENETIC_CODE); - if (codeStr.equals(GeneticCode.UNIVERSAL.getName())) { - codons = Codons.UNIVERSAL; - } else if (codeStr.equals(GeneticCode.VERTEBRATE_MT.getName())) { - codons = Codons.VERTEBRATE_MT; - } else if (codeStr.equals(GeneticCode.YEAST.getName())) { - codons = Codons.YEAST; - } else if (codeStr.equals(GeneticCode.MOLD_PROTOZOAN_MT.getName())) { - codons = Codons.MOLD_PROTOZOAN_MT; - } else if (codeStr.equals(GeneticCode.INVERTEBRATE_MT.getName())) { - codons = Codons.INVERTEBRATE_MT; - } else if (codeStr.equals(GeneticCode.CILIATE.getName())) { - codons = Codons.CILIATE; - } else if (codeStr.equals(GeneticCode.ECHINODERM_MT.getName())) { - codons = Codons.ECHINODERM_MT; - } else if (codeStr.equals(GeneticCode.EUPLOTID_NUC.getName())) { - codons = Codons.EUPLOTID_NUC; - } else if (codeStr.equals(GeneticCode.BACTERIAL.getName())) { - codons = Codons.BACTERIAL; - } else if (codeStr.equals(GeneticCode.ALT_YEAST.getName())) { - codons = Codons.ALT_YEAST; - } else if (codeStr.equals(GeneticCode.ASCIDIAN_MT.getName())) { - codons = Codons.ASCIDIAN_MT; - } else if (codeStr.equals(GeneticCode.FLATWORM_MT.getName())) { - codons = Codons.FLATWORM_MT; - } else if (codeStr.equals(GeneticCode.BLEPHARISMA_NUC.getName())) { - codons = Codons.BLEPHARISMA_NUC; - } else if (codeStr.equals(GeneticCode.NO_STOPS.getName())) { - codons = Codons.NO_STOPS; - } - } - - Parameter omegaParam = (Parameter)xo.getElementFirstChild(OMEGA); - Parameter kappaParam = null; - Parameter mntParam = null; - if(xo.hasChildNamed(KAPPATSTV)) { - kappaParam = (Parameter)xo.getElementFirstChild(KAPPATSTV); - if(kappaParam.getDimension() != 2 && kappaParam.getDimension() != 9) { - throw new XMLParseException("If you use the kappa parameter, you need to enter exactly\n" + - "two values for ts and tv or nine values\n" + - "according to the Kosiol ECM+F+omega+9k model"); - } - } else { - mntParam = (Parameter)xo.getElementFirstChild(MULTI_NT_CHANGE); - } - - String dirString = xo.getStringAttribute(ECM_DATA_DIR); - String freqString = xo.getStringAttribute(ECM_FREQ_MATRIX); - String matString = xo.getStringAttribute(ECM_DATA_MATRIX); - - EmpiricalCodonRateMatrix rateMat = new EmpiricalCodonRateMatrix(EMPIRICAL_RATE_MATRIX, codons, - dirString, freqString, matString); - - // get frequencies from XML, from frequency csv file or estimate from data - FrequencyModel freqModel = null; - if (xo.getChild(FrequencyModel.class) != null) { - freqModel = (FrequencyModel)xo.getChild(FrequencyModel.class); - } else { - freqModel = createNewFreqModel(codons, rateMat); - } - - return new EmpiricalCodonModel(codons, omegaParam, kappaParam, mntParam, rateMat, freqModel); - } - - // creates new FrequencyModel from XML frequencies - private FrequencyModel createNewFreqModel(DataType codons, EmpiricalCodonRateMatrix type) throws XMLParseException { - double[] freqs = type.getFrequencies(); - double sum = 0; - for (int j = 0; j < freqs.length; j++) { - sum += freqs[j]; - } - - if (Math.abs(sum - 1.0) > 1e-8) { - throw new XMLParseException("Frequencies do not sum to 1 (they sum to " + sum + ")"); - } - - FrequencyModel fm = new FrequencyModel(codons, freqs); - - Logger.getLogger("dr.evomodel").info("Using frequencies from data file"); - - return fm; - } - - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - - public String getParserDescription() { - return "This element represents the empirical model of codon evolution."; - } - - public Class getReturnType() { return EmpiricalCodonModel.class; } - - public XMLSyntaxRule[] getSyntaxRules() { return rules; } - - private XMLSyntaxRule[] rules = new XMLSyntaxRule[] { - new StringAttributeRule(GeneticCode.GENETIC_CODE, - "The genetic code to use", - new String[] { - GeneticCode.UNIVERSAL.getName(), - GeneticCode.VERTEBRATE_MT.getName(), - GeneticCode.YEAST.getName(), - GeneticCode.MOLD_PROTOZOAN_MT.getName(), - GeneticCode.INVERTEBRATE_MT.getName(), - GeneticCode.CILIATE.getName(), - GeneticCode.ECHINODERM_MT.getName(), - GeneticCode.EUPLOTID_NUC.getName(), - GeneticCode.BACTERIAL.getName(), - GeneticCode.ALT_YEAST.getName(), - GeneticCode.ASCIDIAN_MT.getName(), - GeneticCode.FLATWORM_MT.getName(), - GeneticCode.BLEPHARISMA_NUC.getName(), - GeneticCode.NO_STOPS.getName()}, true), - new StringAttributeRule(ECM_DATA_DIR, - "The directory with the ECM data file", - "ecmdata", true), - new StringAttributeRule(ECM_DATA_MATRIX, - "The csv file with the ECM data matrix", - "matrix.csv", true), - new StringAttributeRule(ECM_FREQ_MATRIX, - "The csv file with the ECM frequency matrix", - "freqs.csv", true), - new ElementRule(OMEGA, - new XMLSyntaxRule[] { new ElementRule(Parameter.class) }), - new XORRule( - new ElementRule(KAPPATSTV, - new XMLSyntaxRule[] { new ElementRule(Parameter.class) }), - new ElementRule(MULTI_NT_CHANGE, - new XMLSyntaxRule[] { new ElementRule(Parameter.class) })), - new ElementRule(FrequencyModel.class, true) - }; -} - diff --git a/src/dr/oldevomodelxml/substmodel/FrequencyModelParser.java b/src/dr/oldevomodelxml/substmodel/FrequencyModelParser.java deleted file mode 100644 index fd66189798..0000000000 --- a/src/dr/oldevomodelxml/substmodel/FrequencyModelParser.java +++ /dev/null @@ -1,151 +0,0 @@ -/* - * FrequencyModelParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodelxml.substmodel; - -import dr.evolution.alignment.PatternList; -import dr.evolution.datatype.DataType; -import dr.oldevomodel.substmodel.FrequencyModel; -import dr.evoxml.util.DataTypeUtils; -import dr.inference.model.Parameter; -import dr.xml.*; - -import java.text.NumberFormat; -import java.util.logging.Logger; - -/** - * Reads a frequency model from an XMLObject. - */ -public class FrequencyModelParser extends AbstractXMLObjectParser { - public static final String FREQUENCIES = "frequencies"; - public static final String FREQUENCY_MODEL = "frequencyModel"; - public static final String NORMALIZE = "normalize"; - - - public String[] getParserNames() { - return new String[]{ - getParserName(), "beast_" + getParserName() - }; - } - - public String getParserName() { - return FREQUENCY_MODEL; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - DataType dataType = DataTypeUtils.getDataType(xo); - - Parameter freqsParam = (Parameter) xo.getElementFirstChild(FREQUENCIES); - double[] frequencies = null; - - for (int i = 0; i < xo.getChildCount(); i++) { - Object obj = xo.getChild(i); - if (obj instanceof PatternList) { - frequencies = ((PatternList) obj).getStateFrequencies(); - break; - } - } - - StringBuilder sb = new StringBuilder("Creating state frequencies model '" + freqsParam.getParameterName() + "': "); - if (frequencies != null) { - if (freqsParam.getDimension() != frequencies.length) { - throw new XMLParseException("dimension of frequency parameter and number of sequence states don't match!"); - } - for (int j = 0; j < frequencies.length; j++) { - freqsParam.setParameterValue(j, frequencies[j]); - } - sb.append("Using empirical frequencies from data "); - } else { - sb.append("Initial frequencies "); - } - sb.append("= {"); - - double sum = 0; - for (int j = 0; j < freqsParam.getDimension(); j++) { - sum += freqsParam.getParameterValue(j); - } - - if (xo.getAttribute(NORMALIZE, false)) { - for (int j = 0; j < freqsParam.getDimension(); j++) { - if (sum != 0) - freqsParam.setParameterValue(j, freqsParam.getParameterValue(j) / sum); - else - freqsParam.setParameterValue(j, 1.0 / freqsParam.getDimension()); - } - sum = 1.0; - } - - if (Math.abs(sum - 1.0) > 1e-8) { - throw new XMLParseException("Frequencies do not sum to 1 (they sum to " + sum + ")"); - } - - - NumberFormat format = NumberFormat.getNumberInstance(); - format.setMaximumFractionDigits(5); - - sb.append(format.format(freqsParam.getParameterValue(0))); - for (int j = 1; j < freqsParam.getDimension(); j++) { - sb.append(", "); - sb.append(format.format(freqsParam.getParameterValue(j))); - } - sb.append("}"); - Logger.getLogger("dr.evomodel").info(sb.toString()); - - return new FrequencyModel(dataType, freqsParam); - } - - public String getParserDescription() { - return "A model of equilibrium base frequencies."; - } - - public Class getReturnType() { - return FrequencyModel.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private final XMLSyntaxRule[] rules = { - AttributeRule.newBooleanRule(NORMALIZE, true), - - new ElementRule(PatternList.class, "Initial value", 0, 1), - - new XORRule( - new StringAttributeRule(DataType.DATA_TYPE, "The type of sequence data", - DataType.getRegisteredDataTypeNames(), false), - new ElementRule(DataType.class) - ), - - new ElementRule(FREQUENCIES, - new XMLSyntaxRule[]{new ElementRule(Parameter.class)}), - - }; - - -} diff --git a/src/dr/oldevomodelxml/substmodel/GTRParser.java b/src/dr/oldevomodelxml/substmodel/GTRParser.java deleted file mode 100644 index c8db3c351b..0000000000 --- a/src/dr/oldevomodelxml/substmodel/GTRParser.java +++ /dev/null @@ -1,149 +0,0 @@ -/* - * GTRParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodelxml.substmodel; - -import dr.oldevomodel.substmodel.FrequencyModel; -import dr.oldevomodel.substmodel.GTR; -import dr.oldevomodel.substmodel.SubstitutionModel; -import dr.inference.model.Variable; -import dr.xml.*; - -/** - * Parses an element from an DOM document into a DemographicModel. Recognises - * ConstantPopulation and ExponentialGrowth. - */ -public class GTRParser extends AbstractXMLObjectParser { - public static final String GTR_MODEL = "gtrModel"; - - public static final String A_TO_C = "rateAC"; - public static final String A_TO_G = "rateAG"; - public static final String A_TO_T = "rateAT"; - public static final String C_TO_G = "rateCG"; - public static final String C_TO_T = "rateCT"; - public static final String G_TO_T = "rateGT"; - - public static final String FREQUENCIES = "frequencies"; - - public String getParserName() { - return GTR_MODEL; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - XMLObject cxo = xo.getChild(FREQUENCIES); - FrequencyModel freqModel = (FrequencyModel) cxo.getChild(FrequencyModel.class); - - Variable rateACValue = null; - if (xo.hasChildNamed(A_TO_C)) { - rateACValue = (Variable) xo.getElementFirstChild(A_TO_C); - } - Variable rateAGValue = null; - if (xo.hasChildNamed(A_TO_G)) { - rateAGValue = (Variable) xo.getElementFirstChild(A_TO_G); - } - Variable rateATValue = null; - if (xo.hasChildNamed(A_TO_T)) { - rateATValue = (Variable) xo.getElementFirstChild(A_TO_T); - } - Variable rateCGValue = null; - if (xo.hasChildNamed(C_TO_G)) { - rateCGValue = (Variable) xo.getElementFirstChild(C_TO_G); - } - Variable rateCTValue = null; - if (xo.hasChildNamed(C_TO_T)) { - rateCTValue = (Variable) xo.getElementFirstChild(C_TO_T); - } - Variable rateGTValue = null; - if (xo.hasChildNamed(G_TO_T)) { - rateGTValue = (Variable) xo.getElementFirstChild(G_TO_T); - } - int countNull = 0; - if (rateACValue == null) countNull++; - if (rateAGValue == null) countNull++; - if (rateATValue == null) countNull++; - if (rateCGValue == null) countNull++; - if (rateCTValue == null) countNull++; - if (rateGTValue == null) countNull++; - - if (countNull != 1) - throw new XMLParseException("Only five parameters may be specified in GTR, leave exactly one out, the others will be specifed relative to the one left out."); - return new GTR(rateACValue, rateAGValue, rateATValue, rateCGValue, rateCTValue, rateGTValue, freqModel); - } - - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - - public String getParserDescription() { - return "A general reversible model of nucleotide sequence substitution."; - } - - public String getExample() { - - return - "\n" + - "\n" + - "\n" + - "\n" + - "<" + getParserName() + " id=\"gtr1\">\n" + - " <" + FREQUENCIES + "> \n" + - " <" + A_TO_C + "> \n" + - " <" + A_TO_T + "> \n" + - " <" + C_TO_G + "> \n" + - " <" + C_TO_T + "> \n" + - " <" + G_TO_T + "> \n" + - "\n"; - } - - public Class getReturnType() { - return SubstitutionModel.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private final XMLSyntaxRule[] rules = { - new ElementRule(FREQUENCIES, - new XMLSyntaxRule[]{new ElementRule(FrequencyModel.class)}), - new ElementRule(A_TO_C, - new XMLSyntaxRule[]{new ElementRule(Variable.class)}, true), - new ElementRule(A_TO_G, - new XMLSyntaxRule[]{new ElementRule(Variable.class)}, true), - new ElementRule(A_TO_T, - new XMLSyntaxRule[]{new ElementRule(Variable.class)}, true), - new ElementRule(C_TO_G, - new XMLSyntaxRule[]{new ElementRule(Variable.class)}, true), - new ElementRule(C_TO_T, - new XMLSyntaxRule[]{new ElementRule(Variable.class)}, true), - new ElementRule(G_TO_T, - new XMLSyntaxRule[]{new ElementRule(Variable.class)}, true) - }; - - -} diff --git a/src/dr/oldevomodelxml/substmodel/GeneralF81ModelParser.java b/src/dr/oldevomodelxml/substmodel/GeneralF81ModelParser.java deleted file mode 100644 index b545bd93b6..0000000000 --- a/src/dr/oldevomodelxml/substmodel/GeneralF81ModelParser.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * GeneralF81ModelParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodelxml.substmodel; - -import dr.oldevomodel.substmodel.FrequencyModel; -import dr.oldevomodel.substmodel.GeneralF81Model; -import dr.xml.*; - -import java.util.logging.Logger; - -/** - * Parses a GeneralF81Model - */ -public class GeneralF81ModelParser extends AbstractXMLObjectParser { - - public static final String GENERAL_F81_MODEL = "generalF81Model"; - public static final String FREQUENCIES = "frequencies"; - - public String getParserName() { - return GENERAL_F81_MODEL; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - FrequencyModel freqModel = null; - if (xo.hasChildNamed(FREQUENCIES)) { - XMLObject cxo = xo.getChild(FREQUENCIES); - freqModel = (FrequencyModel) cxo.getChild(FrequencyModel.class); - } - Logger.getLogger("dr.evomodel").info(" General F81 Model from frequencyModel '"+ freqModel.getId() + "' (stateCount=" + freqModel.getFrequencyCount() + ")"); - - return new GeneralF81Model(freqModel); - } - - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - - public String getParserDescription() { - return "A general F81 model for an arbitrary number of states."; - } - - public Class getReturnType() { - return GeneralF81ModelParser.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private final XMLSyntaxRule[] rules = { - new ElementRule(FREQUENCIES, FrequencyModel.class) - }; -} diff --git a/src/dr/oldevomodelxml/substmodel/GeneralSubstitutionModelParser.java b/src/dr/oldevomodelxml/substmodel/GeneralSubstitutionModelParser.java deleted file mode 100644 index c49b2af724..0000000000 --- a/src/dr/oldevomodelxml/substmodel/GeneralSubstitutionModelParser.java +++ /dev/null @@ -1,220 +0,0 @@ -/* - * GeneralSubstitutionModelParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodelxml.substmodel; - -import dr.evolution.datatype.DataType; -import dr.oldevomodel.substmodel.FrequencyModel; -import dr.oldevomodel.substmodel.GeneralSubstitutionModel; -import dr.oldevomodel.substmodel.SVSComplexSubstitutionModel; -import dr.oldevomodel.substmodel.SVSGeneralSubstitutionModel; -import dr.evoxml.util.DataTypeUtils; -import dr.inference.model.BayesianStochasticSearchVariableSelection; -import dr.inference.model.Parameter; -import dr.xml.*; - -import java.util.logging.Logger; - -/** - * Parses a GeneralSubstitutionModel or one of its more specific descendants. - */ -public class GeneralSubstitutionModelParser extends AbstractXMLObjectParser { - - public static final String GENERAL_SUBSTITUTION_MODEL = "generalSubstitutionModel"; - public static final String DATA_TYPE = "dataType"; - public static final String RATES = "rates"; - public static final String RELATIVE_TO = "relativeTo"; - public static final String FREQUENCIES = "frequencies"; - public static final String INDICATOR = "rateIndicator"; - - public static final String SVS_GENERAL_SUBSTITUTION_MODEL = "svsGeneralSubstitutionModel"; - public static final String SVS_COMPLEX_SUBSTITUTION_MODEL = "svsComplexSubstitutionModel"; - - public String getParserName() { - return GENERAL_SUBSTITUTION_MODEL; - } - - public String[] getParserNames() { - return new String[]{getParserName(), SVS_GENERAL_SUBSTITUTION_MODEL, SVS_COMPLEX_SUBSTITUTION_MODEL}; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - Parameter ratesParameter = null; - FrequencyModel freqModel = null; - - if (xo.hasChildNamed(FREQUENCIES)) { - XMLObject cxo = xo.getChild(FREQUENCIES); - freqModel = (FrequencyModel) cxo.getChild(FrequencyModel.class); - } - - DataType dataType = DataTypeUtils.getDataType(xo); - - if (dataType == null) dataType = (DataType) xo.getChild(DataType.class); - -// if (xo.hasAttribute(DataType.DATA_TYPE)) { -// String dataTypeStr = xo.getStringAttribute(DataType.DATA_TYPE); -// if (dataTypeStr.equals(Nucleotides.DESCRIPTION)) { -// dataType = Nucleotides.INSTANCE; -// } else if (dataTypeStr.equals(AminoAcids.DESCRIPTION)) { -// dataType = AminoAcids.INSTANCE; -// } else if (dataTypeStr.equals(Codons.DESCRIPTION)) { -// dataType = Codons.UNIVERSAL; -// } else if (dataTypeStr.equals(TwoStates.DESCRIPTION)) { -// dataType = TwoStates.INSTANCE; -// } -// } - - if (dataType == null) dataType = freqModel.getDataType(); - - if (dataType != freqModel.getDataType()) { - throw new XMLParseException("Data type of " + getParserName() + " element does not match that of its frequencyModel."); - } - - XMLObject cxo = xo.getChild(RATES); - ratesParameter = (Parameter) cxo.getChild(Parameter.class); - - int states = dataType.getStateCount(); - Logger.getLogger("dr.evomodel").info(" General Substitution Model (stateCount=" + states + ")"); - - boolean hasRelativeRates = cxo.hasChildNamed(RELATIVE_TO) || (cxo.hasAttribute(RELATIVE_TO) && cxo.getIntegerAttribute(RELATIVE_TO) > 0); - - int nonReversibleRateCount = ((dataType.getStateCount() - 1) * dataType.getStateCount()); - int reversibleRateCount = (nonReversibleRateCount / 2); - - boolean isNonReversible = ratesParameter.getDimension() == nonReversibleRateCount; - boolean hasIndicator = xo.hasChildNamed(INDICATOR); - - if (!hasRelativeRates) { - Parameter indicatorParameter = null; - - if (ratesParameter.getDimension() != reversibleRateCount && ratesParameter.getDimension() != nonReversibleRateCount) { - throw new XMLParseException("Rates parameter in " + getParserName() + " element should have " + (reversibleRateCount) - + " dimensions for reversible model or " + nonReversibleRateCount + " dimensions for non-reversible. " + - "However parameter dimension is " + ratesParameter.getDimension()); - } - - if (hasIndicator) { // this is using BSSVS - cxo = xo.getChild(INDICATOR); - indicatorParameter = (Parameter) cxo.getChild(Parameter.class); - - if (indicatorParameter.getDimension() != ratesParameter.getDimension()) { - throw new XMLParseException("Rates and indicator parameters in " + getParserName() + " element must be the same dimension."); - } - - boolean randomize = xo.getAttribute(ComplexSubstitutionModelParser.RANDOMIZE, false); - if (randomize) { - BayesianStochasticSearchVariableSelection.Utils.randomize(indicatorParameter, - dataType.getStateCount(), !isNonReversible); - } - } - - if (isNonReversible) { - Logger.getLogger("dr.evomodel").info(" Using BSSVS Complex Substitution Model"); - return new SVSComplexSubstitutionModel(getParserName(), dataType, freqModel, ratesParameter, indicatorParameter); - } else { - Logger.getLogger("dr.evomodel").info(" Using BSSVS General Substitution Model"); - return new SVSGeneralSubstitutionModel(dataType, freqModel, ratesParameter, indicatorParameter); - } - - - } else { - // if we have relativeTo attribute then we use the old GeneralSubstitutionModel - - if (ratesParameter.getDimension() != reversibleRateCount - 1) { - throw new XMLParseException("Rates parameter in " + getParserName() + " element should have " + (reversibleRateCount - 1) - + " dimensions. However parameter dimension is " + ratesParameter.getDimension()); - } - - int relativeTo = 0; - if (hasRelativeRates) { - relativeTo = cxo.getIntegerAttribute(RELATIVE_TO) - 1; - } - - if (relativeTo < 0 || relativeTo >= reversibleRateCount) { - throw new XMLParseException(RELATIVE_TO + " must be 1 or greater"); - } else { - int t = relativeTo; - int s = states - 1; - int row = 0; - while (t >= s) { - t -= s; - s -= 1; - row += 1; - } - int col = t + row + 1; - - Logger.getLogger("dr.evomodel").info(" Rates relative to " - + dataType.getCode(row) + "<->" + dataType.getCode(col)); - } - - if (ratesParameter == null) { - if (reversibleRateCount == 1) { - // simplest model for binary traits... - } else { - throw new XMLParseException("No rates parameter found in " + getParserName()); - } - } - - return new GeneralSubstitutionModel(dataType, freqModel, ratesParameter, relativeTo); - } - } - - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - - public String getParserDescription() { - return "A general reversible model of sequence substitution for any data type."; - } - - public Class getReturnType() { - return GeneralSubstitutionModelParser.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private final XMLSyntaxRule[] rules = { - new XORRule( - new StringAttributeRule(DataType.DATA_TYPE, "The type of sequence data", - DataType.getRegisteredDataTypeNames(), false), - new ElementRule(DataType.class) - , true), - new ElementRule(FREQUENCIES, FrequencyModel.class), - new ElementRule(RATES, - new XMLSyntaxRule[]{ - new ElementRule(Parameter.class)} - ), - new ElementRule(INDICATOR, - new XMLSyntaxRule[]{ - new ElementRule(Parameter.class), - }, true), - AttributeRule.newBooleanRule(ComplexSubstitutionModelParser.RANDOMIZE, true), - }; -} diff --git a/src/dr/oldevomodelxml/substmodel/HKYParser.java b/src/dr/oldevomodelxml/substmodel/HKYParser.java deleted file mode 100644 index c92a795940..0000000000 --- a/src/dr/oldevomodelxml/substmodel/HKYParser.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * HKYParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodelxml.substmodel; - -import dr.oldevomodel.substmodel.FrequencyModel; -import dr.oldevomodel.substmodel.HKY; -import dr.oldevomodel.substmodel.NucModelType; -import dr.inference.model.Variable; -import dr.xml.*; - -import java.util.logging.Logger; - -/** - * @author Alexei Drummond - * @author Andrew Rambaut - */ -public class HKYParser extends AbstractXMLObjectParser { - - public static final String KAPPA = "kappa"; - public static final String FREQUENCIES = "frequencies"; - - public String getParserName() { - return NucModelType.HKY.getXMLName(); - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - Variable kappaParam = (Variable) xo.getElementFirstChild(KAPPA); - FrequencyModel freqModel = (FrequencyModel) xo.getElementFirstChild(FrequencyModelParser.FREQUENCIES); - - Logger.getLogger("dr.evomodel").info("Creating HKY substitution model. Initial kappa = " + - kappaParam.getValue(0)); - - return new HKY(kappaParam, freqModel); - } - - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - - public String getParserDescription() { - return "This element represents an instance of the HKY85 " + - "(Hasegawa, Kishino & Yano, 1985) model of nucleotide evolution."; - } - - public Class getReturnType() { - return HKY.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private final XMLSyntaxRule[] rules = { - new ElementRule(FrequencyModelParser.FREQUENCIES, - new XMLSyntaxRule[]{new ElementRule(FrequencyModel.class)}), - new ElementRule(KAPPA, - new XMLSyntaxRule[]{new ElementRule(Variable.class)}) - }; -} \ No newline at end of file diff --git a/src/dr/oldevomodelxml/substmodel/LewisMkSubstitutionModelParser.java b/src/dr/oldevomodelxml/substmodel/LewisMkSubstitutionModelParser.java deleted file mode 100644 index 7fa1f5805f..0000000000 --- a/src/dr/oldevomodelxml/substmodel/LewisMkSubstitutionModelParser.java +++ /dev/null @@ -1,178 +0,0 @@ -/* - * LewisMkSubstitutionModelParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodelxml.substmodel; - -import dr.evolution.datatype.DataType; -import dr.oldevomodel.substmodel.FrequencyModel; -import dr.oldevomodel.substmodel.GeneralSubstitutionModel; -import dr.inference.model.Parameter; -import dr.xml.*; - -import java.util.Stack; - -/** - * Package: LewisMkSubstitutionModelParser - * Description: - *

- *

- * Created by - * - * @author Alexander V. Alekseyenko (alexander.alekseyenko@gmail.com) - * Date: Oct 13, 2009 - * Time: 4:01:38 PM - */ -public class LewisMkSubstitutionModelParser extends AbstractXMLObjectParser { - public static final String LEWIS_MK_MODEL = "lewisMk"; - public static final String TOTAL_ORDER = "totalOrder"; - public static final String FREQUENCIES = "frequencies"; - public static final String ORDER = "order"; - public static final String STATE = "state"; - public static final String ADJACENT = "adjacentTo"; - - //public static XMLObjectParser PARSER=new LewisMkSubstitutionModelParser(); - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - XMLObject cxo = xo.getChild(FREQUENCIES); - FrequencyModel freqModel = (FrequencyModel) cxo.getChild(FrequencyModel.class); - DataType dataType = freqModel.getDataType(); - int k = dataType.getStateCount(); - System.err.println("Number of states " + k); - Parameter ratesParameter; - if (xo.hasAttribute(TOTAL_ORDER) && xo.getBooleanAttribute(TOTAL_ORDER)) { //TOTAL ORDERING OF THE STATES BASED ON DATATYPE - ratesParameter = new Parameter.Default(k * (k - 1) / 2, 0); - int j = k - 1; - for (int i = 0; i < (k - 1) * k / 2; i = i + j + 1) { - ratesParameter.setParameterValue(i, 1); - j -= 1; - } - } else if (xo.hasChildNamed(ORDER)) { // USER-SPECIFIED ORDERING OF THE STATES - ratesParameter = new Parameter.Default(k * (k - 1) / 2, 0); - for (int i = 0; i < xo.getChildCount(); ++i) { - if (xo.getChildName(i).equals(ORDER)) { - cxo = (XMLObject) xo.getChild(i); - if (cxo.getName().equals(ORDER)) { - int from = dataType.getState(cxo.getStringAttribute(STATE).charAt(0)); - int to = dataType.getState(cxo.getStringAttribute(ADJACENT).charAt(0)); - if (from > to) {//SWAP: from should have the smaller state number - to += from; - from = to - from; - to -= from; - } - int ratesIndex = (from * (2 * k - 3) - from * from) / 2 + to - 1; - ratesParameter.setParameterValue(ratesIndex, 1); - } - } - } - } else { - ratesParameter = new Parameter.Default(k * (k - 1) / 2, 1); - } - System.err.println(ratesParameter.toString()); - System.err.println("Infinitesimal matrix:"); - for (int i = 0; i < k; ++i) { - for (int j = 0; j < k; ++j) { - int from, to; - if (i < j) { - from = i; - to = j; - } else { - from = j; - to = i; - } - - - int ratesIndex = (from * (2 * k - 3) - from * from) / 2 + to - 1; //This is right now!!! Thanks, Marc! - - if (i != j) - System.err.print(Double.toString(ratesParameter.getValue(ratesIndex)) + "\t(" + ratesIndex + ")\t"); - else System.err.print("-\t\t"); - - } - System.err.println("");//newline - } - System.err.println(""); - - if (!checkConnected(ratesParameter.getValues(), k)) { - throw (new XMLParseException("The state transitions form a disconnected graph! This model is not suited for this case.")); - } - - return new GeneralSubstitutionModel(dataType, freqModel, ratesParameter, 0); - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private boolean checkConnected(Double rates[], int states) { - boolean[] visited = new boolean[states]; - Stack open = new Stack(); - - open.push(0); - - for (int i = 1; i < states; ++i) { - visited[i] = false; - } - visited[0] = true; - - while (!open.empty()) { - int current = open.pop(); - for (int j = 0; j < states; ++j) { - int rateIndex; - if (current < j) rateIndex = (current * (2 * states - 3) - current * current) / 2 + j - 1; - else rateIndex = (j * (2 * states - 3) - j * j) / 2 + current - 1; - if (current != j && !visited[j] && rates[rateIndex] != 0.0) { - visited[j] = true; - open.push(j); - } - } - } - for (int i = 0; i < states; ++i) { - if (!visited[i]) return false; - } - return true; - } - - private final XMLSyntaxRule[] rules = { - new ElementRule(FREQUENCIES, FrequencyModel.class), - AttributeRule.newBooleanRule(TOTAL_ORDER, true), - new ElementRule(ORDER, - new XMLSyntaxRule[]{AttributeRule.newStringRule(STATE, false), - AttributeRule.newStringRule(ADJACENT, false)}, 0, Integer.MAX_VALUE) - }; - - public String getParserDescription() { - return "A parser for Lewis' Mk model"; - } - - public Class getReturnType() { - return GeneralSubstitutionModel.class; - } - - public String getParserName() { - return LEWIS_MK_MODEL; - } -} diff --git a/src/dr/oldevomodelxml/substmodel/LinearBiasModelParser.java b/src/dr/oldevomodelxml/substmodel/LinearBiasModelParser.java deleted file mode 100644 index 5b2546eba4..0000000000 --- a/src/dr/oldevomodelxml/substmodel/LinearBiasModelParser.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * LinearBiasModelParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodelxml.substmodel; - -import dr.evolution.datatype.Microsatellite; -import dr.oldevomodel.substmodel.FrequencyModel; -import dr.oldevomodel.substmodel.LinearBiasModel; -import dr.oldevomodel.substmodel.OnePhaseModel; -import dr.inference.model.Parameter; -import dr.xml.*; -/** - * @author Chieh-Hsi Wu - * - * Parser for LinearBiasModel of Microsatellite. - */ -public class LinearBiasModelParser extends AbstractXMLObjectParser { - public static final String SUBMODEL = "Submodel"; - public static final String BIAS_CONSTANT = "BiasConstant"; - public static final String BIAS_LINEAR = "BiasLinear"; - public static final String ESTIMATE_SUBMODEL_PARAMS = "estimateSubmodelParameters"; - public static final String LOGISTICS = "logistics"; - public static final String IS_SUBMODEL = "isSubmodel"; - - - public String getParserName() { - return LinearBiasModel.LINEAR_BIAS_MODEL; - } - - - //AbstractXMLObjectParser implementation - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - OnePhaseModel subModel = (OnePhaseModel) xo.getElementFirstChild(SUBMODEL); - Microsatellite dataType = (Microsatellite)subModel.getDataType(); - - Parameter biasConst = null; - if(xo.hasChildNamed(BIAS_CONSTANT)){ - biasConst =(Parameter) xo.getElementFirstChild(BIAS_CONSTANT); - } - - Parameter biasLin = null; - if(xo.hasChildNamed(BIAS_LINEAR)){ - biasLin = (Parameter) xo.getElementFirstChild(BIAS_LINEAR); - } - - //get FrequencyModel - FrequencyModel freqModel = null; - if(xo.hasChildNamed(FrequencyModelParser.FREQUENCIES)){ - freqModel = (FrequencyModel)xo.getElementFirstChild(FrequencyModelParser.FREQUENCIES); - } - - boolean estimateSubmodelParams = false; - if(xo.hasAttribute(ESTIMATE_SUBMODEL_PARAMS)){ - estimateSubmodelParams = xo.getBooleanAttribute(ESTIMATE_SUBMODEL_PARAMS); - } - System.out.println("Is estimating submodel parameter(s): "+estimateSubmodelParams); - - boolean logistics = false; - if(xo.hasAttribute(LOGISTICS)){ - logistics = xo.getBooleanAttribute(LOGISTICS); - } - System.out.println("Using logistic regression: "+ logistics); - - boolean isSubmodel = false; - if(xo.hasAttribute(IS_SUBMODEL)){ - isSubmodel = xo.getBooleanAttribute(IS_SUBMODEL); - } - System.out.println("Is a submodel: "+isSubmodel); - - return new LinearBiasModel( - dataType, - freqModel, - subModel, - biasConst, - biasLin, - logistics, - estimateSubmodelParams, - isSubmodel - ); - } - - public String getParserDescription() { - return "This element represents an instance of the stepwise mutation model of microsatellite evolution."; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{ - new ElementRule(FrequencyModelParser.FREQUENCIES, new XMLSyntaxRule[]{ - new ElementRule(FrequencyModel.class)},true), - new ElementRule(SUBMODEL,new XMLSyntaxRule[]{new ElementRule(OnePhaseModel.class)}), - new ElementRule(Microsatellite.class), - new ElementRule(BIAS_CONSTANT,new XMLSyntaxRule[]{new ElementRule(Parameter.class)},true), - new ElementRule(BIAS_LINEAR,new XMLSyntaxRule[]{new ElementRule(Parameter.class)},true), - new StringAttributeRule(ESTIMATE_SUBMODEL_PARAMS,"whether or not to esitmate the parameters of the submodel",true), - AttributeRule.newBooleanRule(LOGISTICS,true), - AttributeRule.newBooleanRule(IS_SUBMODEL,true) - }; - - public Class getReturnType() { - return LinearBiasModel.class; - } - - -} diff --git a/src/dr/oldevomodelxml/substmodel/MkModelParser.java b/src/dr/oldevomodelxml/substmodel/MkModelParser.java deleted file mode 100644 index 8690b66ba4..0000000000 --- a/src/dr/oldevomodelxml/substmodel/MkModelParser.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * MkModelParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodelxml.substmodel; - -import dr.evolution.datatype.DataType; -import dr.oldevomodel.substmodel.FrequencyModel; -import dr.oldevomodel.substmodel.GeneralSubstitutionModel; -import dr.inference.model.Parameter; -import dr.xml.*; - -import java.util.logging.Logger; - -/** - * @author Alexander V Alekseyenko (alexander.alekseyenko@gmail.com) - *

- * MkModelParser implements Lewis's Mk Model Syst. Biol. 50(6):913-925, 2001 - */ -public class MkModelParser extends AbstractXMLObjectParser { - - public static final String MK_SUBSTITUTION_MODEL = "mkSubstitutionModel"; - - public String getParserName() { - return MK_SUBSTITUTION_MODEL; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - XMLObject cxo = xo.getChild(GeneralSubstitutionModelParser.FREQUENCIES); - FrequencyModel freqModel = (FrequencyModel) cxo.getChild(FrequencyModel.class); - - DataType dataType = freqModel.getDataType(); - int rateCount = ((dataType.getStateCount() - 1) * dataType.getStateCount()) / 2 - 1; - Parameter ratesParameter = new Parameter.Default(rateCount, 1.0); - - Logger.getLogger("dr.evolution").info("Creating an Mk substitution model with data type: " + dataType.getType() + "on " + dataType.getStateCount() + " states."); - - int relativeTo = 1; - - return new GeneralSubstitutionModel(dataType, freqModel, ratesParameter, relativeTo); - } - - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - - public String getParserDescription() { - return "An Mk model of substitution. This model can also accomodate arbitrary orderings of changes."; - } - - public Class getReturnType() { - return GeneralSubstitutionModel.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{ - new ElementRule(GeneralSubstitutionModelParser.FREQUENCIES, FrequencyModel.class), - }; - -} \ No newline at end of file diff --git a/src/dr/oldevomodelxml/substmodel/MsatBMAParser.java b/src/dr/oldevomodelxml/substmodel/MsatBMAParser.java deleted file mode 100644 index 233a21ab74..0000000000 --- a/src/dr/oldevomodelxml/substmodel/MsatBMAParser.java +++ /dev/null @@ -1,329 +0,0 @@ -/* - * MsatBMAParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodelxml.substmodel; - -import dr.xml.*; -import dr.evolution.datatype.Microsatellite; -import dr.inference.model.Parameter; -import dr.oldevomodel.substmodel.MsatBMA; - -import java.util.HashMap; -import java.util.ArrayList; - -/** - * @author Chieh-Hsi Wu - * - * Parser of MsatAveragingSubsetModel - */ -public class MsatBMAParser extends AbstractXMLObjectParser{ - - public static final String MODELS = "models"; - public static final String MODEL = "model"; - public static final String BINARY = "binary"; - public static final String CODE = "code"; - public static final String LOGIT = "logit"; - public static final String RATE_PROPS = "rateProps"; - public static final String RATE_PROP = "rateProp"; - public static final String RATE_QUADS = "rateQuads"; - public static final String RATE_QUAD = "rateQuad"; - public static final String BIAS_CONSTS = "biasConsts"; - public static final String BIAS_CONST = "biasConst"; - public static final String BIAS_LINS = "biasLins"; - public static final String BIAS_LIN = "biasLin"; - public static final String GEOS = "geos"; - public static final String GEO = "geo"; - public static final String PHASE_PROBS = "phaseProbs"; - public static final String PHASE_PROB = "phaseProb"; - public static final String IN_MODELS = "inModels"; - public static final String MODEL_CHOOSE = "modelChoose"; - public static final String MODEL_INDICATOR = "modelIndicator"; - public static final String MSAT_BMA = "msatBMA"; - public static final int PROP_RATES_MAX_COUNT = 6; - public static final int BIAS_CONST_MAX_COUNT = 8; - public static final int BIAS_LIN_MAX_COUNT = 4; - public static final int GEO_MAX_COUNT = 6; - - - - public String getParserName(){ - return MSAT_BMA; - } - - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - //get microsatellite data type - Microsatellite dataType = (Microsatellite)xo.getChild(Microsatellite.class); - - //whether mutational bias is in logit space - boolean logit = xo.getAttribute(LOGIT,true); - - XMLObject modelsXO = xo.getChild(MODELS); - int modelCount = modelsXO.getChildCount(); - - HashMap modelBitIndMap = new HashMap(modelCount); - for(int i = 0; i < modelCount; i++){ - - XMLObject modelXO = (XMLObject)modelsXO.getChild(i); - String bitVec = modelXO.getStringAttribute(BINARY); - int bitVecVal = Integer.parseInt(bitVec,2); - int modelCode = modelXO.getIntegerAttribute(CODE); - modelBitIndMap.put(bitVecVal,modelCode); - - } - - Parameter[][] paramModelMap = new Parameter[6][modelCount]; - - - - XMLObject propRatesXO = xo.getChild(RATE_PROPS); - ArrayList rateProps = - processParameters( - propRatesXO, - paramModelMap, - MsatBMA.PROP_INDEX - ); - - XMLObject quadRatesXO = xo.getChild(RATE_QUADS); - ArrayList rateQuads = - processParameters( - quadRatesXO, - paramModelMap, - MsatBMA.QUAD_INDEX - ); - - XMLObject biasConstsXO = xo.getChild(BIAS_CONSTS); - ArrayList biasConsts = - processParameters( - biasConstsXO, - paramModelMap, - MsatBMA.BIAS_CONST_INDEX - ); - - XMLObject biasLinsXO = xo.getChild(BIAS_LINS); - ArrayList biasLins = - processParameters( - biasLinsXO, - paramModelMap, - MsatBMA.BIAS_LIN_INDEX - ); - - XMLObject geosXO = xo.getChild(GEOS); - ArrayList geos = - processParameters( - geosXO, - paramModelMap, - MsatBMA.GEO_INDEX - ); - - XMLObject phaseProbXO = xo.getChild(PHASE_PROBS); - ArrayList phaseProbs = - processParameters( - phaseProbXO, - paramModelMap, - MsatBMA.PHASE_PROB_INDEX - ); - - Parameter modelChoose = (Parameter) xo.getElementFirstChild(MODEL_CHOOSE); - Parameter modelIndicator = (Parameter) xo.getElementFirstChild(MODEL_INDICATOR); - - printParameters(paramModelMap); - return new MsatBMA( - dataType, - logit, - rateProps, - rateQuads, - biasConsts, - biasLins, - geos, - phaseProbs, - paramModelMap, - modelChoose, - modelIndicator, - modelBitIndMap - ); - } - - public ArrayList processParameters( - XMLObject paramsXO, - Parameter[][] paramModelMap, - int paramIndex)throws XMLParseException{ - - ArrayList paramList = new ArrayList(); - int paramsCount = paramsXO.getChildCount(); - - for(int i = 0; i < paramsCount; i++){ - - XMLObject paramXO = (XMLObject) paramsXO.getChild(i); - int[] inModels = paramXO.getIntegerArrayAttribute(IN_MODELS); - Parameter param = (Parameter)paramXO.getChild(Parameter.class); - - for(int j = 0; j < inModels.length; j++){ - if(paramModelMap[paramIndex][inModels[j]] == null){ - paramModelMap[paramIndex][inModels[j]] = param; - }else{ - throw new RuntimeException("Different objects cannot be assigned to the same parameter in a model"); - } - } - - paramList.add(param); - - } - return paramList; - } - - public void printParameters(Parameter[][] paramModelMap){ - for(int i = 0; i < paramModelMap.length; i++){ - for(int j = 0; j < paramModelMap[i].length; j++){ - System.out.print(paramModelMap[i][j]+" "); - } - System.out.println(); - } - } - - - - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{ - new ElementRule(Microsatellite.class), - AttributeRule.newBooleanRule(LOGIT,true), - new ElementRule( - MODELS, - new XMLSyntaxRule[]{ - new ElementRule( - MODEL, - new XMLSyntaxRule[]{ - AttributeRule.newStringRule(BINARY), - AttributeRule.newStringRule(CODE) - }, - 1, - 27 - ) - } - ), - new ElementRule( - RATE_PROPS, - new XMLSyntaxRule[]{ - new ElementRule( - RATE_PROP, - new XMLSyntaxRule[]{ - AttributeRule.newIntegerArrayRule(IN_MODELS, false), - new ElementRule(Parameter.class) - }, - 1, - 18 - ) - } - ), - new ElementRule( - RATE_QUADS, - new XMLSyntaxRule[]{ - new ElementRule( - RATE_QUAD, - new XMLSyntaxRule[]{ - AttributeRule.newIntegerArrayRule(IN_MODELS, false), - new ElementRule(Parameter.class) - }, - 1, - 9 - ) - } - ), - new ElementRule( - BIAS_CONSTS, - new XMLSyntaxRule[]{ - new ElementRule( - BIAS_CONST, - new XMLSyntaxRule[]{ - AttributeRule.newIntegerArrayRule(IN_MODELS, false), - new ElementRule(Parameter.class) - }, - 1, - 18 - ) - } - ), - new ElementRule( - BIAS_LINS, - new XMLSyntaxRule[]{ - new ElementRule( - BIAS_LIN, - new XMLSyntaxRule[]{ - AttributeRule.newIntegerArrayRule(IN_MODELS, false), - new ElementRule(Parameter.class) - }, - 1, - 9 - ) - } - ), - new ElementRule( - GEOS, - new XMLSyntaxRule[]{ - new ElementRule( - GEO, - new XMLSyntaxRule[]{ - AttributeRule.newIntegerArrayRule(IN_MODELS, false), - new ElementRule(Parameter.class) - }, - 1, - 18 - ) - } - ), - new ElementRule( - PHASE_PROBS, - new XMLSyntaxRule[]{ - new ElementRule( - PHASE_PROB, - new XMLSyntaxRule[]{ - AttributeRule.newIntegerArrayRule(IN_MODELS, false), - new ElementRule(Parameter.class) - }, - 1, - 9 - ) - } - ), - new ElementRule(MODEL_CHOOSE, new XMLSyntaxRule[]{new ElementRule(Parameter.class)}), - new ElementRule(MODEL_INDICATOR, new XMLSyntaxRule[]{new ElementRule(Parameter.class)}) - - }; - - public String getParserDescription() { - return "This element represents an instance of the Microsatellite Averaging Model of microsatellite evolution."; - } - - public Class getReturnType(){ - return MsatBMA.class; - } -} diff --git a/src/dr/oldevomodelxml/substmodel/MutationDeathModelParser.java b/src/dr/oldevomodelxml/substmodel/MutationDeathModelParser.java deleted file mode 100644 index 4ffbdb5d7d..0000000000 --- a/src/dr/oldevomodelxml/substmodel/MutationDeathModelParser.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * MutationDeathModelParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodelxml.substmodel; - -import dr.evolution.datatype.MutationDeathType; -import dr.oldevomodel.substmodel.AbstractSubstitutionModel; -import dr.oldevomodel.substmodel.FrequencyModel; -import dr.oldevomodel.substmodel.MutationDeathModel; -import dr.inference.model.Parameter; -import dr.xml.*; - -import java.util.logging.Logger; - -/** - * - */ -public class MutationDeathModelParser extends AbstractXMLObjectParser { - - public static final String MD_MODEL = "mutationDeathModel"; - public static final String MUTATION_RATE = "mutationRate"; - - public String getParserName() { - return MD_MODEL; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - Parameter dummyFreqParameter; - Parameter delParam = (Parameter) xo.getChild(Parameter.class); - - Logger.getLogger("dr.evomodel").info("Creating MutationDeath substitution model.\n\tInitial death rate is " - + delParam.getParameterValue(0)); - - MutationDeathType dT = (MutationDeathType) xo.getChild(MutationDeathType.class); - - AbstractSubstitutionModel evoModel = (AbstractSubstitutionModel) xo.getChild(AbstractSubstitutionModel.class); - if (evoModel == null) { // Assuming pure survival model - Logger.getLogger("dr.evomodel").info("\tSubstitutionModel not provided assuming pure death/survival model."); - dummyFreqParameter = new Parameter.Default(new double[]{1.0, 0.0}); - } else { - dummyFreqParameter = new Parameter.Default(dT.getStateCount()); - double freqs[] = evoModel.getFrequencyModel().getFrequencies(); - for (int i = 0; i < freqs.length; ++i) { - dummyFreqParameter.setParameterValueQuietly(i, freqs[i]); - } - dummyFreqParameter.setParameterValueQuietly(dT.getStateCount() - 1, 0.0); - } - - FrequencyModel dummyFrequencies = new FrequencyModel(dT, dummyFreqParameter); - - Parameter mutationRate; - - if (xo.hasChildNamed(MUTATION_RATE)) { - mutationRate = (Parameter) xo.getElementFirstChild(MUTATION_RATE); - } else { - mutationRate = new Parameter.Default(new double[]{1.0}); - } - Logger.getLogger("dr.evomodel").info("\tInitial mutation rate is " + mutationRate.getParameterValue(0)); - - return new MutationDeathModel(delParam, dT, evoModel, dummyFrequencies, mutationRate); - } - - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - - public String getParserDescription() { - return "This element represents an instance of the MutationDeath model of CTMC evolution with deletions."; - } - - public Class getReturnType() { - return MutationDeathModel.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{ - new ElementRule(AbstractSubstitutionModel.class, true), - new ElementRule(Parameter.class), - new ElementRule(MutationDeathType.class), - new ElementRule(MUTATION_RATE, new XMLSyntaxRule[]{new ElementRule(Parameter.class)}, true) - }; - -} diff --git a/src/dr/oldevomodelxml/substmodel/NewMicrosatelliteModelParser.java b/src/dr/oldevomodelxml/substmodel/NewMicrosatelliteModelParser.java deleted file mode 100644 index 677ec4ae70..0000000000 --- a/src/dr/oldevomodelxml/substmodel/NewMicrosatelliteModelParser.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * NewMicrosatelliteModelParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodelxml.substmodel; - -import dr.evolution.datatype.Microsatellite; -import dr.oldevomodel.substmodel.FrequencyModel; -import dr.oldevomodel.substmodel.NewMicrosatelliteModel; -import dr.xml.*; - - -/** - * @author Chieh-Hsi Wu - * - */ -public class NewMicrosatelliteModelParser extends AbstractXMLObjectParser{ - public static final String NEW_MSAT_MODEL = "newMsatModel"; - - public String getParserName() { - return NEW_MSAT_MODEL; - } - - - //AbstractXMLObjectParser implementation - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - //get msat data type - System.out.println("Using watkins' model"); - Microsatellite msat = (Microsatellite)xo.getChild(Microsatellite.class); - //get FrequencyModel - FrequencyModel freqModel = null; - if(xo.hasChildNamed(FrequencyModelParser.FREQUENCIES)){ - freqModel = (FrequencyModel)xo.getElementFirstChild(FrequencyModelParser.FREQUENCIES); - } - - - return new NewMicrosatelliteModel(msat, freqModel); - } - - - public String getParserDescription() { - return "This element represents an instance of the stepwise mutation model of microsatellite evolution."; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{ - new ElementRule(Microsatellite.class), - new ElementRule(FrequencyModel.class,true) - }; - - public Class getReturnType() { - return NewMicrosatelliteModel.class; - } -} diff --git a/src/dr/oldevomodelxml/substmodel/NtdBMAParser.java b/src/dr/oldevomodelxml/substmodel/NtdBMAParser.java deleted file mode 100644 index 5262684e2a..0000000000 --- a/src/dr/oldevomodelxml/substmodel/NtdBMAParser.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * NtdBMAParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodelxml.substmodel; - -import dr.xml.*; -import dr.oldevomodel.substmodel.FrequencyModel; -import dr.oldevomodel.substmodel.NtdBMA; -import dr.inference.model.Variable; - -/** - * @author Chieh-Hsi Wu - * Parser for nucleotide subsitution - */ -public class NtdBMAParser extends AbstractXMLObjectParser { - public static final String NTD_BMA = "ntdBMA"; - public static final String KAPPA = "kappa"; - public static final String TN = "tn"; - public static final String AT = "at"; - public static final String AC = "ac"; - public static final String GC = "gc"; - public static final String GT = "gt"; - public static final String MODEL_CHOOSE = "modelChoose"; - - public static final String FREQUENCIES = "frequencies"; - - public String getParserName() { - return NTD_BMA; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - - - Variable kappa = (Variable) xo.getElementFirstChild(KAPPA); - Variable tn = (Variable) xo.getElementFirstChild(TN); - Variable ac = (Variable) xo.getElementFirstChild(AC); - Variable at = (Variable) xo.getElementFirstChild(AT); - Variable gc = (Variable) xo.getElementFirstChild(GC); - Variable gt = (Variable) xo.getElementFirstChild(GT); - Variable modelChoose = (Variable) xo.getElementFirstChild(MODEL_CHOOSE); - XMLObject cxo = xo.getChild(FREQUENCIES); - FrequencyModel freqModel = (FrequencyModel) cxo.getChild(FrequencyModel.class); - - - return new NtdBMA(kappa, tn, ac, at, gc, gt, modelChoose, freqModel); - } - - public Class getReturnType() { - return NtdBMA.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private final XMLSyntaxRule[] rules = { - new ElementRule(FREQUENCIES, - new XMLSyntaxRule[]{new ElementRule(FrequencyModel.class)}), - new ElementRule(KAPPA, - new XMLSyntaxRule[]{new ElementRule(Variable.class)}, true), - new ElementRule(AC, - new XMLSyntaxRule[]{new ElementRule(Variable.class)}, true), - new ElementRule(AT, - new XMLSyntaxRule[]{new ElementRule(Variable.class)}, true), - new ElementRule(GC, - new XMLSyntaxRule[]{new ElementRule(Variable.class)}, true), - new ElementRule(GT, - new XMLSyntaxRule[]{new ElementRule(Variable.class)}, true), - new ElementRule(MODEL_CHOOSE, - new XMLSyntaxRule[]{new ElementRule(Variable.class)}, true), - }; - public String getParserDescription() { - return "A model that allows model averaging over nucleotide substitution models."; - } -} diff --git a/src/dr/oldevomodelxml/substmodel/PCACodonModelParser.java b/src/dr/oldevomodelxml/substmodel/PCACodonModelParser.java deleted file mode 100644 index d833312da4..0000000000 --- a/src/dr/oldevomodelxml/substmodel/PCACodonModelParser.java +++ /dev/null @@ -1,185 +0,0 @@ -/* - * PCACodonModelParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodelxml.substmodel; - -import java.util.logging.Logger; - -import dr.evolution.datatype.Codons; -import dr.evolution.datatype.DataType; -import dr.evolution.datatype.GeneticCode; -import dr.evomodel.substmodel.*; -import dr.inference.model.Parameter; -import dr.oldevomodel.substmodel.AbstractPCARateMatrix; -import dr.oldevomodel.substmodel.FrequencyModel; -import dr.oldevomodel.substmodel.PCACodonModel; -import dr.oldevomodel.substmodel.PCARateMatrixMammalia; -import dr.xml.*; - -/** - * XML parser for PCACodonModel - * - * @author Stefan Zoller - */ -public class PCACodonModelParser extends AbstractXMLObjectParser { - public static final String PCA_CODON_MODEL = "pcaCodonModel"; - public static final String PCATYPE = "pcaType"; - public static final String PCANUMBER = "pcaNumber"; - public static final String PCA_DIMENSION = "pcaDimension"; - public static final String PCA_DATA_DIR = "pcaDataDir"; - - public String getParserName() { return PCA_CODON_MODEL; } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - Codons codons = Codons.UNIVERSAL; - if (xo.hasAttribute(GeneticCode.GENETIC_CODE)) { - String codeStr = xo.getStringAttribute(GeneticCode.GENETIC_CODE); - if (codeStr.equals(GeneticCode.UNIVERSAL.getName())) { - codons = Codons.UNIVERSAL; - } else if (codeStr.equals(GeneticCode.VERTEBRATE_MT.getName())) { - codons = Codons.VERTEBRATE_MT; - } else if (codeStr.equals(GeneticCode.YEAST.getName())) { - codons = Codons.YEAST; - } else if (codeStr.equals(GeneticCode.MOLD_PROTOZOAN_MT.getName())) { - codons = Codons.MOLD_PROTOZOAN_MT; - } else if (codeStr.equals(GeneticCode.INVERTEBRATE_MT.getName())) { - codons = Codons.INVERTEBRATE_MT; - } else if (codeStr.equals(GeneticCode.CILIATE.getName())) { - codons = Codons.CILIATE; - } else if (codeStr.equals(GeneticCode.ECHINODERM_MT.getName())) { - codons = Codons.ECHINODERM_MT; - } else if (codeStr.equals(GeneticCode.EUPLOTID_NUC.getName())) { - codons = Codons.EUPLOTID_NUC; - } else if (codeStr.equals(GeneticCode.BACTERIAL.getName())) { - codons = Codons.BACTERIAL; - } else if (codeStr.equals(GeneticCode.ALT_YEAST.getName())) { - codons = Codons.ALT_YEAST; - } else if (codeStr.equals(GeneticCode.ASCIDIAN_MT.getName())) { - codons = Codons.ASCIDIAN_MT; - } else if (codeStr.equals(GeneticCode.FLATWORM_MT.getName())) { - codons = Codons.FLATWORM_MT; - } else if (codeStr.equals(GeneticCode.BLEPHARISMA_NUC.getName())) { - codons = Codons.BLEPHARISMA_NUC; - } else if (codeStr.equals(GeneticCode.NO_STOPS.getName())) { - codons = Codons.NO_STOPS; - } - } - - // get number of PCs - Parameter pcaDimensionParameter = (Parameter)xo.getElementFirstChild(PCA_DIMENSION); - - // get directory with pca rate matrix files; fallback to default "pcadata" - String dirString = "pcadata"; - if(xo.hasAttribute(PCA_DATA_DIR)) { - dirString = xo.getStringAttribute(PCA_DATA_DIR); - } - - // get type of rate matrix; fallback to mammalia pca - AbstractPCARateMatrix pcaType = new PCARateMatrixMammalia(pcaDimensionParameter.getDimension(), dirString); - // check for other type of pca - if(xo.hasAttribute(PCATYPE)) { - String pcaTypeString = xo.getStringAttribute(PCATYPE); - if(pcaTypeString.equals(PCARateMatrixMammalia.getName())) { - pcaType = new PCARateMatrixMammalia(pcaDimensionParameter.getDimension(), dirString); - } - } - - // decide if getting frequencies from csv or estimating from MSA - FrequencyModel freqModel = null; - if (xo.getChild(FrequencyModel.class) != null) { - freqModel = (FrequencyModel)xo.getChild(FrequencyModel.class); - } else { - freqModel = createNewFreqModel(codons, pcaType); - } - - return new PCACodonModel(codons, pcaType, pcaDimensionParameter, freqModel); - } - - // read frequencies from XML and return FrequencyModel object - private FrequencyModel createNewFreqModel(DataType codons, AbstractPCARateMatrix type) throws XMLParseException { - double[] freqs = type.getFrequencies(); - double sum = 0; - for (int j = 0; j < freqs.length; j++) { - sum += freqs[j]; - } - - if (Math.abs(sum - 1.0) > 1e-8) { - throw new XMLParseException("Frequencies do not sum to 1 (they sum to " + sum + ")"); - } - - FrequencyModel fm = new FrequencyModel(codons, freqs); - - Logger.getLogger("dr.evomodel").info("Using frequencies from data file"); - - return fm; - } - - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - - public String getParserDescription() { - return "This element represents the PCA model of codon evolution."; - } - - public Class getReturnType() { return PCACodonModel.class; } - - public XMLSyntaxRule[] getSyntaxRules() { return rules; } - - private XMLSyntaxRule[] rules = new XMLSyntaxRule[] { - new StringAttributeRule(GeneticCode.GENETIC_CODE, - "The genetic code to use", - new String[] { - GeneticCode.UNIVERSAL.getName(), - GeneticCode.VERTEBRATE_MT.getName(), - GeneticCode.YEAST.getName(), - GeneticCode.MOLD_PROTOZOAN_MT.getName(), - GeneticCode.INVERTEBRATE_MT.getName(), - GeneticCode.CILIATE.getName(), - GeneticCode.ECHINODERM_MT.getName(), - GeneticCode.EUPLOTID_NUC.getName(), - GeneticCode.BACTERIAL.getName(), - GeneticCode.ALT_YEAST.getName(), - GeneticCode.ASCIDIAN_MT.getName(), - GeneticCode.FLATWORM_MT.getName(), - GeneticCode.BLEPHARISMA_NUC.getName(), - GeneticCode.NO_STOPS.getName()}, true), - new StringAttributeRule(PCATYPE, - "The PCA type to use", - new String[] { - PCARateMatrixMammalia.getName(), - }, true), - new StringAttributeRule(PCA_DATA_DIR, - "The directory with the PCA data files", - "pcadata", true), - new ElementRule(PCA_DIMENSION, - new XMLSyntaxRule[] { new ElementRule(Parameter.class) }), - new ElementRule(FrequencyModel.class, true) - }; -} - diff --git a/src/dr/oldevomodelxml/substmodel/PositiveDefiniteSubstitutionModelParser.java b/src/dr/oldevomodelxml/substmodel/PositiveDefiniteSubstitutionModelParser.java deleted file mode 100644 index 372d3f1eff..0000000000 --- a/src/dr/oldevomodelxml/substmodel/PositiveDefiniteSubstitutionModelParser.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * PositiveDefiniteSubstitutionModelParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodelxml.substmodel; - -import dr.oldevomodel.substmodel.PositiveDefiniteSubstitutionModel; -import dr.inference.model.MatrixParameter; -import dr.xml.*; - -/** - * - */ -public class PositiveDefiniteSubstitutionModelParser extends AbstractXMLObjectParser { - - public static final String SVS_GENERAL_SUBSTITUTION_MODEL = "positiveDefiniteSubstitutionModel"; - - public String getParserName() { - return SVS_GENERAL_SUBSTITUTION_MODEL; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - MatrixParameter ratesParameter = (MatrixParameter) xo.getChild(MatrixParameter.class); - - return new PositiveDefiniteSubstitutionModel(ratesParameter); - } - - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - - public String getParserDescription() { - return "A general reversible model of sequence substitution for any data type with stochastic variable selection."; - } - - public Class getReturnType() { - return PositiveDefiniteSubstitutionModel.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{ - new ElementRule(MatrixParameter.class) - }; - -} diff --git a/src/dr/oldevomodelxml/substmodel/SubstitutionEpochModelParser.java b/src/dr/oldevomodelxml/substmodel/SubstitutionEpochModelParser.java deleted file mode 100644 index a1a59a11d8..0000000000 --- a/src/dr/oldevomodelxml/substmodel/SubstitutionEpochModelParser.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * SubstitutionEpochModelParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodelxml.substmodel; - -import dr.evolution.datatype.DataType; -import dr.oldevomodel.substmodel.AbstractSubstitutionModel; -import dr.oldevomodel.substmodel.FrequencyModel; -import dr.oldevomodel.substmodel.SubstitutionEpochModel; -import dr.oldevomodel.substmodel.SubstitutionModel; -import dr.inference.model.Parameter; -import dr.xml.*; - -import java.util.ArrayList; -import java.util.List; - -/** - */ -public class SubstitutionEpochModelParser extends AbstractXMLObjectParser { - - public static final String SUBSTITUTION_EPOCH_MODEL = "substitutionEpochModel"; - public static final String MODELS = "models"; - public static final String TRANSITION_TIMES = "transitionTimes"; - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - DataType dataType = null; - FrequencyModel freqModel = null; - List modelList = new ArrayList(); - XMLObject cxo = xo.getChild(MODELS); - for (int i = 0; i < cxo.getChildCount(); i++) { - SubstitutionModel model = (SubstitutionModel) cxo.getChild(i); - - if (dataType == null) { - dataType = model.getDataType(); - } else if (dataType != model.getDataType()) - throw new XMLParseException("Substitution models across epoches must use the same data type."); - - if (freqModel == null) { - freqModel = model.getFrequencyModel(); - } else if (freqModel != model.getFrequencyModel()) - throw new XMLParseException("Substitution models across epoches must currently use the same frequency model.\nHarass Marc to fix this."); - - modelList.add(model); - } - - Parameter transitionTimes = (Parameter) xo.getChild(Parameter.class); - - if (transitionTimes.getDimension() != modelList.size() - 1) { - throw new XMLParseException("# of transition times must equal # of substitution models - 1\n" + transitionTimes.getDimension() + "\n" + modelList.size()); - } - - return new SubstitutionEpochModel(SUBSTITUTION_EPOCH_MODEL, modelList, transitionTimes, dataType, freqModel); - } - - public XMLSyntaxRule[] getSyntaxRules() { - return new XMLSyntaxRule[]{ - new ElementRule(MODELS, - new XMLSyntaxRule[]{ - new ElementRule(AbstractSubstitutionModel.class, 1, Integer.MAX_VALUE), - }), - new ElementRule(Parameter.class), - }; - } - - public String getParserDescription() { - return null; - } - - public Class getReturnType() { - return SubstitutionEpochModel.class; - } - - public String getParserName() { - return SUBSTITUTION_EPOCH_MODEL; - } -} diff --git a/src/dr/oldevomodelxml/substmodel/TN93Parser.java b/src/dr/oldevomodelxml/substmodel/TN93Parser.java deleted file mode 100644 index d5c6bbbab9..0000000000 --- a/src/dr/oldevomodelxml/substmodel/TN93Parser.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * TN93Parser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodelxml.substmodel; - -import dr.oldevomodel.substmodel.FrequencyModel; -import dr.oldevomodel.substmodel.NucModelType; -import dr.oldevomodel.substmodel.TN93; -import dr.inference.model.Variable; -import dr.xml.*; - -import java.util.logging.Logger; - -/** - * Parses an element from an DOM document into a DemographicModel. Recognises - * ConstantPopulation and ExponentialGrowth. - */ -public class TN93Parser extends AbstractXMLObjectParser { - public static final String TN93_MODEL = NucModelType.TN93.getXMLName(); - public static final String KAPPA1 = "kappa1"; - public static final String KAPPA2 = "kappa2"; - public static final String FREQUENCIES = "frequencies"; - - public String getParserName() { - return TN93_MODEL; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - Variable kappa1Param = (Variable) xo.getElementFirstChild(KAPPA1); - Variable kappa2Param = (Variable) xo.getElementFirstChild(KAPPA2); - FrequencyModel freqModel = (FrequencyModel) xo.getElementFirstChild(FREQUENCIES); - - Logger.getLogger("dr.evomodel").info("Creating TN93 substitution model. Initial kappa = " - + kappa1Param.getValue(0) + "," + kappa2Param.getValue(0)); - - return new TN93(kappa1Param, kappa2Param, freqModel); - } - - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - - public String getParserDescription() { - return "This element represents an instance of the TN93 (Tamura and Nei 1993) model of nucleotide evolution."; - } - - public Class getReturnType() { - return TN93.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private final XMLSyntaxRule[] rules;{ - rules = new XMLSyntaxRule[]{ - new ElementRule(FREQUENCIES, - new XMLSyntaxRule[]{new ElementRule(FrequencyModel.class)}), - new ElementRule(KAPPA1, - new XMLSyntaxRule[]{new ElementRule(Variable.class)}), - new ElementRule(KAPPA2, - new XMLSyntaxRule[]{new ElementRule(Variable.class)}) - }; - } - - -} diff --git a/src/dr/oldevomodelxml/substmodel/TwoPhaseModelParser.java b/src/dr/oldevomodelxml/substmodel/TwoPhaseModelParser.java deleted file mode 100644 index e014b14623..0000000000 --- a/src/dr/oldevomodelxml/substmodel/TwoPhaseModelParser.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * TwoPhaseModelParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodelxml.substmodel; - -import dr.evolution.datatype.Microsatellite; -import dr.oldevomodel.substmodel.FrequencyModel; -import dr.oldevomodel.substmodel.OnePhaseModel; -import dr.oldevomodel.substmodel.TwoPhaseModel; -import dr.inference.model.Parameter; -import dr.xml.*; - -/** - * @author Chieh-Hsi Wu - * - * Parser for Two Phase Model of microsatellites. - * - */ -public class TwoPhaseModelParser extends AbstractXMLObjectParser{ - public static final String SUBMODEL = "Submodel"; - public static final String GEO_PARAM = "GeoParam"; - public static final String ONEPHASEPR_PARAM ="OnePhasePrParam"; - public static final String TRANS_PARAM = "TransformParam"; - public static final double UPPER = 1.0; - public static final double LOWER = 0.0; - public static final String ESTIMATE_SUBMODEL_PARAMS = "estimateSubmodelParameters"; - - public String getParserName() { - return TwoPhaseModel.TWO_PHASE_MODEL; - } - - //AbstractXMLObjectParser implementation - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - OnePhaseModel subModel = (OnePhaseModel) xo.getElementFirstChild(SUBMODEL); - Microsatellite dataType = (Microsatellite)xo.getChild(Microsatellite.class); - - Parameter.Default geoParam =(Parameter.Default) xo.getElementFirstChild(GEO_PARAM); - - Parameter paramP = (Parameter) xo.getElementFirstChild(ONEPHASEPR_PARAM); - - Parameter limitE = null; - if(xo.hasChildNamed(TRANS_PARAM)){ - limitE = (Parameter) xo.getElementFirstChild(TRANS_PARAM); - } - - boolean estimateSubmodelParams = xo.getAttribute(ESTIMATE_SUBMODEL_PARAMS,false); - - FrequencyModel freqModel = null; - if(xo.hasChildNamed(FrequencyModelParser.FREQUENCIES)){ - freqModel = (FrequencyModel)xo.getElementFirstChild(FrequencyModelParser.FREQUENCIES); - } - - return new TwoPhaseModel(dataType, freqModel, subModel, paramP, geoParam, limitE, estimateSubmodelParams); - } - - public String getParserDescription() { - return "This element represents an instance of the Two Phase Model of microsatellite evolution."; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{ - new ElementRule(Microsatellite.class), - new ElementRule(FrequencyModelParser.FREQUENCIES, new XMLSyntaxRule[]{new ElementRule(FrequencyModel.class)},true), - new ElementRule(SUBMODEL,new XMLSyntaxRule[]{new ElementRule(OnePhaseModel.class)}), - new ElementRule(ONEPHASEPR_PARAM,new XMLSyntaxRule[]{new ElementRule(Parameter.class)}), - new ElementRule(GEO_PARAM,new XMLSyntaxRule[]{new ElementRule(Parameter.class)}), - new ElementRule(TRANS_PARAM,new XMLSyntaxRule[]{new ElementRule(Parameter.class)},true), - new StringAttributeRule(ESTIMATE_SUBMODEL_PARAMS,"whether or not to esitmate the parameters of the submodel",true) - }; - - public Class getReturnType() { - return TwoPhaseModel.class; - } - - -} diff --git a/src/dr/oldevomodelxml/substmodel/TwoStateCovarionModelParser.java b/src/dr/oldevomodelxml/substmodel/TwoStateCovarionModelParser.java deleted file mode 100644 index bfda39cded..0000000000 --- a/src/dr/oldevomodelxml/substmodel/TwoStateCovarionModelParser.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * TwoStateCovarionModelParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodelxml.substmodel; - -import dr.evolution.datatype.TwoStateCovarion; -import dr.oldevomodel.substmodel.AbstractCovarionDNAModel; -import dr.oldevomodel.substmodel.FrequencyModel; -import dr.oldevomodel.substmodel.TwoStateCovarionModel; -import dr.inference.model.Parameter; -import dr.xml.*; - -/** - * Parses an element from an DOM document into a TwoStateCovarionModel - */ -public class TwoStateCovarionModelParser extends AbstractXMLObjectParser { - public static final String COVARION_MODEL = "covarionModel"; - public static final String ALPHA = "alpha"; - public static final String SWITCHING_RATE = "switchingRate"; - - public String getParserName() { - return COVARION_MODEL; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - Parameter alphaParameter; - Parameter switchingRateParameter; - - XMLObject cxo = xo.getChild(AbstractCovarionDNAModel.FREQUENCIES); - FrequencyModel freqModel = (FrequencyModel) cxo.getChild(FrequencyModel.class); - - TwoStateCovarion dataType = TwoStateCovarion.INSTANCE; // fancy new datatype courtesy of Helen - - cxo = xo.getChild(ALPHA); - alphaParameter = (Parameter) cxo.getChild(Parameter.class); - - // alpha must be positive and less than 1.0 because the fast rate is normalized to 1.0 - alphaParameter.addBounds(new Parameter.DefaultBounds(1.0, 0.0, 1)); - - cxo = xo.getChild(SWITCHING_RATE); - switchingRateParameter = (Parameter) cxo.getChild(Parameter.class); - - if (dataType != freqModel.getDataType()) { - throw new XMLParseException("Data type of " + getParserName() + " element does not match that of its frequencyModel."); - } - - TwoStateCovarionModel model = new TwoStateCovarionModel(dataType, freqModel, alphaParameter, switchingRateParameter); - - System.out.println(model); - - return model; - } - - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - - public String getParserDescription() { - return "A covarion substitution model on binary data and a hidden rate state with two rates."; - } - - public Class getReturnType() { - return TwoStateCovarionModel.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{ - new ElementRule(AbstractCovarionDNAModel.FREQUENCIES, FrequencyModel.class), - new ElementRule(ALPHA, new XMLSyntaxRule[]{ - new ElementRule(Parameter.class, true)} - ), - new ElementRule(SWITCHING_RATE, new XMLSyntaxRule[]{ - new ElementRule(Parameter.class, true)} - ), - }; -} diff --git a/src/dr/oldevomodelxml/substmodel/YangCodonModelParser.java b/src/dr/oldevomodelxml/substmodel/YangCodonModelParser.java deleted file mode 100644 index 1d75cf319a..0000000000 --- a/src/dr/oldevomodelxml/substmodel/YangCodonModelParser.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * YangCodonModelParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodelxml.substmodel; - -import dr.evolution.datatype.Codons; -import dr.evolution.datatype.GeneticCode; -import dr.oldevomodel.substmodel.FrequencyModel; -import dr.oldevomodel.substmodel.YangCodonModel; -import dr.inference.model.Parameter; -import dr.xml.*; - -/** - * Reads a the model from an XMLObject. - */ -public class YangCodonModelParser extends AbstractXMLObjectParser { - public static final String YANG_CODON_MODEL = "yangCodonModel"; - public static final String OMEGA = "omega"; - public static final String KAPPA = "kappa"; - - - public String getParserName() { return YANG_CODON_MODEL; } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - Codons codons = Codons.UNIVERSAL; - if (xo.hasAttribute(GeneticCode.GENETIC_CODE)) { - String codeStr = xo.getStringAttribute(GeneticCode.GENETIC_CODE); - if (codeStr.equals(GeneticCode.UNIVERSAL.getName())) { - codons = Codons.UNIVERSAL; - } else if (codeStr.equals(GeneticCode.VERTEBRATE_MT.getName())) { - codons = Codons.VERTEBRATE_MT; - } else if (codeStr.equals(GeneticCode.YEAST.getName())) { - codons = Codons.YEAST; - } else if (codeStr.equals(GeneticCode.MOLD_PROTOZOAN_MT.getName())) { - codons = Codons.MOLD_PROTOZOAN_MT; - } else if (codeStr.equals(GeneticCode.INVERTEBRATE_MT.getName())) { - codons = Codons.INVERTEBRATE_MT; - } else if (codeStr.equals(GeneticCode.CILIATE.getName())) { - codons = Codons.CILIATE; - } else if (codeStr.equals(GeneticCode.ECHINODERM_MT.getName())) { - codons = Codons.ECHINODERM_MT; - } else if (codeStr.equals(GeneticCode.EUPLOTID_NUC.getName())) { - codons = Codons.EUPLOTID_NUC; - } else if (codeStr.equals(GeneticCode.BACTERIAL.getName())) { - codons = Codons.BACTERIAL; - } else if (codeStr.equals(GeneticCode.ALT_YEAST.getName())) { - codons = Codons.ALT_YEAST; - } else if (codeStr.equals(GeneticCode.ASCIDIAN_MT.getName())) { - codons = Codons.ASCIDIAN_MT; - } else if (codeStr.equals(GeneticCode.FLATWORM_MT.getName())) { - codons = Codons.FLATWORM_MT; - } else if (codeStr.equals(GeneticCode.BLEPHARISMA_NUC.getName())) { - codons = Codons.BLEPHARISMA_NUC; - } else if (codeStr.equals(GeneticCode.NO_STOPS.getName())) { - codons = Codons.NO_STOPS; - } - } - - Parameter omegaParam = (Parameter)xo.getElementFirstChild(OMEGA); - Parameter kappaParam = (Parameter)xo.getElementFirstChild(KAPPA); - FrequencyModel freqModel = (FrequencyModel)xo.getChild(FrequencyModel.class); - -// codonModel.printRateMap(); - - return new YangCodonModel(codons, omegaParam, kappaParam, freqModel); - } - - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - - public String getParserDescription() { - return "This element represents the Yang model of codon evolution."; - } - - public Class getReturnType() { return YangCodonModel.class; } - - public XMLSyntaxRule[] getSyntaxRules() { return rules; } - - private XMLSyntaxRule[] rules = new XMLSyntaxRule[] { - new StringAttributeRule(GeneticCode.GENETIC_CODE, - "The genetic code to use", - new String[] { - GeneticCode.UNIVERSAL.getName(), - GeneticCode.VERTEBRATE_MT.getName(), - GeneticCode.YEAST.getName(), - GeneticCode.MOLD_PROTOZOAN_MT.getName(), - GeneticCode.INVERTEBRATE_MT.getName(), - GeneticCode.CILIATE.getName(), - GeneticCode.ECHINODERM_MT.getName(), - GeneticCode.EUPLOTID_NUC.getName(), - GeneticCode.BACTERIAL.getName(), - GeneticCode.ALT_YEAST.getName(), - GeneticCode.ASCIDIAN_MT.getName(), - GeneticCode.FLATWORM_MT.getName(), - GeneticCode.BLEPHARISMA_NUC.getName(), - GeneticCode.NO_STOPS.getName()}, true), - new ElementRule(OMEGA, - new XMLSyntaxRule[] { new ElementRule(Parameter.class) }), - new ElementRule(KAPPA, - new XMLSyntaxRule[] { new ElementRule(Parameter.class) }), - new ElementRule(FrequencyModel.class) - }; -} diff --git a/src/dr/oldevomodelxml/treelikelihood/AncestralStateTreeLikelihoodParser.java b/src/dr/oldevomodelxml/treelikelihood/AncestralStateTreeLikelihoodParser.java deleted file mode 100644 index e511764e0f..0000000000 --- a/src/dr/oldevomodelxml/treelikelihood/AncestralStateTreeLikelihoodParser.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * AncestralStateTreeLikelihoodParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodelxml.treelikelihood; - -import dr.evolution.alignment.PatternList; -import dr.evomodel.branchratemodel.BranchRateModel; -import dr.oldevomodel.sitemodel.SiteModel; -import dr.evomodel.tree.TreeModel; -import dr.oldevomodel.treelikelihood.AncestralStateTreeLikelihood; -import dr.xml.*; - -/** - */ -@Deprecated // Switching to BEAGLE -public class AncestralStateTreeLikelihoodParser extends AbstractXMLObjectParser { - - public static final String RECONSTRUCTING_TREE_LIKELIHOOD = "ancestralTreeLikelihood"; - public static final String RECONSTRUCTION_TAG = AncestralStateTreeLikelihood.STATES_KEY; - public static final String RECONSTRUCTION_TAG_NAME = "stateTagName"; - public static final String MAP_RECONSTRUCTION = "useMAP"; - public static final String MARGINAL_LIKELIHOOD = "useMarginalLikelihood"; - - public String[] getParserNames() { - return new String[]{ - getParserName(), "beast_" + getParserName() - }; - } - - public String getParserName() { - return RECONSTRUCTING_TREE_LIKELIHOOD; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - throw new XMLParseException("Ancestral state functionality is only support when using the BEAGLE library.\nAvailable from http://github.com/beagle-dev/beagle-lib/"); - -// boolean useAmbiguities = xo.getAttribute(TreeLikelihoodParser.USE_AMBIGUITIES, false); -// boolean storePartials = xo.getAttribute(TreeLikelihoodParser.STORE_PARTIALS, true); -// -// PatternList patternList = (PatternList) xo.getChild(PatternList.class); -// TreeModel treeModel = (TreeModel) xo.getChild(TreeModel.class); -// SiteModel siteModel = (SiteModel) xo.getChild(SiteModel.class); -// -// BranchRateModel branchRateModel = (BranchRateModel) xo.getChild(BranchRateModel.class); -// -// DataType dataType = ((SubstitutionModel) xo.getChild(SubstitutionModel.class)).getDataType(); -// -// boolean useMAP = xo.getAttribute(MAP_RECONSTRUCTION, false); -// boolean useMarginalLogLikelihood = xo.getAttribute(MARGINAL_LIKELIHOOD, true); -// -// // default tag is RECONSTRUCTION_TAG -// String tag = xo.getAttribute(RECONSTRUCTION_TAG_NAME, RECONSTRUCTION_TAG); -// -// boolean forceRescaling = xo.getAttribute(TreeLikelihoodParser.FORCE_RESCALING, false); -// -// return new AncestralStateTreeLikelihood(patternList, treeModel, siteModel, -// branchRateModel, useAmbiguities, storePartials, dataType, tag, forceRescaling, -// useMAP, useMarginalLogLikelihood); - } - - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - - public String getParserDescription() { - return "This element represents the likelihood of a patternlist on a tree given the site model."; - } - - public Class getReturnType() { - return AncestralStateTreeLikelihood.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{ - AttributeRule.newBooleanRule(TreeLikelihoodParser.USE_AMBIGUITIES, true), - AttributeRule.newBooleanRule(TreeLikelihoodParser.STORE_PARTIALS, true), - AttributeRule.newStringRule(RECONSTRUCTION_TAG_NAME, true), - AttributeRule.newBooleanRule(TreeLikelihoodParser.FORCE_RESCALING, true), - AttributeRule.newBooleanRule(MAP_RECONSTRUCTION, true), - AttributeRule.newBooleanRule(MARGINAL_LIKELIHOOD, true), - new ElementRule(PatternList.class), - new ElementRule(TreeModel.class), - new ElementRule(SiteModel.class), - new ElementRule(BranchRateModel.class, true) - }; -} diff --git a/src/dr/oldevomodelxml/treelikelihood/HiddenLinkageLikelihoodParser.java b/src/dr/oldevomodelxml/treelikelihood/HiddenLinkageLikelihoodParser.java deleted file mode 100644 index d28896f4cb..0000000000 --- a/src/dr/oldevomodelxml/treelikelihood/HiddenLinkageLikelihoodParser.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * HiddenLinkageLikelihoodParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodelxml.treelikelihood; - -import dr.evomodel.tree.HiddenLinkageModel; -import dr.evomodel.tree.TreeModel; -import dr.oldevomodel.treelikelihood.HiddenLinkageLikelihood; -import dr.xml.*; - -/** - * @author Aaron Darling (koadman) - */ -@Deprecated // Switching to BEAGLE -public class HiddenLinkageLikelihoodParser extends AbstractXMLObjectParser { - - @Override - public String getParserDescription() { - return "A likelihood calculator for hidden linkage among metagenomic reads"; - } - - @Override - public Class getReturnType() { - return HiddenLinkageLikelihood.class; - } - - @Override - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - HiddenLinkageModel hlm = (HiddenLinkageModel) xo.getChild(HiddenLinkageModel.class); - TreeModel tree = (TreeModel) xo.getChild(TreeModel.class); - return new HiddenLinkageLikelihood(hlm, tree); - } - - - public String getParserName() { - return "HiddenLinkageLikelihood"; - } - - private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{ - new ElementRule(HiddenLinkageModel.class), - new ElementRule(TreeModel.class), - }; - -} diff --git a/src/dr/oldevomodelxml/treelikelihood/MarkovJumpsTreeLikelihoodParser.java b/src/dr/oldevomodelxml/treelikelihood/MarkovJumpsTreeLikelihoodParser.java deleted file mode 100644 index 7a84d7f864..0000000000 --- a/src/dr/oldevomodelxml/treelikelihood/MarkovJumpsTreeLikelihoodParser.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * MarkovJumpsTreeLikelihoodParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodelxml.treelikelihood; - -import dr.oldevomodel.treelikelihood.AncestralStateTreeLikelihood; -import dr.xml.*; - -/** - */ -@Deprecated // Switching to BEAGLE -public class MarkovJumpsTreeLikelihoodParser extends AbstractXMLObjectParser { - - public static final String RECONSTRUCTING_TREE_LIKELIHOOD = "markovJumpsTreeLikelihood"; - - public String getParserName() { - return RECONSTRUCTING_TREE_LIKELIHOOD; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - throw new XMLParseException("MarkovJump functionality is only support when using the BEAGLE library.\nAvailable from http://github.com/beagle-dev/beagle-lib/"); - } - - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - - public String getParserDescription() { - return "This element represents the likelihood of a patternlist on a tree given the site model."; - } - - public Class getReturnType() { - return AncestralStateTreeLikelihood.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return null; - } -} \ No newline at end of file diff --git a/src/dr/oldevomodelxml/treelikelihood/MicrosatelliteSamplerTreeLikelihoodParser.java b/src/dr/oldevomodelxml/treelikelihood/MicrosatelliteSamplerTreeLikelihoodParser.java deleted file mode 100644 index c3f7991ed7..0000000000 --- a/src/dr/oldevomodelxml/treelikelihood/MicrosatelliteSamplerTreeLikelihoodParser.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * MicrosatelliteSamplerTreeLikelihoodParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodelxml.treelikelihood; - -import dr.evomodel.branchratemodel.BranchRateModel; -import dr.evomodel.branchratemodel.StrictClockBranchRates; -import dr.oldevomodel.substmodel.MicrosatelliteModel; -import dr.evomodel.tree.MicrosatelliteSamplerTreeModel; -import dr.oldevomodel.treelikelihood.MicrosatelliteSamplerTreeLikelihood; -import dr.inference.model.Parameter; -import dr.xml.*; - -/** - * @author Chieh-Hsi Wu - * - * Parser for MicrosatelliteSamplerTreeLikelihood - */ -@Deprecated // Switching to BEAGLE -public class MicrosatelliteSamplerTreeLikelihoodParser extends AbstractXMLObjectParser { - public static final String TREE_LIKELIHOOD = "microsatelliteSamplerTreeLikelihood"; - public static final String MUTATION_RATE = "mutationRate"; - public static final String BRANCH_RATE_MODEL = "branchRateModel"; - public String getParserName(){ - return TREE_LIKELIHOOD; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - MicrosatelliteSamplerTreeModel mstModel = (MicrosatelliteSamplerTreeModel)xo.getChild(MicrosatelliteSamplerTreeModel.class); - MicrosatelliteModel microsatelliteModel = (MicrosatelliteModel)xo.getChild(MicrosatelliteModel.class); - - BranchRateModel branchRateModel; - Object cxo = xo.getChild(BranchRateModel.class); - - if(xo.getChild(BranchRateModel.class) !=null){ - - branchRateModel = (BranchRateModel)cxo; - System.out.println("BranchRateModel provided to MicrosatelliteSamplerTreeLikelihood"); - - }else if(xo.hasChildNamed(MUTATION_RATE)){ - - Parameter muRate = (Parameter)xo.getElementFirstChild(MUTATION_RATE); - branchRateModel = new StrictClockBranchRates(muRate); - System.out.println("mutation rate provided to MicrosatelliteSamplerTreeLikelihood"); - - }else{ - branchRateModel = new StrictClockBranchRates(new Parameter.Default(1.0)); - } - - return new MicrosatelliteSamplerTreeLikelihood(mstModel,microsatelliteModel, branchRateModel); - } - - private final XMLSyntaxRule[] rules = { - new ElementRule(MicrosatelliteSamplerTreeModel.class), - new ElementRule(MicrosatelliteModel.class), - new ElementRule(MUTATION_RATE, new XMLSyntaxRule[]{new ElementRule(Parameter.class)},true), - new ElementRule(BranchRateModel.class,true) - }; - - public String getParserDescription(){ - return "this parser returns an object of the TreeMicrosatelliteSamplerLikelihood class"; - } - - public Class getReturnType(){ - return MicrosatelliteSamplerTreeLikelihood.class; - } - - -} diff --git a/src/dr/oldevomodelxml/treelikelihood/TreeLikelihoodParser.java b/src/dr/oldevomodelxml/treelikelihood/TreeLikelihoodParser.java deleted file mode 100644 index 8ddb0d55d6..0000000000 --- a/src/dr/oldevomodelxml/treelikelihood/TreeLikelihoodParser.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * TreeLikelihoodParser.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package dr.oldevomodelxml.treelikelihood; - -import dr.evolution.alignment.PatternList; -import dr.evomodel.branchratemodel.BranchRateModel; -import dr.oldevomodel.sitemodel.SiteModel; -import dr.evomodel.tipstatesmodel.TipStatesModel; -import dr.evomodel.tree.TreeModel; -import dr.oldevomodel.treelikelihood.TreeLikelihood; -import dr.xml.*; - -/** - */ -@Deprecated // Switching to BEAGLE -public class TreeLikelihoodParser extends AbstractXMLObjectParser { - - public static final String TREE_LIKELIHOOD = "treeLikelihood"; - public static final String ANCESTRAL_TREE_LIKELIHOOD = "ancestralTreeLikelihood"; - public static final String USE_AMBIGUITIES = "useAmbiguities"; - public static final String ALLOW_MISSING_TAXA = "allowMissingTaxa"; - public static final String STORE_PARTIALS = "storePartials"; - public static final String SCALING_FACTOR = "scalingFactor"; - public static final String SCALING_THRESHOLD = "scalingThreshold"; - public static final String FORCE_JAVA_CORE = "forceJavaCore"; - public static final String FORCE_RESCALING = "forceRescaling"; - - - public String getParserName() { - return TREE_LIKELIHOOD; - } - - public Object parseXMLObject(XMLObject xo) throws XMLParseException { - - boolean useAmbiguities = xo.getAttribute(USE_AMBIGUITIES, false); - boolean allowMissingTaxa = xo.getAttribute(ALLOW_MISSING_TAXA, false); - boolean storePartials = xo.getAttribute(STORE_PARTIALS, true); - boolean forceJavaCore = xo.getAttribute(FORCE_JAVA_CORE, false); - - if (Boolean.valueOf(System.getProperty("java.only"))) { - forceJavaCore = true; - } - - PatternList patternList = (PatternList) xo.getChild(PatternList.class); - TreeModel treeModel = (TreeModel) xo.getChild(TreeModel.class); - SiteModel siteModel = (SiteModel) xo.getChild(SiteModel.class); - - BranchRateModel branchRateModel = (BranchRateModel) xo.getChild(BranchRateModel.class); - - TipStatesModel tipStatesModel = (TipStatesModel) xo.getChild(TipStatesModel.class); - if (tipStatesModel != null && tipStatesModel.getPatternList() != null) { - throw new XMLParseException("The same sequence error model cannot be used for multiple partitions"); - } - if (tipStatesModel != null && tipStatesModel.getModelType() == TipStatesModel.Type.STATES) { - throw new XMLParseException("The state emitting TipStateModel requires BEAGLE"); - } - - - boolean forceRescaling = xo.getAttribute(FORCE_RESCALING, false); - - return new TreeLikelihood( - patternList, - treeModel, - siteModel, - branchRateModel, - tipStatesModel, - useAmbiguities, allowMissingTaxa, storePartials, forceJavaCore, forceRescaling); - } - - //************************************************************************ - // AbstractXMLObjectParser implementation - //************************************************************************ - - public String getParserDescription() { - return "This element represents the likelihood of a patternlist on a tree given the site model."; - } - - public Class getReturnType() { - return TreeLikelihood.class; - } - - public XMLSyntaxRule[] getSyntaxRules() { - return rules; - } - - private final XMLSyntaxRule[] rules = { - AttributeRule.newBooleanRule(USE_AMBIGUITIES, true), - AttributeRule.newBooleanRule(ALLOW_MISSING_TAXA, true), - AttributeRule.newBooleanRule(STORE_PARTIALS, true), - AttributeRule.newBooleanRule(FORCE_JAVA_CORE, true), - AttributeRule.newBooleanRule(FORCE_RESCALING, true), - new ElementRule(PatternList.class), - new ElementRule(TreeModel.class), - new ElementRule(SiteModel.class), - new ElementRule(BranchRateModel.class, true), - new ElementRule(TipStatesModel.class, true) - }; -} diff --git a/src/test/dr/app/beagle/MarkovJumpsTest.java b/src/test/dr/app/beagle/MarkovJumpsTest.java index 74e0fbf1e2..ed8252c826 100644 --- a/src/test/dr/app/beagle/MarkovJumpsTest.java +++ b/src/test/dr/app/beagle/MarkovJumpsTest.java @@ -34,8 +34,6 @@ import dr.evolution.alignment.SitePatterns; import dr.inference.model.Parameter; import dr.inference.markovjumps.MarkovJumpsType; -import dr.oldevomodelxml.substmodel.HKYParser; -import dr.oldevomodelxml.sitemodel.GammaSiteModelParser; import dr.evomodel.substmodel.FrequencyModel; import dr.evomodel.substmodel.nucleotide.HKY; import dr.evomodel.siteratemodel.GammaSiteRateModel; @@ -44,6 +42,9 @@ import dr.evomodel.branchratemodel.BranchRateModel; import dr.math.MathUtils; +import static dr.evomodelxml.siteratemodel.SiteModelParser.MUTATION_RATE; +import static dr.evomodelxml.substmodel.HKYParser.KAPPA; + /** * @author Marc Suchard */ @@ -69,13 +70,13 @@ public void testMarkovJumps() { //substitutionModel Parameter freqs = new Parameter.Default(new double[]{0.40, 0.25, 0.25, 0.10}); - Parameter kappa = new Parameter.Default(HKYParser.KAPPA, 10.0, 0, 100); + Parameter kappa = new Parameter.Default(KAPPA, 10.0, 0, 100); FrequencyModel f = new FrequencyModel(Nucleotides.INSTANCE, freqs); HKY hky = new HKY(kappa, f); //siteModel // double alpha = 0.5; - Parameter mu = new Parameter.Default(GammaSiteModelParser.MUTATION_RATE, 0.5, 0, Double.POSITIVE_INFINITY); + Parameter mu = new Parameter.Default(MUTATION_RATE, 0.5, 0, Double.POSITIVE_INFINITY); // Parameter pInv = new Parameter.Default("pInv", 0.5, 0, 1); Parameter pInv = null; GammaSiteRateModel siteRateModel = new GammaSiteRateModel("gammaModel", mu, 1.0, null, -1, pInv); diff --git a/src/test/dr/app/beagle/TN93Test.java b/src/test/dr/app/beagle/TN93Test.java index 7d814a6a89..10b67fbace 100644 --- a/src/test/dr/app/beagle/TN93Test.java +++ b/src/test/dr/app/beagle/TN93Test.java @@ -58,15 +58,6 @@ public void testTN93() { double[] probs = new double[16]; tn.getTransitionProbabilities(time, probs); System.out.println("new probs = " + new Vector(probs)); - - // check against old implementation - dr.oldevomodel.substmodel.FrequencyModel oldFreq = new dr.oldevomodel.substmodel.FrequencyModel(Nucleotides.INSTANCE, pi); - dr.oldevomodel.substmodel.TN93 oldTN = new dr.oldevomodel.substmodel.TN93(kappa1, kappa2, oldFreq); - - double[] oldProbs = new double[16]; - oldTN.getTransitionProbabilities(time, oldProbs); - System.out.println("old probs = " + new Vector(oldProbs)); - assertEquals(probs, oldProbs, 10E-6); } } diff --git a/src/test/dr/app/beagle/TinyTest.java b/src/test/dr/app/beagle/TinyTest.java index abd56c7ef3..a2fa1bcdb8 100644 --- a/src/test/dr/app/beagle/TinyTest.java +++ b/src/test/dr/app/beagle/TinyTest.java @@ -31,11 +31,12 @@ import dr.evomodel.substmodel.FrequencyModel; import dr.evomodel.substmodel.nucleotide.HKY; import dr.evolution.datatype.Nucleotides; -import dr.oldevomodelxml.sitemodel.GammaSiteModelParser; -import dr.oldevomodelxml.substmodel.HKYParser; import dr.inference.model.Parameter; import test.dr.inference.trace.TraceCorrelationAssert; +import static dr.evomodelxml.siteratemodel.SiteModelParser.MUTATION_RATE; +import static dr.evomodelxml.substmodel.HKYParser.KAPPA; + /** * @author Marc A. Suchard */ @@ -59,7 +60,7 @@ public void testTiny() { //substitutionModel Parameter freqs = new Parameter.Default(new double[]{0.25, 0.25, 0.25, 0.25}); - Parameter kappa = new Parameter.Default(HKYParser.KAPPA, 1.0, 0, 100); + Parameter kappa = new Parameter.Default(KAPPA, 1.0, 0, 100); FrequencyModel f = new FrequencyModel(Nucleotides.INSTANCE, freqs); HKY hky = new HKY(kappa, f); @@ -67,7 +68,7 @@ public void testTiny() { double alpha = 0.5; GammaSiteRateModel siteRateModel = new GammaSiteRateModel("gammaModel", alpha, 4); siteRateModel.setSubstitutionModel(hky); - Parameter mu = new Parameter.Default(GammaSiteModelParser.MUTATION_RATE, 1.0, 0, Double.POSITIVE_INFINITY); + Parameter mu = new Parameter.Default(MUTATION_RATE, 1.0, 0, Double.POSITIVE_INFINITY); siteRateModel.setRelativeRateParameter(mu); // @todo update to use latest beagle diff --git a/src/test/dr/evomodel/alloppnet/speciation/AlloppSpeciesNetworkModelTEST.java b/src/test/dr/evomodel/alloppnet/speciation/AlloppSpeciesNetworkModelTEST.java deleted file mode 100644 index 0e5fe41057..0000000000 --- a/src/test/dr/evomodel/alloppnet/speciation/AlloppSpeciesNetworkModelTEST.java +++ /dev/null @@ -1,254 +0,0 @@ -/* - * AlloppSpeciesNetworkModelTEST.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package test.dr.evomodel.alloppnet.speciation; - -import dr.evomodel.alloppnet.speciation.AlloppMulLabTree; -import dr.evomodel.alloppnet.speciation.AlloppSpeciesBindings; -import dr.evomodel.alloppnet.speciation.AlloppSpeciesBindings.ApSpInfo; -import dr.math.MathUtils; -import dr.math.distributions.GammaDistribution; -import org.junit.Before; -import org.junit.Test; -import dr.evomodel.alloppnet.speciation.AlloppSpeciesBindings.Individual; -import dr.evomodel.alloppnet.speciation.AlloppSpeciesNetworkModel; - - - -import static org.junit.Assert.assertEquals; - - -/** - * - * @author Graham Jones - * Date: 01/06/2011 - */ - - -public class AlloppSpeciesNetworkModelTEST { - - @Before - public void setUp() throws Exception { - } - - - - - @Test - public void testAlloppSpeciesNetworkModel() { - - //testGammaQuantile(); - testNetworkToMulLabTree(); - testLhoodMulLabTree(); - // grjtodo-soon would like a test of gene tree in network compatibility. - } - - - /* - * ****************** TESTING MulLabTree conversion ****************** - * - */ - - - // trying to reproduce weird bug when quantile returned 4.9e-324 - public void testGammaQuantile() { - MathUtils.setSeed(42); - for (int i = 0; i < 1000000; i++) { - double s = MathUtils.uniform(.999, 1.001); - double b = MathUtils.uniform(6e-5, 7e-5); - final GammaDistribution gamma = new GammaDistribution(s,b); - double q = MathUtils.uniform(3e-7, 4e-7); - double x = gamma.quantile(q); - assert x > 1e-20; - } - } - - - public void testNetworkToMulLabTree() { - ApSpInfo[] apspecies = new ApSpInfo[5]; - apspecies[0] = new ApSpInfo("a", 2, new Individual[0]); - apspecies[1] = new ApSpInfo("b", 4, new Individual[0]); - apspecies[2] = new ApSpInfo("c", 4, new Individual[0]); - apspecies[3] = new ApSpInfo("d", 4, new Individual[0]); - apspecies[4] = new ApSpInfo("e", 2, new Individual[0]); - - AlloppSpeciesBindings testASB = new AlloppSpeciesBindings(apspecies); - AlloppSpeciesNetworkModel testASNM = new AlloppSpeciesNetworkModel(testASB); - - System.out.println("Tests of Network To MulLabTree conversion with dips a,e and tets b,c,d"); - String newick; - newick = testASNM.testExampleNetworkToMulLabTree(1); - System.out.println(newick + "\n\n"); - assertEquals(0, newick.compareTo("((((b0,c0),d0),a),(((b1,c1),d1),e))")); - newick = testASNM.testExampleNetworkToMulLabTree(2); - System.out.println(newick + "\n\n"); - assertEquals(0, newick.compareTo("(((((b0,c0),d0),a),((b1,c1),d1)),e)")); - newick = testASNM.testExampleNetworkToMulLabTree(3); - System.out.println(newick + "\n\n"); - assertEquals(0, newick.compareTo("(((((b0,c0),d0),((b1,c1),d1)),a),e)")); - newick = testASNM.testExampleNetworkToMulLabTree(4); - System.out.println(newick + "\n\n"); - assertEquals(0, newick.compareTo("((((b0,c0),a),(d0,d1)),((b1,c1),e))")); - newick = testASNM.testExampleNetworkToMulLabTree(5); - System.out.println(newick + "\n\n"); - assertEquals(0, newick.compareTo("(((((a,b0),c0),c1),(d0,d1)),(b1,e))")); - System.out.println(""); - System.out.println(""); - } - - - public void testLhoodMulLabTree() { - ApSpInfo[] apspecies = new ApSpInfo[3]; - apspecies[0] = new ApSpInfo("a", 2, new Individual[0]); - apspecies[1] = new ApSpInfo("b", 2, new Individual[0]); - apspecies[2] = new ApSpInfo("z", 4, new Individual[0]); - - AlloppSpeciesBindings testASB = new AlloppSpeciesBindings(apspecies); - AlloppMulLabTree testamlt = new AlloppMulLabTree(testASB); - double llhood = testamlt.testGeneTreeInMULTreeLogLikelihood(); - assertEquals(llhood, -13.562218135041552713, 1e-10); - System.out.println(llhood); - } - - - /* This R code produces -13.562218135041552713 - -# 0 2 3 1 -# a z0 z1 b b' -# | # | # | # | | -# | # | + | # | | hyb 0.005 -# | 4 | # | # | | (a,z0) in multree 0.01 -# \ / # | # | | -# v # | # | | (a,z0) in gene tree 0.015 -# | # | 5 | | (z1,b) in multree 0.02 -# | # \ / / -# | # v / (z1,b) in gene tree 0.025 -# | # | | -# \ # / / -# | 6 | | root multree 0.03 -# | |/ (z1,b),b' 0.035 -# | / -# \ / -# v root gene tree 0.045 -# | - - -# here, numbers 1-9 show branch or part-branch indices -# a z0 z1 b b' -# | # 2 # 3 # | | -# 1 # | + | # | | hyb 0.005 -# | # 4 # 5 # |6| (a,z0) in multree 0.01 -# \ / # | # | | -# v # | # | | (a,z0) in gene tree 0.015 -# | # | # | | (z1,b) in multree 0.02 -# | # \ / / -# 7| # v / (z1,b) in gene tree 0.025 -# | # 8| | -# \ # / / -# | # | | root multree 0.03 -# | |/ (z1,b),b' 0.035 -# | 9 / -# \ / -# v root gene tree 0.045 -# | - - - - -brs <- matrix(0, nrow=9, ncol=3) -tms <- matrix(0, nrow=9, ncol=4) -brs[1,] <- c(.003, .001, 1); tms[1,] <- c(.0, .01, -1,-1) -brs[2,] <- c(.003, .001, 1); tms[2,] <- c(.00, .005, -1,-1) -brs[3,] <- c(.003, .001, 1); tms[3,] <- c(.00, .005, -1,-1) -brs[4,] <- c(.001, .001, 1); tms[4,] <- c(.005, .01, -1,-1) -brs[5,] <- c(.001, .001, 1); tms[5,] <- c(.005, .01, -1,-1) -brs[6,] <- c(.003, .001, 2); tms[6,] <- c(.0, .02, -1,-1) -brs[7,] <- c(.002, .001, 2); tms[7,] <- c(.01, .015, .03, -1) -brs[8,] <- c(.002, .001, 3); tms[8,] <- c(.02, .025, .03, -1) -brs[9,] <- c(.002, .002, 3); tms[9,] <- c(.03, .035, .045, 999) - - - -branchllhood <- function(b, tm) { - llhood <- 0 - tm <- tm[tm>=0] - tm <- tm - tm[1] - k <- length(tm) - n <- b[3] - p0 <- b[1] - pk <- b[2] - for (i in 1:(k-1)) { - pi0 <- linear.interp.pop(tm[1], tm[k], p0, pk, tm[i]) - pi1 <- linear.interp.pop(tm[1], tm[k], p0, pk, tm[i+1]) - if (i < k-1) { - x <- onecoalllhood(n, tm[i], tm[i+1], pi0, pi1) - n <- n-1 - } else { - x <- nocoalllhood(n, tm[i], tm[i+1], pi0, pi1) - } - llhood <- llhood + x - } - llhood - } - -linear.interp.pop <- function(t0, t1, p0, p1, x) -{ -(p0*(t1-x) + p1*(x-t0))/(t1-t0) -} - -onecoalllhood <- function(n, t0, t1, p0, p1) { - x <- -log(p1) - integrate(pop.integrand, n=n, t0=t0, t1=t1, p0=p0, p1=p1, lower=t0, upper=t1)$value - cat("onecoalllhood", "n", n, "t0", t0, "t1", t1, "p0", p0, "p1", p1, "llhood", x, "\n") - x - } - - -nocoalllhood <- function(n, t0, t1, p0, p1) { - x <- - integrate(pop.integrand, n=n, t0=t0, t1=t1, p0=p0, p1=p1, lower=t0, upper=t1)$value - cat("nocoalllhood", "n", n, "t0", t0, "t1", t1, "p0", p0, "p1", p1, "llhood", x, "\n") - x - } - - -pop.integrand <- function(x, n, t0, t1, p0, p1) -{ -(n*(n-1)/2) * (t1-t0) / (p0*(t1-x) + p1*(x-t0)) -} - - -llhood <- 0 -for (i in 1:dim(brs)[1]) { - x <- branchllhood(brs[i,], tms[i,]) - cat("branch", i, "llhood", x, "\n") - llhood <- llhood + x - } -llhood - - */ - -} - diff --git a/src/test/dr/evomodel/arg/operators/ARGAddRemoveOperatorTest.java b/src/test/dr/evomodel/arg/operators/ARGAddRemoveOperatorTest.java deleted file mode 100644 index 03e9950772..0000000000 --- a/src/test/dr/evomodel/arg/operators/ARGAddRemoveOperatorTest.java +++ /dev/null @@ -1,229 +0,0 @@ -/* - * ARGAddRemoveOperatorTest.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package test.dr.evomodel.arg.operators; - -import dr.evolution.io.Importer; -import dr.evolution.io.NewickImporter; -import dr.evomodel.arg.ARGLogger; -import dr.evomodel.arg.ARGModel; -import dr.evomodel.arg.ARGReassortmentNodeCountStatistic; -import dr.evomodel.arg.coalescent.ARGUniformPrior; -import dr.evomodelxml.tree.TreeModelParser; -import dr.inference.distribution.DistributionLikelihood; -import dr.inference.loggers.ArrayLogFormatter; -import dr.inference.loggers.MCLogger; -import dr.inference.loggers.TabDelimitedFormatter; -import dr.inference.mcmc.MCMC; -import dr.inference.mcmc.MCMCOptions; -import dr.inference.model.CompoundLikelihood; -import dr.inference.model.CompoundParameter; -import dr.inference.model.Likelihood; -import dr.inference.operators.AdaptationMode; -import dr.inference.operators.OperatorSchedule; -import dr.inference.operators.ScaleOperator; -import dr.inference.operators.SimpleOperatorSchedule; -import dr.inference.trace.ArrayTraceList; -import dr.inference.trace.Trace; -import dr.inference.trace.TraceCorrelation; -import dr.math.distributions.GammaDistribution; -import dr.math.distributions.PoissonDistribution; -import test.dr.inference.trace.TraceCorrelationAssert; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -/** - * @author Marc Suchard - */ - -public class ARGAddRemoveOperatorTest extends TraceCorrelationAssert { - - public ARGAddRemoveOperatorTest(String name) { - super(name); - } - - public void setUp() throws Exception { - super.setUp(); - - NewickImporter importer = new NewickImporter( - "(((A:1.0,B:1.0):1.0,C:2.0):1.0,D:3.0);"); - arg4 = new ARGModel(importer.importTree(null)); - arg4.setupHeightBounds(); - arg4.addLikelihoodCalculator(null); - arg4.addLikelihoodCalculator(null); - - importer = new NewickImporter( - "((((A:1.0,B:1.0):1.0,C:2.0):1.0,D:3.0):1.0, E:4.0);"); - ARGModel arg5 = new ARGModel(importer.importTree(null)); - - importer = new NewickImporter( - "(((((A:1.0,B:1.0):1.0,C:2.0):1.0,D:3.0):1.0, E:4.0),F:5.0);"); - ARGModel arg6 = new ARGModel(importer.importTree(null)); - } - - // 4 taxa args - public void testFlatPrior4() throws IOException, Importer.ImportException { - flatPriorTester(arg4, 2000000, 1000, 2.0, 100.0, 0.5, 3); - } - - private void flatPriorTester(ARGModel arg, int chainLength, int sampleTreeEvery, - double nodeCountSetting, double rootHeightAlpha, double rootHeightBeta, int maxCount) - throws IOException, Importer.ImportException { - - MCMC mcmc = new MCMC("mcmc1"); - MCMCOptions options = new MCMCOptions(chainLength); - -// double nodeCountSetting = 2.0; -// double rootHeightAlpha = 100; -// double rootHeightBeta = 0.5; - - OperatorSchedule schedule = getSchedule(arg); - - ARGUniformPrior uniformPrior = new ARGUniformPrior(arg, maxCount, arg.getExternalNodeCount()); - - PoissonDistribution poisson = new PoissonDistribution(nodeCountSetting); - - DistributionLikelihood nodeCountPrior = new DistributionLikelihood(poisson, 0.0); - ARGReassortmentNodeCountStatistic nodeCountStatistic = new ARGReassortmentNodeCountStatistic("nodeCount", arg); - nodeCountPrior.addData(nodeCountStatistic); - - DistributionLikelihood rootPrior = new DistributionLikelihood(new GammaDistribution(rootHeightAlpha, rootHeightBeta), 0.0); - CompoundParameter rootHeight = (CompoundParameter) arg.createNodeHeightsParameter(true, false, false); - rootPrior.addData(rootHeight); - - List likelihoods = new ArrayList(); - likelihoods.add(uniformPrior); - likelihoods.add(rootPrior); - likelihoods.add(nodeCountPrior); - - CompoundLikelihood compoundLikelihood = new CompoundLikelihood(1, likelihoods); - compoundLikelihood.setId("likelihood1"); - - MCLogger[] loggers = new MCLogger[3]; - - loggers[0] = new MCLogger(new TabDelimitedFormatter(System.out), 10000, false); - loggers[0].add(compoundLikelihood); - loggers[0].add(arg); - - File file = new File("test.args"); - file.deleteOnExit(); - FileOutputStream out = new FileOutputStream(file); - - loggers[1] = new ARGLogger(arg, new TabDelimitedFormatter(out), sampleTreeEvery, "test"); - - ArrayLogFormatter formatter = new ArrayLogFormatter(false); - - loggers[2] = new MCLogger(formatter, sampleTreeEvery, false); - loggers[2].add(arg); - arg.getRootHeightParameter().setId("root"); - loggers[2].add(arg.getRootHeightParameter()); - - mcmc.setShowOperatorAnalysis(true); - - mcmc.init(options, compoundLikelihood, schedule, loggers); - - mcmc.run(); - out.flush(); - out.close(); - - List traces = formatter.getTraces(); - -// Set uniqueTrees = new HashSet(); -// -// NexusImporter importer = new NexusImporter(new FileReader(file)); -// while (importer.hasTree()) { -// Tree t = importer.importNextTree(); -// uniqueTrees.add(Tree.Utils.uniqueNewick(t, t.getRoot())); -// } -// -// TestCase.assertEquals(numTopologies, uniqueTrees.size()); List traces = formatter.getTraces(); - - ArrayTraceList traceList = new ArrayTraceList("ARGTest", traces, 0); - - for (int i = 1; i < traces.size(); i++) { - traceList.analyseTrace(i); - } - - TraceCorrelation nodeCountStats = traceList.getCorrelationStatistics(1); - TraceCorrelation rootHeightStats = traceList.getCorrelationStatistics(4); - - assertExpectation("nodeCount", nodeCountStats, poisson.truncatedMean(maxCount)); - assertExpectation(TreeModelParser.ROOT_HEIGHT, rootHeightStats, rootHeightAlpha * rootHeightBeta); - - } - - public static OperatorSchedule getSchedule(ARGModel arg) { - - CompoundParameter rootHeight = (CompoundParameter) arg.createNodeHeightsParameter(true, false, false); - CompoundParameter internalHeights = (CompoundParameter) arg.createNodeHeightsParameter(false, true, false); - //CompoundParameter allInternalNodeHeights = (CompoundParameter) arg.createNodeHeightsParameter(true, true, false); -// CompoundParameter rates = (CompoundParameter) arg.createNodeRatesParameter(false, true, true); - -// ARGAddRemoveEventOperator operator1 = new ARGAddRemoveEventOperator(arg, 5, 0.5, -// AdaptationMode.ADAPTATION_ON, internalHeights, allInternalNodeHeights, rates, 0.9, null,-1); - - ScaleOperator operator2 = new ScaleOperator(rootHeight, 0.75, AdaptationMode.ADAPTATION_ON, 5); - ScaleOperator operator3 = new ScaleOperator(internalHeights, 0.75, AdaptationMode.ADAPTATION_ON, 10); - - OperatorSchedule schedule = new SimpleOperatorSchedule(); -// schedule.addOperator(operator1); - schedule.addOperator(operator2); - schedule.addOperator(operator3); - - return schedule; - -// -// -// -// -// -// -// - -// -// -// -// -// -// -// -// -// -// -// -// - } - - - private ARGModel arg4; -} diff --git a/src/test/dr/evomodel/branchratemodel/RandomLocalClockTestProblem.java b/src/test/dr/evomodel/branchratemodel/RandomLocalClockTestProblem.java deleted file mode 100644 index ce81557de8..0000000000 --- a/src/test/dr/evomodel/branchratemodel/RandomLocalClockTestProblem.java +++ /dev/null @@ -1,298 +0,0 @@ -/* - * RandomLocalClockTestProblem.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package test.dr.evomodel.branchratemodel; - -import dr.evolution.alignment.SitePatterns; -import dr.evolution.datatype.Nucleotides; -import dr.evomodel.branchratemodel.RandomLocalClockModel; -import dr.evomodel.coalescent.CoalescentLikelihood; -import dr.evomodel.coalescent.demographicmodel.ConstantPopulationModel; -import dr.evomodel.coalescent.TreeIntervals; -import dr.evomodel.operators.ExchangeOperator; -import dr.evomodel.operators.SubtreeSlideOperator; -import dr.evomodel.operators.WilsonBalding; -import dr.evomodel.tree.DefaultTreeModel; -import dr.oldevomodel.sitemodel.GammaSiteModel; -import dr.oldevomodel.substmodel.FrequencyModel; -import dr.oldevomodel.substmodel.HKY; -import dr.evomodel.tree.RateCovarianceStatistic; -import dr.evomodel.tree.RateStatistic; -import dr.oldevomodel.treelikelihood.TreeLikelihood; -import dr.evomodelxml.branchratemodel.RandomLocalClockModelParser; -import dr.evomodelxml.coalescent.demographicmodel.ConstantPopulationModelParser; -import dr.oldevomodelxml.sitemodel.GammaSiteModelParser; -import dr.oldevomodelxml.substmodel.HKYParser; -import dr.evomodelxml.tree.RateStatisticParser; -import dr.oldevomodelxml.treelikelihood.TreeLikelihoodParser; -import dr.inference.distribution.DistributionLikelihood; -import dr.inference.loggers.ArrayLogFormatter; -import dr.inference.loggers.MCLogger; -import dr.inference.loggers.TabDelimitedFormatter; -import dr.inference.mcmc.MCMC; -import dr.inference.mcmc.MCMCOptions; -import dr.inference.model.*; -import dr.inference.operators.*; -import dr.inference.trace.ArrayTraceList; -import dr.inference.trace.Trace; -import dr.inference.trace.TraceCorrelation; -import dr.inferencexml.model.CompoundLikelihoodParser; -import dr.math.MathUtils; -import dr.math.distributions.GammaDistribution; -import dr.math.distributions.PoissonDistribution; -import junit.framework.Test; -import junit.framework.TestSuite; -import test.dr.inference.trace.TraceCorrelationAssert; - -import java.util.ArrayList; -import java.util.List; - -/** - * @author Walter Xie - * convert testRandomLocalClock.xml in the folder /example - * the Random Local Clock model has problem - */ - -public class RandomLocalClockTestProblem extends TraceCorrelationAssert { - - public RandomLocalClockTestProblem(String name) { - super(name); - } - - public void setUp() throws Exception { - super.setUp(); - - MathUtils.setSeed(666); - - createAlignment(PRIMATES_TAXON_SEQUENCE, Nucleotides.INSTANCE); - } - - - public void testRandomLocalClock() throws Exception { - Parameter popSize = new Parameter.Default(ConstantPopulationModelParser.POPULATION_SIZE, 0.077, 0, Double.POSITIVE_INFINITY); - ConstantPopulationModel constantModel = createRandomInitialTree(popSize); - - TreeIntervals intervalList = new TreeIntervals(treeModel, null, null); - CoalescentLikelihood coalescent = new CoalescentLikelihood(intervalList, constantModel); - coalescent.setId("coalescent"); - - // clock model - Parameter ratesParameter = new Parameter.Default(RandomLocalClockModelParser.RATES, 10, 1); - Parameter rateIndicatorParameter = new Parameter.Default(RandomLocalClockModelParser.RATE_INDICATORS, 10, 1); - Parameter meanRateParameter = new Parameter.Default(RandomLocalClockModelParser.CLOCK_RATE, 1, 1.0); - - RandomLocalClockModel branchRateModel = new RandomLocalClockModel(treeModel, meanRateParameter, - rateIndicatorParameter, ratesParameter, false, 0.5); - - SumStatistic rateChanges = new SumStatistic("rateChangeCount", true, null); - rateChanges.addStatistic(rateIndicatorParameter); - - RateStatistic meanRate = new RateStatistic("meanRate", treeModel, branchRateModel, true, true, RateStatisticParser.MEAN); - RateStatistic coefficientOfVariation = new RateStatistic(RateStatisticParser.COEFFICIENT_OF_VARIATION, treeModel, branchRateModel, - true, true, RateStatisticParser.COEFFICIENT_OF_VARIATION); - RateCovarianceStatistic covariance = new RateCovarianceStatistic("covariance", treeModel, branchRateModel); - - // Sub model - Parameter freqs = new Parameter.Default(alignment.getStateFrequencies()); - Parameter kappa = new Parameter.Default(HKYParser.KAPPA, 1.0, 0, Double.POSITIVE_INFINITY); - - FrequencyModel f = new FrequencyModel(Nucleotides.INSTANCE, freqs); - HKY hky = new HKY(kappa, f); - - //siteModel - GammaSiteModel siteModel = new GammaSiteModel(hky); - Parameter mu = new Parameter.Default(GammaSiteModelParser.MUTATION_RATE, 1.0, 0, Double.POSITIVE_INFINITY); - siteModel.setMutationRateParameter(mu); - - //treeLikelihood - SitePatterns patterns = new SitePatterns(alignment, null, 0, -1, 1, true); - - TreeLikelihood treeLikelihood = new TreeLikelihood(patterns, treeModel, siteModel, branchRateModel, null, - false, false, true, false, false); - treeLikelihood.setId(TreeLikelihoodParser.TREE_LIKELIHOOD); - - // Operators - OperatorSchedule schedule = new SimpleOperatorSchedule(); - - MCMCOperator operator = new ScaleOperator(kappa, 0.75); - operator.setWeight(1.0); - schedule.addOperator(operator); - - operator = new ScaleOperator(ratesParameter, 0.75); - operator.setWeight(10.0); - schedule.addOperator(operator); - - operator = new BitFlipOperator(rateIndicatorParameter, 15.0, true); - schedule.addOperator(operator); - - operator = new ScaleOperator(popSize, 0.75); - operator.setWeight(3.0); - schedule.addOperator(operator); - - Parameter rootHeight = ((DefaultTreeModel)treeModel).getRootHeightParameter(); - rootHeight.setId(TREE_HEIGHT); - operator = new ScaleOperator(rootHeight, 0.75); - operator.setWeight(3.0); - schedule.addOperator(operator); - - Parameter internalHeights = ((DefaultTreeModel)treeModel).createNodeHeightsParameter(false, true, false); - operator = new UniformOperator(internalHeights, 30.0); - schedule.addOperator(operator); - - operator = new SubtreeSlideOperator(((DefaultTreeModel)treeModel), 15.0, 0.0077, true, false, false, false, AdaptationMode.ADAPTATION_ON, AdaptableMCMCOperator.DEFAULT_ADAPTATION_TARGET); - schedule.addOperator(operator); - - operator = new ExchangeOperator(ExchangeOperator.NARROW, treeModel, 15.0); -// operator.doOperation(); - schedule.addOperator(operator); - - operator = new ExchangeOperator(ExchangeOperator.WIDE, treeModel, 3.0); -// operator.doOperation(); - schedule.addOperator(operator); - - operator = new WilsonBalding(treeModel, 3.0); -// operator.doOperation(); - schedule.addOperator(operator); - - //CompoundLikelihood - OneOnXPrior likelihood1 = new OneOnXPrior(); - likelihood1.addData(popSize); - OneOnXPrior likelihood2 = new OneOnXPrior(); - likelihood2.addData(kappa); - DistributionLikelihood likelihood3 = new DistributionLikelihood(new GammaDistribution(0.5, 2.0), 0.0); - likelihood3.addData(ratesParameter); - DistributionLikelihood likelihood4 = new DistributionLikelihood(new PoissonDistribution(1.0), 0.0); - likelihood4.addData(rateChanges); - - List likelihoods = new ArrayList(); - likelihoods.add(likelihood1); - likelihoods.add(likelihood2); - likelihoods.add(likelihood3); - likelihoods.add(likelihood4); - likelihoods.add(coalescent); - Likelihood prior = new CompoundLikelihood(0, likelihoods); - prior.setId(CompoundLikelihoodParser.PRIOR); - - likelihoods.clear(); - likelihoods.add(treeLikelihood); - Likelihood likelihood = new CompoundLikelihood(-1, likelihoods); - - likelihoods.clear(); - likelihoods.add(prior); - likelihoods.add(likelihood); - Likelihood posterior = new CompoundLikelihood(0, likelihoods); - posterior.setId(CompoundLikelihoodParser.POSTERIOR); - - // Log - ArrayLogFormatter formatter = new ArrayLogFormatter(false); - - MCLogger[] loggers = new MCLogger[2]; - loggers[0] = new MCLogger(formatter, 1000, false); - loggers[0].add(posterior); - loggers[0].add(prior); - loggers[0].add(treeLikelihood); - loggers[0].add(rootHeight); - loggers[0].add(kappa); -// loggers[0].add(meanRate); - loggers[0].add(rateChanges); - loggers[0].add(coefficientOfVariation); - loggers[0].add(covariance); - loggers[0].add(popSize); - loggers[0].add(coalescent); - - loggers[1] = new MCLogger(new TabDelimitedFormatter(System.out), 10000, false); - loggers[1].add(posterior); - loggers[1].add(treeLikelihood); - loggers[1].add(rootHeight); - loggers[1].add(meanRate); - loggers[1].add(rateChanges); - - // MCMC - MCMC mcmc = new MCMC("mcmc1"); - MCMCOptions options = new MCMCOptions(1000000); - - mcmc.setShowOperatorAnalysis(true); - mcmc.init(options, posterior, schedule, loggers); - mcmc.run(); - - // time - System.out.println(mcmc.getTimer().toString()); - - // Tracer - List traces = formatter.getTraces(); - ArrayTraceList traceList = new ArrayTraceList("RandomLocalClockTest", traces, 0); - - for (int i = 1; i < traces.size(); i++) { - traceList.analyseTrace(i); - } - -// -// -// -// -// -// -// -// covariance 0.47952 -// -// - - TraceCorrelation likelihoodStats = traceList.getCorrelationStatistics(traceList.getTraceIndex(CompoundLikelihoodParser.POSTERIOR)); - assertExpectation(CompoundLikelihoodParser.POSTERIOR, likelihoodStats, -1818.26); - - likelihoodStats = traceList.getCorrelationStatistics(traceList.getTraceIndex(CompoundLikelihoodParser.PRIOR)); - assertExpectation(CompoundLikelihoodParser.PRIOR, likelihoodStats, -2.70143); - - likelihoodStats = traceList.getCorrelationStatistics(traceList.getTraceIndex(TreeLikelihoodParser.TREE_LIKELIHOOD)); - assertExpectation(TreeLikelihoodParser.TREE_LIKELIHOOD, likelihoodStats, -1815.56); - - TraceCorrelation treeHeightStats = traceList.getCorrelationStatistics(traceList.getTraceIndex(TREE_HEIGHT)); - assertExpectation(TREE_HEIGHT, treeHeightStats, 6.363E-2); - - TraceCorrelation kappaStats = traceList.getCorrelationStatistics(traceList.getTraceIndex(HKYParser.KAPPA)); - assertExpectation(HKYParser.KAPPA, kappaStats, 30.0394); - - TraceCorrelation rateChangeStats = traceList.getCorrelationStatistics(traceList.getTraceIndex("rateChangeCount")); - assertExpectation("rateChangeCount", rateChangeStats, 0.40786); - - TraceCorrelation coefficientOfVariationStats = traceList.getCorrelationStatistics(traceList.getTraceIndex(RateStatisticParser.COEFFICIENT_OF_VARIATION)); - assertExpectation(RateStatisticParser.COEFFICIENT_OF_VARIATION, coefficientOfVariationStats, 7.02408E-2); - - TraceCorrelation covarianceStats = traceList.getCorrelationStatistics(traceList.getTraceIndex("covariance")); - assertExpectation("covariance", covarianceStats, 0.47952); - - TraceCorrelation popStats = traceList.getCorrelationStatistics(traceList.getTraceIndex(ConstantPopulationModelParser.POPULATION_SIZE)); - assertExpectation(ConstantPopulationModelParser.POPULATION_SIZE, popStats, 9.67405E-2); - - TraceCorrelation coalescentStats = traceList.getCorrelationStatistics(traceList.getTraceIndex("coalescent")); - assertExpectation("coalescent", coalescentStats, 7.29521); - } - - public static Test suite() { - return new TestSuite(RandomLocalClockTestProblem.class); - } -} diff --git a/src/test/dr/evomodel/branchratemodel/StrictClockTest.java b/src/test/dr/evomodel/branchratemodel/StrictClockTest.java index e343eeb28e..853ef06892 100644 --- a/src/test/dr/evomodel/branchratemodel/StrictClockTest.java +++ b/src/test/dr/evomodel/branchratemodel/StrictClockTest.java @@ -29,6 +29,7 @@ import dr.evolution.alignment.SitePatterns; import dr.evolution.datatype.Nucleotides; +import dr.evomodel.branchmodel.HomogeneousBranchModel; import dr.evomodel.branchratemodel.StrictClockBranchRates; import dr.evomodel.coalescent.CoalescentLikelihood; import dr.evomodel.coalescent.demographicmodel.ConstantPopulationModel; @@ -36,15 +37,17 @@ import dr.evomodel.operators.ExchangeOperator; import dr.evomodel.operators.SubtreeSlideOperator; import dr.evomodel.operators.WilsonBalding; +import dr.evomodel.siteratemodel.DiscretizedSiteRateModel; +import dr.evomodel.siteratemodel.SiteRateModel; +import dr.evomodel.substmodel.FrequencyModel; +import dr.evomodel.substmodel.nucleotide.HKY; import dr.evomodel.tree.DefaultTreeModel; -import dr.oldevomodel.sitemodel.GammaSiteModel; -import dr.oldevomodel.substmodel.FrequencyModel; -import dr.oldevomodel.substmodel.HKY; -import dr.oldevomodel.treelikelihood.TreeLikelihood; +import dr.evomodel.treedatalikelihood.BeagleDataLikelihoodDelegate; +import dr.evomodel.treedatalikelihood.PreOrderSettings; +import dr.evomodel.treedatalikelihood.TreeDataLikelihood; +import dr.evomodel.treelikelihood.PartialsRescalingScheme; import dr.evomodelxml.coalescent.demographicmodel.ConstantPopulationModelParser; -import dr.oldevomodelxml.sitemodel.GammaSiteModelParser; -import dr.oldevomodelxml.substmodel.HKYParser; -import dr.oldevomodelxml.treelikelihood.TreeLikelihoodParser; +import dr.evomodelxml.substmodel.HKYParser; import dr.inference.loggers.ArrayLogFormatter; import dr.inference.loggers.MCLogger; import dr.inference.loggers.TabDelimitedFormatter; @@ -66,6 +69,9 @@ import java.util.ArrayList; import java.util.List; +import static dr.evomodelxml.substmodel.HKYParser.*; +import static dr.evomodelxml.treelikelihood.BeagleTreeLikelihoodParser.TREE_LIKELIHOOD; + /** * @author Walter Xie * convert testStrictClock.xml in the folder /example @@ -100,22 +106,23 @@ public void testStrictClock() throws Exception { // Sub model Parameter freqs = new Parameter.Default(alignment.getStateFrequencies()); - Parameter kappa = new Parameter.Default(HKYParser.KAPPA, 1.0, 0, 100.0); + Parameter kappa = new Parameter.Default(KAPPA, 1.0, 0, 100.0); FrequencyModel f = new FrequencyModel(Nucleotides.INSTANCE, freqs); HKY hky = new HKY(kappa, f); - //siteModel - GammaSiteModel siteModel = new GammaSiteModel(hky); - Parameter mu = new Parameter.Default(GammaSiteModelParser.MUTATION_RATE, 1.0, 0, Double.POSITIVE_INFINITY); - siteModel.setMutationRateParameter(mu); + SiteRateModel siteRateModel = new DiscretizedSiteRateModel(""); //treeLikelihood SitePatterns patterns = new SitePatterns(alignment, null, 0, -1, 1, true); - TreeLikelihood treeLikelihood = new TreeLikelihood(patterns, treeModel, siteModel, branchRateModel, null, - false, false, true, false, false); - treeLikelihood.setId(TreeLikelihoodParser.TREE_LIKELIHOOD); + TreeDataLikelihood treeLikelihood = new TreeDataLikelihood( + new BeagleDataLikelihoodDelegate(treeModel, patterns, + new HomogeneousBranchModel(hky), siteRateModel, true, + false, PartialsRescalingScheme.DEFAULT, false, PreOrderSettings.getDefault()), + treeModel, null + ); + treeLikelihood.setId(TREE_LIKELIHOOD); // Operators OperatorSchedule schedule = new SimpleOperatorSchedule(); @@ -228,14 +235,14 @@ public void testStrictClock() throws Exception { TraceCorrelation likelihoodStats = traceList.getCorrelationStatistics(traceList.getTraceIndex(CompoundLikelihoodParser.POSTERIOR)); assertExpectation(CompoundLikelihoodParser.POSTERIOR, likelihoodStats, -3928.71); - likelihoodStats = traceList.getCorrelationStatistics(traceList.getTraceIndex(TreeLikelihoodParser.TREE_LIKELIHOOD)); - assertExpectation(TreeLikelihoodParser.TREE_LIKELIHOOD, likelihoodStats, -3856.59); + likelihoodStats = traceList.getCorrelationStatistics(traceList.getTraceIndex(TREE_LIKELIHOOD)); + assertExpectation(TREE_LIKELIHOOD, likelihoodStats, -3856.59); TraceCorrelation treeHeightStats = traceList.getCorrelationStatistics(traceList.getTraceIndex(TREE_HEIGHT)); assertExpectation(TREE_HEIGHT, treeHeightStats, 69.0580); - TraceCorrelation kappaStats = traceList.getCorrelationStatistics(traceList.getTraceIndex(HKYParser.KAPPA)); - assertExpectation(HKYParser.KAPPA, kappaStats, 18.2782); + TraceCorrelation kappaStats = traceList.getCorrelationStatistics(traceList.getTraceIndex(KAPPA)); + assertExpectation(KAPPA, kappaStats, 18.2782); TraceCorrelation rateStats = traceList.getCorrelationStatistics(traceList.getTraceIndex(StrictClockBranchRates.RATE)); assertExpectation(StrictClockBranchRates.RATE, rateStats, 8.04835E-4); diff --git a/src/test/dr/evomodel/sitemodel/testGammaSiteBMA.java b/src/test/dr/evomodel/sitemodel/testGammaSiteBMA.java deleted file mode 100644 index efe1dabfbf..0000000000 --- a/src/test/dr/evomodel/sitemodel/testGammaSiteBMA.java +++ /dev/null @@ -1,289 +0,0 @@ -/* - * testGammaSiteBMA.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package test.dr.evomodel.sitemodel; - -import junit.framework.TestCase; -import dr.inference.model.Variable; -import dr.inference.model.Parameter; -import dr.oldevomodel.substmodel.SubstitutionModel; -import dr.oldevomodel.substmodel.FrequencyModel; -import dr.oldevomodel.substmodel.HKY; -import dr.oldevomodel.sitemodel.GammaSiteBMA; -import dr.evolution.datatype.Nucleotides; - -/** - * @author Chieh-Hsi Wu - * - */ -public class testGammaSiteBMA extends TestCase { - interface Instance { - SubstitutionModel getSubstModel (); - - double getMu(); - - double getLogitInvar(); - - double getLogShape(); - - int getCategoryCount(); - - Variable getModelChoose(); - - double[] getCategoryRates(); - - double[] getCategoryProportions(); - } - - //Neither gamma shape nor site invariant parameters is included. - Instance test0 = new Instance(){ - public SubstitutionModel getSubstModel (){ - - //Create a JC model - Parameter kappa = new Parameter.Default(1, 1); - double[] pi = new double[]{0.25, 0.25, 0.25, 0.25}; - - Parameter freqs = new Parameter.Default(pi); - FrequencyModel f = new FrequencyModel(Nucleotides.INSTANCE, freqs); - HKY jc = new HKY(kappa, f); - return jc; - } - - public double getMu(){ - return 1.5; - } - - - public double getLogitInvar(){ - //The invariant site proportion, p = 0.2. - return -1.38629436112; - } - - public double getLogShape(){ - //Gamma shape parameter, alpha = 2. - return 0.69314718056; - } - - public int getCategoryCount(){ - return 4; - } - - public Variable getModelChoose(){ - return new Variable.I(new int[]{0, 0}); - } - - public double[] getCategoryRates(){ - return new double[]{0.0, 1.5, 1.5, 1.5, 1.5}; - } - - public double[] getCategoryProportions(){ - return new double[]{0, 0.25, 0.25, 0.25, 0.25}; - } - - }; - - //Neither gamma shape nor site invariant parameters is included. - Instance test1 = new Instance(){ - public SubstitutionModel getSubstModel (){ - - //Create a JC model - Parameter kappa = new Parameter.Default(1, 1); - double[] pi = new double[]{0.25, 0.25, 0.25, 0.25}; - - Parameter freqs = new Parameter.Default(pi); - FrequencyModel f = new FrequencyModel(Nucleotides.INSTANCE, freqs); - HKY jc = new HKY(kappa, f); - return jc; - } - - public double getMu(){ - return 1.5; - } - - - public double getLogitInvar(){ - //The invariant site proportion, p = 0.2. - return -1.38629436112; - } - - public double getLogShape(){ - //Gamma shape parameter, alpha = 2. - return 0.69314718056; - } - - public int getCategoryCount(){ - return 4; - } - - public Variable getModelChoose(){ - return new Variable.I(new int[]{0, 1}); - } - - public double[] getCategoryRates(){ - return new double[]{0.0, 1.875, 1.875, 1.875, 1.875}; - } - - public double[] getCategoryProportions(){ - return new double[]{0.2, 0.2, 0.2, 0.2, 0.2}; - } - - - }; - - //Neither gamma shape nor site invariant parameters is included. - Instance test2 = new Instance(){ - public SubstitutionModel getSubstModel (){ - - //Create a JC model - Parameter kappa = new Parameter.Default(1, 1); - double[] pi = new double[]{0.25, 0.25, 0.25, 0.25}; - - Parameter freqs = new Parameter.Default(pi); - FrequencyModel f = new FrequencyModel(Nucleotides.INSTANCE, freqs); - HKY jc = new HKY(kappa, f); - return jc; - } - - public double getMu(){ - return 1.5; - } - - - public double getLogitInvar(){ - //The invariant site proportion, p = 0.2. - return -1.38629436112; - } - - public double getLogShape(){ - //Gamma shape parameter, alpha = 2. - return 0.69314718056; - } - - public int getCategoryCount(){ - return 4; - } - - public Variable getModelChoose(){ - return new Variable.I(new int[]{1, 1}); - } - - public double[] getCategoryRates(){ - return new double[]{0.0, 0.59824693778, 1.28130225333, 2.07933195980, 3.54111884909}; - } - - public double[] getCategoryProportions(){ - return new double[]{0.2, 0.2, 0.2, 0.2, 0.2}; - } - }; - - - - Instance test3 = new Instance(){ - public SubstitutionModel getSubstModel (){ - - //Create a JC model - Parameter kappa = new Parameter.Default(1, 1); - double[] pi = new double[]{0.25, 0.25, 0.25, 0.25}; - - Parameter freqs = new Parameter.Default(pi); - FrequencyModel f = new FrequencyModel(Nucleotides.INSTANCE, freqs); - HKY jc = new HKY(kappa, f); - return jc; - } - - public double getMu(){ - return 1.5; - } - - - public double getLogitInvar(){ - //The invariant site proportion, p = 0.2. - return -1.38629436112; - } - - public double getLogShape(){ - //Gamma shape parameter, alpha = 2. - return 0.69314718056; - } - - public int getCategoryCount(){ - return 8; - } - - public Variable getModelChoose(){ - return new Variable.I(new int[]{1, 1}); - } - - public double[] getCategoryRates(){ - return new double[]{0.0, - 0.387224876120, 0.757770190732, 1.085824675833, 1.426031312891, - 1.810616868095, 2.285251426765, 2.955667305794, 4.291613343768}; - } - - public double[] getCategoryProportions(){ - return new double[]{0.2, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1}; - } - }; - Instance[] all = {test0,test1,test2,test3}; - public void testGammaSiteBMA(){ - - for(Instance test: all){ - SubstitutionModel substModel = test.getSubstModel(); - Parameter mu = new Parameter.Default(test.getMu()); - Parameter logitInvar = new Parameter.Default(test.getLogitInvar()); - Parameter logShape = new Parameter.Default(test.getLogShape()); - int catCount = test.getCategoryCount(); - Variable modelChoose = test.getModelChoose(); - GammaSiteBMA gammaSiteBMA = new GammaSiteBMA( - substModel, - mu, - logitInvar, - logShape, - catCount, - modelChoose - ); - - double[] catRates = gammaSiteBMA.getCategoryRates(); - double[] expectedCatRates = test.getCategoryRates(); - - for(int i = 0; i < catRates.length; i++){ - assertEquals(catRates[i], expectedCatRates[i], 8e-10); - } - - double[] catProps = gammaSiteBMA.getCategoryProportions(); - double[] expectedCatProps = test.getCategoryProportions(); - for(int i = 0; i < catProps.length; i++){ - assertEquals(catProps[i], expectedCatProps[i], 1e-10); - } - - } - - - } - - -} diff --git a/src/test/dr/evomodel/substmodel/AsymQuadTest.java b/src/test/dr/evomodel/substmodel/AsymQuadTest.java deleted file mode 100644 index 3c3e86f507..0000000000 --- a/src/test/dr/evomodel/substmodel/AsymQuadTest.java +++ /dev/null @@ -1,267 +0,0 @@ -/* - * AsymQuadTest.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package test.dr.evomodel.substmodel; - -import junit.framework.TestCase; -import dr.inference.model.Parameter; -import dr.oldevomodel.substmodel.AsymmetricQuadraticModel; -import dr.evolution.datatype.Microsatellite; - -/** - * @author Chieh-Hsi Wu - * - * Tests AsymmetricQuadraticModel exponentiation. - */ -public class AsymQuadTest extends TestCase { - - interface Instance { - public Microsatellite getDataType(); - - public double getExpanConst(); - - public double getExpanLin(); - - public double getExpanQuad(); - - public double getContractConst(); - - public double getContractLin(); - - public double getContractQuad(); - - double getDistance(); - - double[] getExpectedPi(); - - public double[] getExpectedResult(); - } - - Instance test0 = new Instance() { - public Microsatellite getDataType(){ - return new Microsatellite(1,4); - } - public double getExpanConst(){ - return 1.0; - } - - public double getExpanLin(){ - return 5.0; - } - - public double getExpanQuad(){ - return 0.0; - } - - public double getContractConst(){ - return 1.0; - } - - public double getContractLin(){ - return 5.0; - } - - public double getContractQuad(){ - return 0.0; - } - - public double getDistance() { - return 0.1; - } - - public double[] getExpectedPi() { - return new double[]{ - 0.757532281205165, 0.126255380200861, 0.068866571018651, 0.047345767575323 - }; - } - - public double[] getExpectedResult() { - return new double[]{ - 0.979555040783480, 0.019216583311851, 0.001139116232520, 0.000089259672149, - 0.115299499871107, 0.780702902910835, 0.092806213742576, 0.011191383475483, - 0.012530278557716, 0.170144725194722, 0.654730453041978, 0.162594543205584, - 0.001428154754382, 0.029843689267955, 0.236501153753577, 0.732227002224086 - }; - } - }; - - Instance test1 = new Instance() { - public Microsatellite getDataType(){ - return new Microsatellite(1,4); - } - public double getExpanConst(){ - return 1.0; - } - - public double getExpanLin(){ - return 5.0; - } - - public double getExpanQuad(){ - return 0.0; - } - - public double getContractConst(){ - return 2.0; - } - - public double getContractLin(){ - return 3.0; - } - - public double getContractQuad(){ - return 0.0; - } - - public double getDistance() { - return 0.2; - } - - public double[] getExpectedPi() { - return new double[]{ - 0.666666666666667, 0.133333333333333, 0.100000000000000, 0.100000000000000 - }; - } - - public double[] getExpectedResult() { - return new double[]{ - 0.965025560544615, 0.031394424214122, 0.003139726429413, 0.000440288811850, - 0.156972121070610, 0.676199129838700, 0.136694646485644, 0.030134102605046, - 0.020931509529421, 0.182259528647526, 0.546569017275914, 0.250239944547139, - 0.002935258745666, 0.040178803473394, 0.250239944547139, 0.706645993233800 - }; - } - - - }; - - Instance test2 = new Instance() { - public Microsatellite getDataType(){ - return new Microsatellite(1,4); - } - public double getExpanConst(){ - return 1.0; - } - - public double getExpanLin(){ - return 5.0; - } - - public double getExpanQuad(){ - return 3.0; - } - - public double getContractConst(){ - return 2.0; - } - - public double getContractLin(){ - return 3.0; - } - - public double getContractQuad(){ - return 5.0; - } - - public double getDistance() { - return 0.3; - } - - public double[] getExpectedPi() { - return new double[]{ - 0.873099838521076, 0.087309983852108, 0.028063923381035, 0.011526254245782 - }; - } - - public double[] getExpectedResult() { - return new double[]{ - 0.951679358560076, 0.039846739718488, 0.006618862899417, 0.001855038822019, - 0.398467397184877, 0.419766204810971, 0.131559686528619, 0.050206711475533, - 0.205920179092971, 0.409296802533481, 0.257041454224293, 0.127741564149256, - 0.140516950382903, 0.380309775814669, 0.311022938798188, 0.168150335004240 - }; - } - - }; - - Instance[] all = {test0, test1, test2}; - public void testAsymmetricQuadraticModel() { - - for (Instance test : all) { - Parameter expanConst = new Parameter.Default(1,test.getExpanConst()); - Parameter expanLin = new Parameter.Default(1, test.getExpanLin()); - Parameter expanQuad = new Parameter.Default(1, test.getExpanQuad()); - Parameter contractConst = new Parameter.Default(1,test.getContractConst()); - Parameter contractLin = new Parameter.Default(1, test.getContractLin()); - Parameter contractQuad = new Parameter.Default(1, test.getContractQuad()); - - Microsatellite microsat = test.getDataType(); - AsymmetricQuadraticModel aqm = new AsymmetricQuadraticModel(microsat,null, - expanConst, expanLin, expanQuad, contractConst, contractLin, contractQuad, false); - - aqm.computeStationaryDistribution(); - - double[] statDist = aqm.getStationaryDistribution(); - final double[] expectedStatDist = test.getExpectedPi(); - for (int k = 0; k < statDist.length; ++k) { - assertEquals(statDist[k], expectedStatDist[k], 1e-10); - } - - double[] mat = new double[4*4]; - aqm.getTransitionProbabilities(test.getDistance(), mat); - final double[] result = test.getExpectedResult(); - - int k; - for (k = 0; k < mat.length; ++k) { - assertEquals(result[k], mat[k], 1e-10); - // System.out.print(" " + (mat[k] - result[k])); - } - - k = 0; - for(int i = 0; i < microsat.getStateCount(); i ++){ - for(int j = 0; j < microsat.getStateCount(); j ++){ - assertEquals(result[k++], aqm.getOneTransitionProbabilityEntry(test.getDistance(), i , j), 1e-10); - - } - } - - for(int j = 0; j < microsat.getStateCount();j ++){ - double[] colTransitionProb = aqm.getColTransitionProbabilities(test.getDistance(), j); - for(int i =0 ; i < microsat.getStateCount(); i++){ - assertEquals(result[i*microsat.getStateCount()+j], colTransitionProb[i], 1e-10); - } - } - - for(int i = 0; i < microsat.getStateCount();i ++){ - double[] rowTransitionProb = aqm.getRowTransitionProbabilities(test.getDistance(), i); - for(int j =0 ; j < microsat.getStateCount(); j++){ - assertEquals(result[i*microsat.getStateCount()+j], rowTransitionProb[j], 1e-10); - } - } - } - } -} diff --git a/src/test/dr/evomodel/substmodel/BinaryCovarionModelTest.java b/src/test/dr/evomodel/substmodel/BinaryCovarionModelTest.java deleted file mode 100644 index 3c19edb747..0000000000 --- a/src/test/dr/evomodel/substmodel/BinaryCovarionModelTest.java +++ /dev/null @@ -1,254 +0,0 @@ -/* - * BinaryCovarionModelTest.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package test.dr.evomodel.substmodel; - -import dr.evolution.datatype.DataType; -import dr.evolution.datatype.TwoStateCovarion; -import dr.evolution.datatype.TwoStates; -import dr.oldevomodel.substmodel.BinaryCovarionModel; -import dr.oldevomodel.substmodel.FrequencyModel; -import dr.oldevomodel.substmodel.GeneralSubstitutionModel; -import dr.oldevomodel.substmodel.SubstitutionModelUtils; -import dr.inference.model.Parameter; -import dr.math.matrixAlgebra.IllegalDimension; -import dr.math.matrixAlgebra.Matrix; -import dr.math.matrixAlgebra.Vector; -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - -/** - * BinaryCovarionModel Tester. - * - * @author Alexei Drummond - * @since

08/26/2007
- */ -public class BinaryCovarionModelTest extends TestCase { - public BinaryCovarionModelTest(String name) { - super(name); - } - - @Override - public void setUp() throws Exception { - super.setUp(); - - frequencies = new Parameter.Default(new double[]{0.5, 0.5}); - hiddenFrequencies = new Parameter.Default(new double[]{0.5, 0.5}); - alpha = new Parameter.Default(0.0); - switchingRate = new Parameter.Default(1.0); - - model = new BinaryCovarionModel(TwoStateCovarion.INSTANCE, frequencies, hiddenFrequencies, alpha, switchingRate, - BinaryCovarionModel.Version.VERSION1); - dataType = model.getDataType(); - } - - @Override - public void tearDown() throws Exception { - super.tearDown(); - } - - /** - * Tests that pi*Q = 0 - */ - public void testEquilibriumDistribution() { - - alpha.setParameterValue(0, 0.1); - switchingRate.setParameterValue(0, 1.0); - - model.setupMatrix(); - - double[] pi = model.getFrequencyModel().getFrequencies(); - - try { - Matrix m = new Matrix(model.getQ()); - Vector p = new Vector(pi); - Vector y = m.product(p); - - assertEquals(0.0, y.norm(), 1e-14); - } catch (IllegalDimension illegalDimension) { - } - } - - public void testTransitionProbabilitiesAgainstEqualBaseFreqsEqualRates() { - - // with alpha == 1, the transition probability should be the same as binary jukes cantor - alpha.setParameterValue(0, 1.0); - switchingRate.setParameterValue(0, 1.0); - - model.setupMatrix(); - - double[] matrix = new double[16]; - - double[] pi = model.getFrequencyModel().getFrequencies(); - - for (double distance = 0.01; distance <= 1.005; distance += 0.01) { - model.getTransitionProbabilities(distance, matrix); - - double pChange = - (matrix[1] + matrix[3]) * pi[0] + - (matrix[4] + matrix[6]) * pi[1] + - (matrix[9] + matrix[11]) * pi[2] + - (matrix[12] + matrix[14]) * pi[3]; - - // analytical result for the probability of a mismatch in binary jukes cantor model - double jc = 0.5 * (1 - Math.exp(-2.0 * distance)); - - assertEquals(pChange, jc, 1e-14); - } - } - - public void testTransitionProbabilitiesUnequalBaseFreqsEqualRates() { - - // with alpha == 1, the transition probability should be the same as binary jukes cantor - alpha.setParameterValue(0, 1.0); - switchingRate.setParameterValue(0, 1.0); - frequencies.setParameterValue(0, 0.25); - frequencies.setParameterValue(1, 0.75); - - FrequencyModel freqModel = new FrequencyModel(TwoStates.INSTANCE, frequencies); - - GeneralSubstitutionModel modelToCompare = new GeneralSubstitutionModel(TwoStates.INSTANCE, freqModel, null, 0); - - model.setupMatrix(); - - double[] matrix = new double[16]; - double[] m = new double[4]; - - double[] pi = model.getFrequencyModel().getFrequencies(); - - for (double distance = 0.01; distance <= 1.005; distance += 0.01) { - model.getTransitionProbabilities(distance, matrix); - - modelToCompare.getTransitionProbabilities(distance, m); - - double pChange = - (matrix[1] + matrix[3]) * pi[0] + - (matrix[4] + matrix[6]) * pi[1] + - (matrix[9] + matrix[11]) * pi[2] + - (matrix[12] + matrix[14]) * pi[3]; - - double pChange2 = m[1] * frequencies.getParameterValue(0) + - m[2] * frequencies.getParameterValue(1); - - System.out.println(distance + "\t" + pChange2 + "\t" + pChange); - - assertEquals(pChange2, pChange, 1e-14); - } - } - - public void testTransitionProbabilitiesUnequalBaseFreqsUnequalRateFreqsEqualRates() { - - // with alpha == 1, the transition probability should be the same as binary jukes cantor - alpha.setParameterValue(0, 1.0); - switchingRate.setParameterValue(0, 1.0); - frequencies.setParameterValue(0, 0.25); - frequencies.setParameterValue(1, 0.75); - hiddenFrequencies.setParameterValue(0, 0.1); - hiddenFrequencies.setParameterValue(1, 0.9); - - FrequencyModel freqModel = new FrequencyModel(TwoStates.INSTANCE, frequencies); - - GeneralSubstitutionModel modelToCompare = new GeneralSubstitutionModel(TwoStates.INSTANCE, freqModel, null, 0); - - model.setupMatrix(); - - double[] matrix = new double[16]; - double[] m = new double[4]; - - double[] pi = model.getFrequencyModel().getFrequencies(); - - for (double distance = 0.01; distance <= 1.005; distance += 0.01) { - model.getTransitionProbabilities(distance, matrix); - - modelToCompare.getTransitionProbabilities(distance, m); - - double pChange = - (matrix[1] + matrix[3]) * pi[0] + - (matrix[4] + matrix[6]) * pi[1] + - (matrix[9] + matrix[11]) * pi[2] + - (matrix[12] + matrix[14]) * pi[3]; - - double pChange2 = m[1] * frequencies.getParameterValue(0) + - m[2] * frequencies.getParameterValue(1); - - //System.out.println(distance + "\t" + pChange2 + "\t" + pChange); - - assertEquals(pChange2, pChange, 1e-14); - } - } - - - public void testTransitionProbabilitiesAgainstMatLab() { - // test againt Matlab results for alpha = 0.5 and switching rate = 1.0 - // and visible state base frequencies = 0.25, 0.75 - - alpha.setParameterValue(0, 0.5); - switchingRate.setParameterValue(0, 1.0); - frequencies.setParameterValue(0, 0.25); - frequencies.setParameterValue(1, 0.75); - - model.setupMatrix(); - double[] matrix = new double[16]; - - double[] pi = model.getFrequencyModel().getFrequencies(); - System.out.println(pi[0] + " " + pi[1] + " " + pi[2] + " " + pi[3]); - - System.out.println(SubstitutionModelUtils.toString(model.getQ(), dataType, 2)); - - int index = 0; - for (double distance = 0.01; distance <= 1.005; distance += 0.01) { - model.getTransitionProbabilities(distance, matrix); - - - double pChange = - (matrix[1] + matrix[3]) * pi[0] + - (matrix[4] + matrix[6]) * pi[1] + - (matrix[9] + matrix[11]) * pi[2] + - (matrix[12] + matrix[14]) * pi[3]; - - - double pChangeIndependent = TwoStateCovarionModelTest.matLabPChange[index]; - - //System.out.println(distance + "\t" + pChange + "\t" + pChangeIndependent); - assertEquals(pChange, pChangeIndependent, 1e-14); - - index += 1; - } - } - - public static Test suite() { - return new TestSuite(BinaryCovarionModelTest.class); - } - - BinaryCovarionModel model; - DataType dataType; - Parameter frequencies; - Parameter hiddenFrequencies; - Parameter switchingRate; - Parameter alpha; -} diff --git a/src/test/dr/evomodel/substmodel/CovarionHKYTest.java b/src/test/dr/evomodel/substmodel/CovarionHKYTest.java deleted file mode 100644 index cb82aca559..0000000000 --- a/src/test/dr/evomodel/substmodel/CovarionHKYTest.java +++ /dev/null @@ -1,405 +0,0 @@ -/* - * CovarionHKYTest.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package test.dr.evomodel.substmodel; - -import dr.evolution.datatype.OldHiddenNucleotides; -import dr.evomodel.substmodel.*; -import dr.inference.model.Parameter; -import dr.oldevomodel.substmodel.CovarionHKY; -import dr.oldevomodel.substmodel.FrequencyModel; -import dr.oldevomodel.substmodel.SubstitutionModelUtils; -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - -/** - * CovarionHKY Tester. - * - * @author Alexei Drummond - * @since
08/20/2007
- */ -public class CovarionHKYTest extends TestCase { - public CovarionHKYTest(String name) { - super(name); - } - - public void setUp() throws Exception { - super.setUp(); - - alpha = new Parameter.Default(0.0); - switchingRate = new Parameter.Default(1.0); - kappa = new Parameter.Default(2.0); - - dataType = new OldHiddenNucleotides(2); - - } - - public void tearDown() throws Exception { - super.tearDown(); - } - - public void testK2PTransitionProbabilities() { - - double[] frequencies = new double[] - {0.125, 0.125, 0.125, 0.125, 0.125, 0.125, 0.125, 0.125}; - - transitionProbabilitiesTester(frequencies, matLabPChange_K2P); - } - - public void testHKYTransitionProbabilities() { - - double[] baseFrequencies = new double[]{0.15, 0.2, 0.3, 0.35}; - - double[] frequencies = new double[8]; - for (int i = 0; i < frequencies.length; i++) { - frequencies[i] = baseFrequencies[i % 4] / 2.0; - } - - transitionProbabilitiesTester(frequencies, matLabPChange_HKY); - } - - - public void transitionProbabilitiesTester(double[] freqs, double[] expectedP) { - - Parameter frequencies = new Parameter.Default(freqs); - FrequencyModel freqModel = new FrequencyModel(dataType, frequencies); - model = new CovarionHKY(dataType, kappa, alpha, switchingRate, freqModel); - - alpha.setParameterValue(0, 0.0); - switchingRate.setParameterValue(0, 1.0); - kappa.setParameterValue(0, 2.0); - - model.setupMatrix(); - - System.out.println(SubstitutionModelUtils.toString(model.getQ(), dataType, 2)); - - double[] matrix = new double[64]; - double[] pi = model.getFrequencyModel().getFrequencies(); - - int index = 0; - for (double distance = 0.01; distance <= 1.005; distance += 0.01) { - model.getTransitionProbabilities(distance, matrix); - - double pChange = 0.0; - double pNoOrHiddenChange = 0.0; - int k = 0; - for (int i = 0; i < 8; i++) { - for (int j = 0; j < 8; j++) { - - if ((i % 4) != (j % 4)) { - pChange += matrix[k] * pi[i]; - } else { - pNoOrHiddenChange += matrix[k] * pi[i]; - } - k += 1; - } - } - - double totalP = pChange + pNoOrHiddenChange; - - assertEquals(1.0, totalP, 1e-10); - - System.out.print(distance + "\t" + "\t" + pChange + "\t"); - if (index < 100) System.out.print(expectedP[index]); - System.out.println(); - - //assertEquals(expectedP[index], pChange, 1e-14); - - index += 1; - } - } - - - public void testGetRelativeDNARates() throws Exception { - //TODO: Test goes here... - } - - public void testSetGetKappa() throws Exception { - //TODO: Test goes here... - } - - public static Test suite() { - return new TestSuite(CovarionHKYTest.class); - } - - CovarionHKY model; - OldHiddenNucleotides dataType; - Parameter kappa; - Parameter switchingRate; - Parameter alpha; - - /* - %The following Matlab code provided by David Bryant was used to calculate - %the probabilities for a covarion K2P model with hidden rates of 0 and 1, - %kappa of 2 and a switching rate of 1 - - format long; - clear all; - - r=4; - k=2; - - Q = [-2-k 1 k 1; 1 -2-k 1 k; k 1 -2-k 1; 1 k 1 -2-k]; - - piQ = diag([0.25 0.25 0.25 0.25]); - - %Next step necessary for unequal base cases. Commented out - %to match Alexei's code. - %Q = Q*piQ; - - G = [-1 1; 1 -1]; %Transition matrix for rate classes - piG = diag([1/2 1/2]); - D = diag([0 1]); - I = eye(r,r); - R = kron(D,Q) + kron(G,I); - - pi = kron(piG,piQ); - - %Matrix C is a 0 one matrix. Picks out where bases change - C = kron(ones(2,2),ones(r,r)-eye(r)); - - %Normalise - rate = sum(sum(C.*(pi*R))); - R = R/rate; - - - for i=1:1:100 - t = i*0.01; - P = expm(R*t); - pchange(i) = sum(sum(C.*(pi*P))); - end - - pchange' - - */ - static final double[] matLabPChange_K2P = { - 0.00986400785088, - 0.01946196037798, - 0.02880252532240, - 0.03789407770533, - 0.04674470983328, - 0.05536224095885, - 0.06375422660885, - 0.07192796759140, - 0.07989051869303, - 0.08764869707661, - 0.09520909039030, - 0.10257806459771, - 0.10976177153876, - 0.11676615623066, - 0.12359696391788, - 0.13025974687993, - 0.13675987100520, - 0.14310252213901, - 0.14929271221364, - 0.15533528516793, - 0.16123492266363, - 0.16699614960557, - 0.17262333947249, - 0.17812071946489, - 0.18349237547643, - 0.18874225689480, - 0.19387418123805, - 0.19889183863200, - 0.20379879613422, - 0.20859850190993, - 0.21329428926481, - 0.21788938053981, - 0.22238689087256, - 0.22678983183007, - 0.23110111491715, - 0.23532355496481, - 0.23945987340274, - 0.24351270142001, - 0.24748458301758, - 0.25137797795665, - 0.25519526460616, - 0.25893874269311, - 0.26261063595893, - 0.26621309472519, - 0.26974819837174, - 0.27321795773026, - 0.27662431739624, - 0.27996915796208, - 0.28325429817402, - 0.28648149701564, - 0.28965245572033, - 0.29276881971518, - 0.29583218049872, - 0.29884407745474, - 0.30180599960433, - 0.30471938729832, - 0.30758563385225, - 0.31040608712556, - 0.31318205104731, - 0.31591478708987, - 0.31860551569264, - 0.32125541763742, - 0.32386563537701, - 0.32643727431884, - 0.32897140406488, - 0.33146905960964, - 0.33393124249748, - 0.33635892194069, - 0.33875303589965, - 0.34111449212649, - 0.34344416917334, - 0.34574291736640, - 0.34801155974717, - 0.35025089298173, - 0.35246168823930, - 0.35464469204110, - 0.35680062708056, - 0.35893019301571, - 0.36103406723493, - 0.36311290559680, - 0.36516734314491, - 0.36719799479871, - 0.36920545602088, - 0.37119030346234, - 0.37315309558549, - 0.37509437326636, - 0.37701466037663, - 0.37891446434595, - 0.38079427670539, - 0.38265457361258, - 0.38449581635920, - 0.38631845186142, - 0.38812291313386, - 0.38990961974765, - 0.39167897827306, - 0.39343138270730, - 0.39516721488804, - 0.39688684489292, - 0.39859063142581, - 0.40027892219004 - }; - - static final double[] matLabPChange_HKY = { - 0.00985954695768, - 0.01944735733283, - 0.02877658973544, - 0.03785964647441, - 0.04670821854965, - 0.05533332794691, - 0.06374536739747, - 0.07195413775516, - 0.07996888313383, - 0.08779832394009, - 0.09545068792763, - 0.10293373939203, - 0.11025480661789, - 0.11742080768318, - 0.12443827471949, - 0.13131337672096, - 0.13805194098895, - 0.14465947329452, - 0.15114117683550, - 0.15750197006065, - 0.16374650342878, - 0.16987917516689, - 0.17590414608721, - 0.18182535351970, - 0.18764652441305, - 0.19337118765401, - 0.19900268565191, - 0.20454418523250, - 0.20999868788237, - 0.21536903938304, - 0.22065793887109, - 0.22586794735891, - 0.23100149574820, - 0.23606089236674, - 0.24104833005692, - 0.24596589284278, - 0.25081556220095, - 0.25559922295905, - 0.26031866884393, - 0.26497560770062, - 0.26957166640174, - 0.27410839546591, - 0.27858727340240, - 0.28300971079857, - 0.28737705416541, - 0.29169058955549, - 0.29595154596716, - 0.30016109854757, - 0.30432037160662, - 0.30843044145304, - 0.31249233906332, - 0.31650705259341, - 0.32047552974251, - 0.32439867997787, - 0.32827737662883, - 0.33211245885791, - 0.33590473351622, - 0.33965497689022, - 0.34336393634610, - 0.34703233187806, - 0.35066085756610, - 0.35425018294872, - 0.35780095431559, - 0.36131379592506, - 0.36478931115072, - 0.36822808356150, - 0.37163067793909, - 0.37499764123646, - 0.37832950348097, - 0.38162677862531, - 0.38488996534947, - 0.38811954781650, - 0.39131599638496, - 0.39447976828045, - 0.39761130822876, - 0.40071104905293, - 0.40377941223623, - 0.40681680845316, - 0.40982363807038, - 0.41280029161931, - 0.41574715024200, - 0.41866458611203, - 0.42155296283168, - 0.42441263580698, - 0.42724395260180, - 0.43004725327227, - 0.43282287068266, - 0.43557113080388, - 0.43829235299547, - 0.44098685027222, - 0.44365492955622, - 0.44629689191518, - 0.44891303278793, - 0.45150364219766, - 0.45406900495387, - 0.45660940084344, - 0.45912510481158, - 0.46161638713329, - 0.46408351357576, - 0.46652674555230 - }; -} diff --git a/src/test/dr/evomodel/substmodel/GeneralF81Test.java b/src/test/dr/evomodel/substmodel/GeneralF81Test.java deleted file mode 100644 index 4839a5fcf4..0000000000 --- a/src/test/dr/evomodel/substmodel/GeneralF81Test.java +++ /dev/null @@ -1,166 +0,0 @@ -/* - * GeneralF81Test.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package test.dr.evomodel.substmodel; - -import dr.evolution.datatype.GeneralDataType; -import dr.oldevomodel.substmodel.FrequencyModel; -import dr.oldevomodel.substmodel.GeneralF81Model; -import junit.framework.TestCase; - -/** - * Test GeneralF81 matrix exponentiation - * - * @author Walter Xie - */ -public class GeneralF81Test extends TestCase { - - interface Instance { - double[] getPi(); - - double getDistance(); - - double[] getExpectedResult(); - } - - /* - * Results obtained by running the following scilab code, - - piQ = diag([.2, .3, .25, .25]) ; d = 0.05 ; - - % Q matrix with zeroed diagonal - XQ = [0 1 1 1; 1 0 1 1; 1 1 0 1; 1 1 1 0]; - - xx = XQ * piQ ; - - % fill diagonal and normalize by total substitution rate - q0 = (xx + diag(-sum(xx,2))) / sum(piQ * sum(xx,2)) ; - format('v', 15); - expm(q0 * d) - - */ - Instance test0 = new Instance() { - public double[] getPi() { - return new double[]{0.25, 0.25, 0.25, 0.25}; - } - - public double getDistance() { - return 0.1; - } - - public double[] getExpectedResult() { - return new double[]{ - 0.906379989282, 0.031206670239, 0.031206670239, 0.031206670239, - 0.031206670239, 0.906379989282, 0.031206670239, 0.031206670239, - 0.031206670239, 0.031206670239, 0.906379989282, 0.031206670239, - 0.031206670239, 0.031206670239, 0.031206670239, 0.906379989282 - }; - } - }; - - Instance test1 = new Instance() { - public double[] getPi() { - return new double[]{0.50, 0.20, 0.2, 0.1}; - } - - public double getDistance() { - return 0.1; - } - - public double[] getExpectedResult() { - return new double[]{ - 0.929702430444, 0.028119027822, 0.028119027822, 0.014059513911, - 0.070297569556, 0.887523888711, 0.028119027822, 0.014059513911, - 0.070297569556, 0.028119027822, 0.887523888711, 0.014059513911, - 0.070297569556, 0.028119027822, 0.028119027822, 0.873464374800 - }; - } - }; - - Instance test2 = new Instance() { - public double[] getPi() { - return new double[]{0.20, 0.30, 0.25, 0.25}; - } - - public double getDistance() { - return 0.05; - } - - public double[] getExpectedResult() { - return new double[]{ - 0.948070805840, 0.019473447810, 0.016227873175, 0.016227873175, - 0.012982298540, 0.954561955110, 0.016227873175, 0.016227873175, - 0.012982298540, 0.019473447810, 0.951316380475, 0.016227873175, - 0.012982298540, 0.019473447810, 0.016227873175, 0.951316380475 - }; - } - }; - - Instance test3 = new Instance() { - public double[] getPi() { - return new double[]{0.20, 0.30, 0.25, 0.25}; - } - - public double getDistance() { - return 0.2; - } - - public double[] getExpectedResult() { - return new double[]{ - 0.811647020254, 0.070632367405, 0.058860306171, 0.058860306171, - 0.047088244936, 0.835191142722, 0.058860306171, 0.058860306171, - 0.047088244936, 0.070632367405, 0.823419081488, 0.058860306171, - 0.047088244936, 0.070632367405, 0.058860306171, 0.823419081488 - }; - } - }; - - Instance[] all = {test0, test1, test2, test3}; - - public void testGF81() { - for (Instance test : all) { - - double[] pi = test.getPi(); - -// Parameter freqs = new Parameter.Default(pi); - GeneralDataType gdt = new GeneralDataType(new String[]{"1", "2", "3", "4"}); - FrequencyModel f = new FrequencyModel(gdt, pi); - GeneralF81Model generalF81Model = new GeneralF81Model(f); - - double distance = test.getDistance(); - - double[] mat = new double[4 * 4]; - generalF81Model.getTransitionProbabilities(distance, mat); - final double[] result = test.getExpectedResult(); - - for (int k = 0; k < mat.length; ++k) { - assertEquals(mat[k], result[k], 1e-10); - // System.out.print(" " + (mat[k] - result[k])); - } - } - } -} diff --git a/src/test/dr/evomodel/substmodel/GeneralSubstitutionModelTest.java b/src/test/dr/evomodel/substmodel/GeneralSubstitutionModelTest.java index 9d5e2e3612..525d9067c0 100644 --- a/src/test/dr/evomodel/substmodel/GeneralSubstitutionModelTest.java +++ b/src/test/dr/evomodel/substmodel/GeneralSubstitutionModelTest.java @@ -32,14 +32,10 @@ import dr.evomodel.operators.ExchangeOperator; import dr.evomodel.operators.SubtreeSlideOperator; import dr.evomodel.operators.WilsonBalding; +import dr.evomodel.substmodel.FrequencyModel; +import dr.evomodel.substmodel.GeneralSubstitutionModel; import dr.evomodel.tree.DefaultTreeModel; -import dr.oldevomodel.sitemodel.GammaSiteModel; -import dr.oldevomodel.substmodel.FrequencyModel; -import dr.oldevomodel.substmodel.GeneralSubstitutionModel; -import dr.oldevomodel.treelikelihood.TreeLikelihood; -import dr.oldevomodelxml.sitemodel.GammaSiteModelParser; -import dr.oldevomodelxml.substmodel.GeneralSubstitutionModelParser; -import dr.oldevomodelxml.treelikelihood.TreeLikelihoodParser; +import dr.evomodelxml.substmodel.GeneralSubstitutionModelParser; import dr.inference.loggers.ArrayLogFormatter; import dr.inference.loggers.MCLogger; import dr.inference.loggers.TabDelimitedFormatter; @@ -58,6 +54,8 @@ import java.util.ArrayList; import java.util.List; +import static dr.evomodelxml.siteratemodel.SiteModelParser.MUTATION_RATE; + /** * @author Walter Xie * convert testGeneralSubstitutionModel.xml in the folder /example @@ -98,103 +96,104 @@ public void setUp() throws Exception { public void testGeneralSubstitutionModel() { + throw new UnsupportedOperationException("Not implemented - uses oldevomodel.treelikelihood, now deleted"); MathUtils.setSeed(666); // Sub model - FrequencyModel freqModel = new FrequencyModel(dataType, alignment.getStateFrequencies()); - Parameter ratesPara = new Parameter.Default(GeneralSubstitutionModelParser.RATES, 5, 1.0); // dimension="5" value="1.0" - GeneralSubstitutionModel generalSubstitutionModel = new GeneralSubstitutionModel(dataType, freqModel, ratesPara, 4); // relativeTo="5" - - //siteModel - GammaSiteModel siteModel = new GammaSiteModel(generalSubstitutionModel); - Parameter mu = new Parameter.Default(GammaSiteModelParser.MUTATION_RATE, 1.0, 0, Double.POSITIVE_INFINITY); - siteModel.setMutationRateParameter(mu); - - //treeLikelihood - SitePatterns patterns = new SitePatterns(alignment, null, 0, -1, 1, true); - - TreeLikelihood treeLikelihood = new TreeLikelihood(patterns, treeModel, siteModel, null, null, - false, false, true, false, false); - treeLikelihood.setId(TreeLikelihoodParser.TREE_LIKELIHOOD); - - // Operators - OperatorSchedule schedule = new SimpleOperatorSchedule(); - - MCMCOperator operator = new ScaleOperator(ratesPara, 0.5); - operator.setWeight(1.0); - schedule.addOperator(operator); - - Parameter rootHeight = ((DefaultTreeModel)treeModel).getRootHeightParameter(); - rootHeight.setId(TREE_HEIGHT); - operator = new ScaleOperator(rootHeight, 0.5); - operator.setWeight(1.0); - schedule.addOperator(operator); - - Parameter internalHeights = ((DefaultTreeModel)treeModel).createNodeHeightsParameter(false, true, false); - operator = new UniformOperator(internalHeights, 10.0); - schedule.addOperator(operator); - - operator = new SubtreeSlideOperator(((DefaultTreeModel)treeModel), 1, 1, true, false, false, false, AdaptationMode.ADAPTATION_ON, AdaptableMCMCOperator.DEFAULT_ADAPTATION_TARGET); - schedule.addOperator(operator); - - operator = new ExchangeOperator(ExchangeOperator.NARROW, treeModel, 1.0); -// operator.doOperation(); - schedule.addOperator(operator); - - operator = new ExchangeOperator(ExchangeOperator.WIDE, treeModel, 1.0); -// operator.doOperation(); - schedule.addOperator(operator); - - operator = new WilsonBalding(treeModel, 1.0); -// operator.doOperation(); - schedule.addOperator(operator); - - // Log - ArrayLogFormatter formatter = new ArrayLogFormatter(false); - - MCLogger[] loggers = new MCLogger[2]; - loggers[0] = new MCLogger(formatter, 1000, false); - loggers[0].add(treeLikelihood); - loggers[0].add(rootHeight); - loggers[0].add(ratesPara); - - loggers[1] = new MCLogger(new TabDelimitedFormatter(System.out), 100000, false); - loggers[1].add(treeLikelihood); - loggers[1].add(rootHeight); - loggers[1].add(ratesPara); - - // MCMC - MCMC mcmc = new MCMC("mcmc1"); - MCMCOptions options = new MCMCOptions(10000000); - - mcmc.setShowOperatorAnalysis(true); - mcmc.init(options, treeLikelihood, schedule, loggers); - mcmc.run(); - - // time - System.out.println(mcmc.getTimer().toString()); - - // Tracer - List traces = formatter.getTraces(); - ArrayTraceList traceList = new ArrayTraceList("GeneralSubstitutionModelTest", traces, 0); - - for (int i = 1; i < traces.size(); i++) { - traceList.analyseTrace(i); - } - -// -// -// - - TraceCorrelation likelihoodStats = traceList.getCorrelationStatistics(traceList.getTraceIndex(TreeLikelihoodParser.TREE_LIKELIHOOD)); - assertExpectation(TreeLikelihoodParser.TREE_LIKELIHOOD, likelihoodStats, -1815.75); - - TraceCorrelation treeHeightStats = traceList.getCorrelationStatistics(traceList.getTraceIndex(TREE_HEIGHT)); - assertExpectation(TREE_HEIGHT, treeHeightStats, 0.0640787258170083); - - TraceCorrelation rateACStats = traceList.getCorrelationStatistics(traceList.getTraceIndex(GeneralSubstitutionModelParser.RATES + "1")); - assertExpectation(GeneralSubstitutionModelParser.RATES + "1", rateACStats, 0.061071756742081366); +// FrequencyModel freqModel = new FrequencyModel(dataType, alignment.getStateFrequencies()); +// Parameter ratesPara = new Parameter.Default(GeneralSubstitutionModelParser.RATES, 5, 1.0); // dimension="5" value="1.0" +// GeneralSubstitutionModel generalSubstitutionModel = new GeneralSubstitutionModel(dataType, freqModel, ratesPara, 4); // relativeTo="5" +// +// //siteModel +// GammaSiteModel siteModel = new GammaSiteModel(generalSubstitutionModel); +// Parameter mu = new Parameter.Default(MUTATION_RATE, 1.0, 0, Double.POSITIVE_INFINITY); +// siteModel.setMutationRateParameter(mu); +// +// //treeLikelihood +// SitePatterns patterns = new SitePatterns(alignment, null, 0, -1, 1, true); +// +// TreeLikelihood treeLikelihood = new TreeLikelihood(patterns, treeModel, siteModel, null, null, +// false, false, true, false, false); +// treeLikelihood.setId(TreeLikelihoodParser.TREE_LIKELIHOOD); +// +// // Operators +// OperatorSchedule schedule = new SimpleOperatorSchedule(); +// +// MCMCOperator operator = new ScaleOperator(ratesPara, 0.5); +// operator.setWeight(1.0); +// schedule.addOperator(operator); +// +// Parameter rootHeight = ((DefaultTreeModel)treeModel).getRootHeightParameter(); +// rootHeight.setId(TREE_HEIGHT); +// operator = new ScaleOperator(rootHeight, 0.5); +// operator.setWeight(1.0); +// schedule.addOperator(operator); +// +// Parameter internalHeights = ((DefaultTreeModel)treeModel).createNodeHeightsParameter(false, true, false); +// operator = new UniformOperator(internalHeights, 10.0); +// schedule.addOperator(operator); +// +// operator = new SubtreeSlideOperator(((DefaultTreeModel)treeModel), 1, 1, true, false, false, false, AdaptationMode.ADAPTATION_ON, AdaptableMCMCOperator.DEFAULT_ADAPTATION_TARGET); +// schedule.addOperator(operator); +// +// operator = new ExchangeOperator(ExchangeOperator.NARROW, treeModel, 1.0); +//// operator.doOperation(); +// schedule.addOperator(operator); +// +// operator = new ExchangeOperator(ExchangeOperator.WIDE, treeModel, 1.0); +//// operator.doOperation(); +// schedule.addOperator(operator); +// +// operator = new WilsonBalding(treeModel, 1.0); +//// operator.doOperation(); +// schedule.addOperator(operator); +// +// // Log +// ArrayLogFormatter formatter = new ArrayLogFormatter(false); +// +// MCLogger[] loggers = new MCLogger[2]; +// loggers[0] = new MCLogger(formatter, 1000, false); +// loggers[0].add(treeLikelihood); +// loggers[0].add(rootHeight); +// loggers[0].add(ratesPara); +// +// loggers[1] = new MCLogger(new TabDelimitedFormatter(System.out), 100000, false); +// loggers[1].add(treeLikelihood); +// loggers[1].add(rootHeight); +// loggers[1].add(ratesPara); +// +// // MCMC +// MCMC mcmc = new MCMC("mcmc1"); +// MCMCOptions options = new MCMCOptions(10000000); +// +// mcmc.setShowOperatorAnalysis(true); +// mcmc.init(options, treeLikelihood, schedule, loggers); +// mcmc.run(); +// +// // time +// System.out.println(mcmc.getTimer().toString()); +// +// // Tracer +// List traces = formatter.getTraces(); +// ArrayTraceList traceList = new ArrayTraceList("GeneralSubstitutionModelTest", traces, 0); +// +// for (int i = 1; i < traces.size(); i++) { +// traceList.analyseTrace(i); +// } +// +//// +//// +//// +// +// TraceCorrelation likelihoodStats = traceList.getCorrelationStatistics(traceList.getTraceIndex(TreeLikelihoodParser.TREE_LIKELIHOOD)); +// assertExpectation(TreeLikelihoodParser.TREE_LIKELIHOOD, likelihoodStats, -1815.75); +// +// TraceCorrelation treeHeightStats = traceList.getCorrelationStatistics(traceList.getTraceIndex(TREE_HEIGHT)); +// assertExpectation(TREE_HEIGHT, treeHeightStats, 0.0640787258170083); +// +// TraceCorrelation rateACStats = traceList.getCorrelationStatistics(traceList.getTraceIndex(GeneralSubstitutionModelParser.RATES + "1")); +// assertExpectation(GeneralSubstitutionModelParser.RATES + "1", rateACStats, 0.061071756742081366); } public static Test suite() { diff --git a/src/test/dr/evomodel/substmodel/HKYTest.java b/src/test/dr/evomodel/substmodel/HKYTest.java index 5960ee5839..6b292f6db9 100644 --- a/src/test/dr/evomodel/substmodel/HKYTest.java +++ b/src/test/dr/evomodel/substmodel/HKYTest.java @@ -28,8 +28,8 @@ package test.dr.evomodel.substmodel; import dr.evolution.datatype.Nucleotides; -import dr.oldevomodel.substmodel.FrequencyModel; -import dr.oldevomodel.substmodel.HKY; +import dr.evomodel.substmodel.FrequencyModel; +import dr.evomodel.substmodel.nucleotide.HKY; import dr.inference.model.Parameter; import junit.framework.TestCase; diff --git a/src/test/dr/evomodel/substmodel/LinearBiasTest.java b/src/test/dr/evomodel/substmodel/LinearBiasTest.java deleted file mode 100644 index 86956c9c2a..0000000000 --- a/src/test/dr/evomodel/substmodel/LinearBiasTest.java +++ /dev/null @@ -1,247 +0,0 @@ -/* - * LinearBiasTest.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package test.dr.evomodel.substmodel; -import junit.framework.TestCase; -import dr.evolution.datatype.Microsatellite; -import dr.oldevomodel.substmodel.OnePhaseModel; -import dr.oldevomodel.substmodel.AsymmetricQuadraticModel; -import dr.oldevomodel.substmodel.LinearBiasModel; -import dr.inference.model.Parameter; - -/** - * @author Chieh-Hsi Wu - * - * Tests the LinearBiasModel of microsatellites. - */ -public class LinearBiasTest extends TestCase { - interface Instance { - - public OnePhaseModel getSubModel(); - - public double getBiasLinearParam(); - - public double getBiasConstantParam(); - - double getDistance(); - - double[] getExpectedPi(); - - double[] getExpectedResult(); - - public boolean isLogistics(); - - } - - Instance test0 = new Instance() { - - public OnePhaseModel getSubModel(){ - return new AsymmetricQuadraticModel(new Microsatellite(1,4),null, - new Parameter.Default(5.0), new Parameter.Default(3.0),new Parameter.Default(0.0), - new Parameter.Default(5.0), new Parameter.Default(3.0),new Parameter.Default(0.0), false); - } - public double getBiasConstantParam(){ - return 0.6; - } - - - public double getBiasLinearParam(){ - return -0.3; - } - - - public double getDistance() { - return 0.1; - } - - public double[] getExpectedPi() { - return new double[]{ - 0.605108055009823, 0.324165029469548, 0.070726915520629, 0 - }; - } - - public double[] getExpectedResult() { - return new double[]{ - 0.946658398354944, 0.052177678283089, 0.001163923361967, 0, - 0.097398332795100, 0.863963320210341, 0.038638346994560, 0, - 0.009958010985717, 0.177092423725065, 0.812949565289218, 0, - 0.000867275762735, 0.023191450073206, 0.212503945856679, 0.763437328307380 - }; - } - - public boolean isLogistics(){ - return false; - } - }; - - Instance test1 = new Instance() { - - public OnePhaseModel getSubModel(){ - return new AsymmetricQuadraticModel(new Microsatellite(1,4), null, - new Parameter.Default(2.0), new Parameter.Default(5.0), new Parameter.Default(1.0), - new Parameter.Default(2.0), new Parameter.Default(5.0), new Parameter.Default(1.0), false); - } - public double getBiasConstantParam(){ - return 0.7; - } - - - public double getBiasLinearParam(){ - return -0.1; - } - - - public double getDistance() { - return 0.76; - } - - public double[] getExpectedPi() { - return new double[]{ - 0.545073375262055, 0.238469601677149, 0.143081761006289, 0.073375262054507 - }; - } - - public double[] getExpectedResult() { - return new double[]{ - 0.863562128338329, 0.108051762152360, 0.022697835971058, 0.005688273538253, - 0.246975456348250, 0.483877169454682, 0.197140800250442, 0.072006573946625, - 0.086467946556413, 0.328568000417404, 0.374198643716438, 0.210765409309745, - 0.042255746284165, 0.234021365326532, 0.410992548154004, 0.312730340235300 - }; - } - - public boolean isLogistics(){ - return false; - } - - }; - - - - Instance test2 = new Instance() { - - public OnePhaseModel getSubModel(){ - return new AsymmetricQuadraticModel(new Microsatellite(1,6), null); - } - public double getBiasConstantParam(){ - return -0.1; - } - - - public double getBiasLinearParam(){ - return 0.2; - } - - - public double getDistance() { - return 0.135; - } - - public double[] getExpectedPi() { - return new double[]{ - 0.0596248692859803, 0.0596248692859803, 0.0735548466843399, 0.111916502631505, 0.209948475478618, 0.485330436633581 - }; - } - - public double[] getExpectedResult() { - return new double[]{ - 9.06886087194020e-01, 8.80044177328101e-02, 4.90144978250249e-03, 0.000201113041761387, 6.73323616634035e-06, 1.99012740290826e-07, - 8.80044177328099e-02, 8.14017231936112e-01, 9.20028255435521e-02, 0.005709760680862604, 2.56214890258364e-04, 9.54921640436405e-06, - 3.97320252528957e-03, 7.45791296461646e-02, 8.13688411677705e-01, 0.100651260606737944, 6.76913614468138e-03, 3.38859399421337e-04, - 1.07145403446126e-04, 3.04194400509115e-03, 6.61509953263142e-02, 0.813368537652168544, 1.09045253167639e-01, 8.28612444534153e-03, - 1.91222310785769e-06, 7.27644213941150e-05, 2.37154744835561e-03, 0.058128373331922951, 8.13110664106114e-01, 1.26314738469105e-01, - 2.44495455773264e-08, 1.17316108146806e-06, 5.13562498673616e-05, 0.001910768413216536, 5.46423318430593e-02, 9.43394345883230e-01 - }; - } - - public boolean isLogistics(){ - return true; - } - - }; - - Instance[] all = {test0, test1, test2}; - public void testLinearBiasModel() { - - for (Instance test : all) { - OnePhaseModel subModel = test.getSubModel(); - Microsatellite microsat = (Microsatellite)subModel.getDataType(); - Parameter biasLinear = new Parameter.Default(1, test.getBiasLinearParam()); - Parameter biasConstant = new Parameter.Default(1, test.getBiasConstantParam()); - LinearBiasModel lbm = new LinearBiasModel( - microsat, - null, - subModel, - biasConstant, - biasLinear, - test.isLogistics(), - false, - false); - - lbm.computeStationaryDistribution(); - - double[] statDist = lbm.getStationaryDistribution(); - final double[] expectedStatDist = test.getExpectedPi(); - for (int k = 0; k < statDist.length; ++k) { - assertEquals(statDist[k], expectedStatDist[k], 1e-10); - } - int stateCount = microsat.getStateCount(); - double[] mat = new double[stateCount*stateCount]; - lbm.getTransitionProbabilities(test.getDistance(), mat); - final double[] result = test.getExpectedResult(); - - int k; - for (k = 0; k < mat.length; ++k) { - assertEquals(result[k], mat[k], 5e-9); - //System.out.print(" " + (mat[k] - result[k])); - } - - k = 0; - for(int i = 0; i < microsat.getStateCount(); i ++){ - for(int j = 0; j < microsat.getStateCount(); j ++){ - assertEquals(result[k++], lbm.getOneTransitionProbabilityEntry(test.getDistance(), i , j), 5e-9); - - } - } - - for(int j = 0; j < microsat.getStateCount();j ++){ - double[] colTransitionProb = lbm.getColTransitionProbabilities(test.getDistance(), j); - for(int i =0 ; i < microsat.getStateCount(); i++){ - assertEquals(result[i*microsat.getStateCount()+j], colTransitionProb[i], 5e-9); - } - } - - for(int i = 0; i < microsat.getStateCount();i ++){ - double[] rowTransitionProb = lbm.getRowTransitionProbabilities(test.getDistance(), i); - for(int j =0 ; j < microsat.getStateCount(); j++){ - assertEquals(result[i*microsat.getStateCount()+j], rowTransitionProb[j], 5e-9); - } - } - } - } - -} diff --git a/src/test/dr/evomodel/substmodel/MsatFullLikelihoodTest.java b/src/test/dr/evomodel/substmodel/MsatFullLikelihoodTest.java deleted file mode 100644 index 95fbbda844..0000000000 --- a/src/test/dr/evomodel/substmodel/MsatFullLikelihoodTest.java +++ /dev/null @@ -1,201 +0,0 @@ -/* - * MsatFullLikelihoodTest.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package test.dr.evomodel.substmodel; - -import dr.evomodel.tree.DefaultTreeModel; -import junit.framework.TestCase; -import dr.evolution.datatype.Microsatellite; -import dr.evolution.util.Taxa; -import dr.evolution.util.Taxon; -import dr.evolution.alignment.Patterns; -import dr.evolution.io.NewickImporter; -import dr.evolution.tree.Tree; -import dr.evomodel.tree.TreeModel; -import dr.oldevomodel.substmodel.AsymmetricQuadraticModel; -import dr.oldevomodel.sitemodel.GammaSiteModel; -import dr.oldevomodel.treelikelihood.TreeLikelihood; - -import java.util.ArrayList; -import java.util.Collections; - -/** - * @author Chieh-Hsi Wu - * - * JUnit test for testing the full likelihood calculation with microsatellite models. - */ -public class MsatFullLikelihoodTest extends TestCase { - - TreeLikelihood treeLikelihood1; - TreeLikelihood treeLikelihood2; - TreeLikelihood treeLikelihood3; - - public void setUp() throws Exception { - super.setUp(); - - //taxa - ArrayList taxonList1= new ArrayList(); - Collections.addAll(taxonList1, new Taxon("taxon1"), new Taxon("taxon2"), new Taxon("taxon3")); - Taxa taxa1 = new Taxa(taxonList1); - - //msat datatype - Microsatellite msat = new Microsatellite(1,3); - Patterns msatPatterns = new Patterns(msat, taxa1); - msatPatterns.addPattern(new int[]{0, 1, 2}); //pattern in the correct code form. - - //create tree - NewickImporter importer = new NewickImporter("(taxon1:7.5,(taxon2:5.3,taxon3:5.3):2.2);"); - Tree tree = importer.importTree(null); - - //treeModel - TreeModel treeModel = new DefaultTreeModel(tree); - - //msatsubstModel - AsymmetricQuadraticModel aqm1 = new AsymmetricQuadraticModel(msat, null); - - //siteModel - GammaSiteModel siteModel = new GammaSiteModel(aqm1); - - //treeLikelihood - treeLikelihood1 = new TreeLikelihood( - msatPatterns, - treeModel, - siteModel, - null, - null, - false, false, true, false, false); - - setUpExample2(); - setUpExample3(); - } - - private void setUpExample2()throws Exception{ - //taxa - ArrayList taxonList2= new ArrayList(); - Collections.addAll( - taxonList2, - new Taxon("taxon1"), - new Taxon("taxon2"), - new Taxon("taxon3"), - new Taxon("taxon4"), - new Taxon("taxon5") - ); - Taxa taxa2 = new Taxa(taxonList2); - - //msat datatype - Microsatellite msat = new Microsatellite(1,3); - Patterns msatPatterns = new Patterns(msat, taxa2); - msatPatterns.addPattern(new int[]{0, 1, 2, 1, 2}); //pattern in the correct code form. - - //create tree - NewickImporter importer = new NewickImporter("(((taxon1:1.5,taxon2:1.5):1.5,(taxon3:2.1,taxon4:2.1):0.9):0.7,taxon5:3.7);"); - Tree tree = importer.importTree(null); - - //treeModel - TreeModel treeModel = new DefaultTreeModel(tree); - - //msatsubstModel - AsymmetricQuadraticModel aqm2 = new AsymmetricQuadraticModel(msat, null); - - //siteModel - GammaSiteModel siteModel = new GammaSiteModel(aqm2); - - //treeLikelihood - treeLikelihood2 = new TreeLikelihood( - msatPatterns, - treeModel, - siteModel, - null, - null, - false, false, true, false, false); - } - - private void setUpExample3() throws Exception{ - //taxa - ArrayList taxonList3= new ArrayList(); - Collections.addAll( - taxonList3, - new Taxon("taxon1"), - new Taxon("taxon2"), - new Taxon("taxon3"), - new Taxon("taxon4"), - new Taxon("taxon5"), - new Taxon("taxon6"), - new Taxon("taxon7") - ); - Taxa taxa3 = new Taxa(taxonList3); - - //msat datatype - Microsatellite msat = new Microsatellite(1,4); - Patterns msatPatterns = new Patterns(msat, taxa3); - msatPatterns.addPattern(new int[]{0,3,1,2,3,0,1}); //pattern in the correct code form. - - //create tree - NewickImporter importer = - new NewickImporter("(((taxon1:0.3,taxon2:0.3):0.6,taxon3:0.9):0.9,((taxon4:0.5,taxon5:0.5):0.3,(taxon6:0.7,taxon7:0.7):0.1):1.0);"); - Tree tree = importer.importTree(null); - - //treeModel - TreeModel treeModel = new DefaultTreeModel(tree); - - //msatsubstModel - AsymmetricQuadraticModel aqm3 = new AsymmetricQuadraticModel(msat, null); - - //siteModel - GammaSiteModel siteModel = new GammaSiteModel(aqm3); - - //treeLikelihood - treeLikelihood3 = new TreeLikelihood( - msatPatterns, - treeModel, - siteModel, - null, - null, - false, false, true, false, false); - } - - public void testMsatFullLikelihood(){ - double logL1 = -3.29585637705580; //answer calculated by hand. - assertEquals(logL1, treeLikelihood1.getLogLikelihood(), 1e-10); - - double logL2 = -5.51026695214529; - assertEquals(logL2, treeLikelihood2.getLogLikelihood(), 1e-10); - - double logL3 = -14.39899197302407; - assertEquals(logL3, treeLikelihood3.getLogLikelihood(), 1e-10); - - - } - - - - - - - - -} diff --git a/src/test/dr/evomodel/substmodel/MsatSamplingTreeLikelihoodTest.java b/src/test/dr/evomodel/substmodel/MsatSamplingTreeLikelihoodTest.java deleted file mode 100644 index 3a8d30d568..0000000000 --- a/src/test/dr/evomodel/substmodel/MsatSamplingTreeLikelihoodTest.java +++ /dev/null @@ -1,240 +0,0 @@ -/* - * MsatSamplingTreeLikelihoodTest.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package test.dr.evomodel.substmodel; - -import dr.evolution.util.Taxon; -import dr.evolution.util.Taxa; -import dr.evolution.datatype.Microsatellite; -import dr.evolution.alignment.Patterns; -import dr.evolution.io.NewickImporter; -import dr.evolution.tree.Tree; -import dr.evomodel.tree.DefaultTreeModel; -import dr.evomodel.tree.TreeModel; -import dr.evomodel.tree.MicrosatelliteSamplerTreeModel; -import dr.oldevomodel.substmodel.AsymmetricQuadraticModel; -import dr.oldevomodel.substmodel.TwoPhaseModel; -import dr.oldevomodel.substmodel.LinearBiasModel; -import dr.oldevomodel.treelikelihood.MicrosatelliteSamplerTreeLikelihood; -import dr.evomodel.branchratemodel.BranchRateModel; -import dr.evomodel.branchratemodel.StrictClockBranchRates; -import dr.inference.model.Parameter; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; - -import junit.framework.TestCase; - -/** - * @author Chieh-Hsi Wu - */ -public class MsatSamplingTreeLikelihoodTest extends TestCase { - - MicrosatelliteSamplerTreeLikelihood eu1Likelihood; - MicrosatelliteSamplerTreeLikelihood eu2Likelihood; - MicrosatelliteSamplerTreeLikelihood ec1Likelihood; - MicrosatelliteSamplerTreeLikelihood ec2Likelihood; - MicrosatelliteSamplerTreeLikelihood el1Likelihood; - MicrosatelliteSamplerTreeLikelihood pu1Likelihood; - MicrosatelliteSamplerTreeLikelihood pu2Likelihood; - MicrosatelliteSamplerTreeLikelihood pc1Likelihood; - MicrosatelliteSamplerTreeLikelihood pc2Likelihood; - MicrosatelliteSamplerTreeLikelihood pl1Likelihood; - - - public void setUp() throws Exception{ - super.setUp(); - //taxa - ArrayList taxonList3= new ArrayList(); - Collections.addAll( - taxonList3, - new Taxon("Taxon1"), - new Taxon("Taxon2"), - new Taxon("Taxon3"), - new Taxon("Taxon4"), - new Taxon("Taxon5"), - new Taxon("Taxon6"), - new Taxon("Taxon7") - ); - Taxa taxa3 = new Taxa(taxonList3); - - //msat datatype - Microsatellite msat = new Microsatellite(1,6); - Patterns msatPatterns = new Patterns(msat, taxa3); - msatPatterns.addPattern(new int[]{0,1,3,2,4,5,1}); //pattern in the correct code form. - - //create tree - NewickImporter importer = - new NewickImporter("(((Taxon1:0.3,Taxon2:0.3):0.6,Taxon3:0.9):0.9,((Taxon4:0.5,Taxon5:0.5):0.3,(Taxon6:0.7,Taxon7:0.7):0.1):1.0);"); - Tree tree = importer.importTree(null); - - //treeModel - TreeModel treeModel = new DefaultTreeModel(tree); - - //msatsubstModel - AsymmetricQuadraticModel eu1 = new AsymmetricQuadraticModel(msat, null); - - - //create msatSamplerTreeModel - Parameter internalVal = new Parameter.Default(new double[]{2, 3, 4, 2, 1, 5}); - int[] externalValues = msatPatterns.getPattern(0); - HashMap taxaMap = new HashMap(externalValues.length); - boolean internalValuesProvided = true; - for(int i = 0; i < externalValues.length; i++){ - taxaMap.put(msatPatterns.getTaxonId(i),i); - } - MicrosatelliteSamplerTreeModel msatTreeModel = new MicrosatelliteSamplerTreeModel("JUnitTestEx", treeModel, internalVal, msatPatterns, externalValues, taxaMap, internalValuesProvided); - - //create msatSamplerTreeLikelihood - BranchRateModel branchRateModel = new StrictClockBranchRates(new Parameter.Default(1.0)); - eu1Likelihood = new MicrosatelliteSamplerTreeLikelihood(msatTreeModel,eu1, branchRateModel); - - - //eu2 - TwoPhaseModel eu2 = new TwoPhaseModel( - msat, - null, - eu1, - new Parameter.Default(0.0), - new Parameter.Default(0.4), - null, - false - ); - eu2Likelihood = new MicrosatelliteSamplerTreeLikelihood(msatTreeModel,eu2, branchRateModel); - - - //ec1 - LinearBiasModel ec1 = new LinearBiasModel( - msat, - null, - eu1, - new Parameter.Default(0.48), - new Parameter.Default(0.0), - false, - false, - false - ); - ec1Likelihood = new MicrosatelliteSamplerTreeLikelihood(msatTreeModel,ec1, branchRateModel); - - //ec2 - TwoPhaseModel ec2 = new TwoPhaseModel( - msat, - null, - ec1, - new Parameter.Default(0.0), - new Parameter.Default(0.4), - null, - false - ); - ec2Likelihood = new MicrosatelliteSamplerTreeLikelihood(msatTreeModel,ec2, branchRateModel); - - //el1 - LinearBiasModel el1 = new LinearBiasModel( - msat, - null, - eu1, - new Parameter.Default(0.2), - new Parameter.Default(-0.018), - true, - false, - false - ); - el1Likelihood = new MicrosatelliteSamplerTreeLikelihood(msatTreeModel,el1, branchRateModel); - - AsymmetricQuadraticModel pu1 = new AsymmetricQuadraticModel( - msat, - null, - new Parameter.Default(1.0), - new Parameter.Default(0.015), - new Parameter.Default(0.0), - new Parameter.Default(1.0), - new Parameter.Default(0.015), - new Parameter.Default(0.0), - false - ); - - pu1Likelihood = new MicrosatelliteSamplerTreeLikelihood(msatTreeModel,pu1, branchRateModel); - - - //ec2 - TwoPhaseModel pu2 = new TwoPhaseModel( - msat, - null, - pu1, - new Parameter.Default(0.0), - new Parameter.Default(0.4), - null, - false - ); - pu2Likelihood = new MicrosatelliteSamplerTreeLikelihood(msatTreeModel,pu2, branchRateModel); - - //ec1 - LinearBiasModel pc1 = new LinearBiasModel( - msat, - null, - pu1, - new Parameter.Default(0.48), - new Parameter.Default(0.0), - false, - false, - false - ); - pc1Likelihood = new MicrosatelliteSamplerTreeLikelihood(msatTreeModel,pc1, branchRateModel); - - - } - - public void testMsatSamplerTreeLikelihood(){ - double eu1LogLik = -40.83979410253295; - assertEquals(eu1LogLik, eu1Likelihood.getLogLikelihood(), 1e-10); - - double eu2LogLik = -31.06158432691919; - assertEquals(eu2LogLik, eu2Likelihood.getLogLikelihood(), 1e-10); - - double ec1LogLik = -40.78984094007343; - assertEquals(ec1LogLik, ec1Likelihood.getLogLikelihood(), 1e-10); - - double ec2LogLik = -31.0303143412092; - assertEquals(ec2LogLik, ec2Likelihood.getLogLikelihood(), 1e-10); - - double el1LogLik = -40.8979343964233; - assertEquals(el1LogLik, el1Likelihood.getLogLikelihood(), 1e-10); - - double pu1LogLik = -40.8068080725352; - assertEquals(pu1LogLik, pu1Likelihood.getLogLikelihood(), 1e-10); - - double pu2LogLik = -31.07280789202575; - assertEquals(pu2LogLik, pu2Likelihood.getLogLikelihood(), 1e-10); - - double pc1LogLik = -40.7148747667439; - assertEquals(pc1LogLik, pc1Likelihood.getLogLikelihood(), 1e-10); - - } - - -} diff --git a/src/test/dr/evomodel/substmodel/TN93Test.java b/src/test/dr/evomodel/substmodel/TN93Test.java index 98f8790005..ce307d3fe5 100644 --- a/src/test/dr/evomodel/substmodel/TN93Test.java +++ b/src/test/dr/evomodel/substmodel/TN93Test.java @@ -28,8 +28,8 @@ package test.dr.evomodel.substmodel; import dr.evolution.datatype.Nucleotides; -import dr.oldevomodel.substmodel.FrequencyModel; -import dr.oldevomodel.substmodel.TN93; +import dr.evomodel.substmodel.FrequencyModel; +import dr.evomodel.substmodel.nucleotide.TN93; import dr.inference.model.Parameter; import junit.framework.TestCase; diff --git a/src/test/dr/evomodel/substmodel/TimeIrreversibleTest.java b/src/test/dr/evomodel/substmodel/TimeIrreversibleTest.java index eef61bc2fa..82264da6fd 100644 --- a/src/test/dr/evomodel/substmodel/TimeIrreversibleTest.java +++ b/src/test/dr/evomodel/substmodel/TimeIrreversibleTest.java @@ -28,9 +28,9 @@ package test.dr.evomodel.substmodel; import dr.evolution.datatype.DataType; -import dr.oldevomodel.substmodel.ComplexSubstitutionModel; -import dr.oldevomodel.substmodel.FrequencyModel; -import dr.oldevomodel.substmodel.SVSComplexSubstitutionModel; +import dr.evomodel.substmodel.ComplexSubstitutionModel; +import dr.evomodel.substmodel.FrequencyModel; +import dr.evomodel.substmodel.SVSComplexSubstitutionModel; import dr.inference.model.Parameter; import junit.framework.TestCase; diff --git a/src/test/dr/evomodel/substmodel/TwoPhaseModelTest.java b/src/test/dr/evomodel/substmodel/TwoPhaseModelTest.java deleted file mode 100644 index 9261e00aab..0000000000 --- a/src/test/dr/evomodel/substmodel/TwoPhaseModelTest.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - * TwoPhaseModelTest.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package test.dr.evomodel.substmodel; - -import dr.oldevomodel.substmodel.AsymmetricQuadraticModel; -import dr.oldevomodel.substmodel.OnePhaseModel; -import dr.oldevomodel.substmodel.TwoPhaseModel; -import junit.framework.TestCase; -import dr.evolution.datatype.Microsatellite; -import dr.evomodel.substmodel.*; -import dr.inference.model.Parameter; - -/** - * @author Chieh-Hsi Wu - * - * JUnit test for TwoPhaseModel of microsatellites - * - */ -public class TwoPhaseModelTest extends TestCase { - interface Instance { - - public OnePhaseModel getSubModel(); - - double getPParam(); - - double getMParam(); - - double getDistance(); - - double[] getPi(); - - public double[] getExpectedResult(); - } - - Instance test0 = new Instance() { - - public OnePhaseModel getSubModel(){ - return new AsymmetricQuadraticModel(new Microsatellite(1,6), null); - } - - public double getPParam(){ - return 0.75; - } - - public double getMParam(){ - return 0.58; - } - - public double getDistance(){ - return 0.94; - } - - public double[] getPi(){ - return new double[]{0.18744637901040673, 0.1607567474109271, 0.15179687357866556, 0.15179687357866556, 0.16075674741092702, 0.18744637901040695}; - } - - public double[] getExpectedResult(){ - return new double[]{ - 0.63398241451779758, 0.23675486586787650, 0.07330431013568975, 0.02919578818459456, 0.01589013386525921, 0.01087248742878196, - 0.27524752392268953, 0.42098887984631489, 0.19147132450808460, 0.06606140653506744, 0.02837812583210070, 0.01785273935574281, - 0.09233761983753200, 0.20121070458110243, 0.40820601172807069, 0.19248802732743994, 0.06994493808030816, 0.03581269844554699, - 0.03581269844554700, 0.06994493808030799, 0.19248802732743994, 0.40820601172807053, 0.20121070458110252, 0.09233761983753204, - 0.01785273935574278, 0.02837812583210064, 0.06606140653506756, 0.19147132450808424, 0.42098887984631500, 0.27524752392268970, - 0.01087248742878200, 0.01589013386525917, 0.02919578818459453, 0.07330431013568960, 0.23675486586787683, 0.63398241451779769 - }; - } - - }; - - Instance[] all = {test0}; - - - public void testTwoPhaseModel() { - - for (Instance test : all) { - - OnePhaseModel subModel = test.getSubModel(); - Microsatellite microsat = (Microsatellite)subModel.getDataType(); - Parameter pParam = new Parameter.Default(test.getPParam()); - Parameter mParam = new Parameter.Default(test.getMParam()); - - - - TwoPhaseModel tpm = new TwoPhaseModel(microsat, null, subModel, pParam, mParam, null,false); - - int k; - - tpm.computeStationaryDistribution(); - double[] statDist = tpm.getStationaryDistribution(); - final double[] expectedStatDist = test.getPi(); - for (k = 0; k < statDist.length; ++k) { - assertEquals(statDist[k], expectedStatDist[k], 1e-10); - } - - int stateCount = microsat.getStateCount(); - double[] mat = new double[stateCount*stateCount]; - tpm.getTransitionProbabilities(test.getDistance(), mat); - final double[] result = test.getExpectedResult(); - - - for (k = 0; k < mat.length; ++k) { - assertEquals(result[k], mat[k], 5e-9); - //System.out.print(" " + (mat[k]));// - result[k])); - } - - k = 0; - for(int i = 0; i < microsat.getStateCount(); i ++){ - for(int j = 0; j < microsat.getStateCount(); j ++){ - assertEquals(result[k++], tpm.getOneTransitionProbabilityEntry(test.getDistance(), i , j), 1e-10); - - } - } - - for(int j = 0; j < microsat.getStateCount();j ++){ - double[] colTransitionProb = tpm.getColTransitionProbabilities(test.getDistance(), j); - for(int i =0 ; i < microsat.getStateCount(); i++){ - assertEquals(result[i*microsat.getStateCount()+j], colTransitionProb[i], 1e-10); - } - } - - - - for(int i = 0; i < microsat.getStateCount();i ++){ - double[] rowTransitionProb = tpm.getRowTransitionProbabilities(test.getDistance(), i); - for(int j =0 ; j < microsat.getStateCount(); j++){ - assertEquals(result[i*microsat.getStateCount()+j], rowTransitionProb[j], 1e-10); - } - } - } - - } - - -} diff --git a/src/test/dr/evomodel/substmodel/TwoStateCovarionModelTest.java b/src/test/dr/evomodel/substmodel/TwoStateCovarionModelTest.java deleted file mode 100644 index 3e3e6e740e..0000000000 --- a/src/test/dr/evomodel/substmodel/TwoStateCovarionModelTest.java +++ /dev/null @@ -1,318 +0,0 @@ -/* - * TwoStateCovarionModelTest.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package test.dr.evomodel.substmodel; - -import dr.evolution.datatype.DataType; -import dr.evolution.datatype.TwoStateCovarion; -import dr.oldevomodel.substmodel.FrequencyModel; -import dr.oldevomodel.substmodel.SubstitutionModelUtils; -import dr.oldevomodel.substmodel.TwoStateCovarionModel; -import dr.inference.model.Parameter; -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - -/** - * TwoStateCovarionModel Tester. - * - * @author Alexei Drummond - */ -public class TwoStateCovarionModelTest extends TestCase { - public TwoStateCovarionModelTest(String name) { - super(name); - } - - public void setUp() throws Exception { - super.setUp(); - - frequencies = new Parameter.Default(new double[]{0.25, 0.25, 0.25, 0.25}); - alpha = new Parameter.Default(0.0); - switchingRate = new Parameter.Default(1.0); - - FrequencyModel freqModel = new FrequencyModel(TwoStateCovarion.INSTANCE, frequencies); - model = new TwoStateCovarionModel(TwoStateCovarion.INSTANCE, freqModel, alpha, switchingRate); - dataType = model.getDataType(); - } - - public void testTransitionProbabilities() { - - // with alpha == 1, the transition probability should be the same as binary jukes cantor - alpha.setParameterValue(0, 1.0); - switchingRate.setParameterValue(0, 1.0); - - model.setupMatrix(); - - double[] matrix = new double[16]; - - double[] pi = model.getFrequencyModel().getFrequencies(); - - for (double distance = 0.01; distance <= 1; distance += 0.01) { - model.getTransitionProbabilities(distance, matrix); - - double pChange = - (matrix[1] + matrix[3]) * pi[0] + - (matrix[4] + matrix[6]) * pi[1] + - (matrix[9] + matrix[11]) * pi[2] + - (matrix[12] + matrix[14]) * pi[3]; - - // analytical result for the probability of a mismatch in binary jukes cantor model - double jc = 0.5 * (1 - Math.exp(-2.0 * distance)); - -// System.err.println("Testing d=" + distance); - assertEquals(pChange, jc, 1e-14); - } - } - /* - public void testCompareToScilabCode() { - - // test against Scilab results for alpha = 0.0 and switching rate = 1.0, visible state freq = {0.25, 0.75} - - frequencies = new Parameter.Default(new double[]{0.125, 0.125, 0.375, 0.375}); - - FrequencyModel freqModel = new FrequencyModel(TwoStateCovarion.INSTANCE, frequencies); - model = new TwoStateCovarionModel(TwoStateCovarion.INSTANCE, freqModel, alpha, switchingRate); - dataType = model.getDataType(); - - alpha.setParameterValue(0, 0.5); - switchingRate.setParameterValue(0, 1.0); - - model.setupMatrix(); - - double[] matrix = new double[16]; - - double[] pi = model.getFrequencyModel().getFrequencies(); - - model.setupMatrix(); - - int index = 0; - for (double distance = 0.01; distance <= 1.005; distance += 0.01) { - model.getTransitionProbabilities(distance, matrix); - - double pChange = - (matrix[1] + matrix[3]) * pi[0] + - (matrix[4] + matrix[6]) * pi[1] + - (matrix[9] + matrix[11]) * pi[2] + - (matrix[12] + matrix[14]) * pi[3]; - - //System.out.println(distance + "\t" + pChange + "\t"); - - double pChangeIndependent = matLabPChange[index]; - - System.err.println("Testing against scilab d=" + distance); - assertEquals(pChange, pChangeIndependent, 1e-14); - - index += 1; - } - } */ - - public void testSetupRelativeRates() throws Exception { - - model.setupMatrix(); - - assertEquals(alpha.getParameterValue(0), model.getRelativeRates()[0], 1e-8); - assertEquals(switchingRate.getParameterValue(0), model.getRelativeRates()[1], 1e-8); - assertEquals(0.0, model.getRelativeRates()[2], 1e-8); - assertEquals(0.0, model.getRelativeRates()[3], 1e-8); - assertEquals(switchingRate.getParameterValue(0), model.getRelativeRates()[4], 1e-8); - assertEquals(1.0, model.getRelativeRates()[5], 1e-8); - } - - public void testNormalize() { - - model.setupMatrix(); - - double[] pi = model.getFrequencyModel().getFrequencies(); - - int stateCount = dataType.getStateCount(); - - double totalRate = 0.0; - for (int i = 0; i < stateCount; i++) { - for (int j = 0; j < stateCount; j++) { - int diff = Math.abs(i - j); - if (diff != 2 && diff != 0) { - totalRate += model.getQ()[i][j] * pi[i]; - } - } - } - - System.out.println(SubstitutionModelUtils.toString(model.getQ(), dataType, 2)); - - assertEquals(1.0, totalRate, 1e-8); - } - - public static Test suite() { - return new TestSuite(TwoStateCovarionModelTest.class); - } - - TwoStateCovarionModel model; - DataType dataType; - Parameter frequencies; - Parameter switchingRate; - Parameter alpha; - - - /* - // The following Scilab code was written by Alexei Drummond - // (adapted from Matlab code by David Bryant) - - Q = [-1,1;1,-1]; - - // frequencies of visible states - pi = diag([0.25,0.75]); - - Q = Q*pi; - - G = [-1,1;1,-1]; - D = diag([0.5,1]); - I = eye(2,2); - R = kron(D,Q) + kron(G, I); - - // frequencies of hidden states - f = diag([0.5, 0.5]); - - // frequencies of big matrix - pif = kron(f, pi); - - C = [0,1,0,1;1,0,1,0;0,1,0,1;1,0,1,0] - - rate = sum(sum(C.*(pif*R))) - - Rn = R/rate; - - for i = 1:1:100 - t = i*0.01; - P = expm(Rn*t); - pchange(i) = sum(sum(C .*(pif*P))); - end; - - - */ - static final double[] matLabPChange = { - 0.009853754858257556, - 0.01942241145387763, - 0.028716586161758886, - 0.03774630552222203, - 0.046521051427055954, - 0.055049802312796506, - 0.06334107073053451, - 0.07140293762693993, - 0.07924308363985522, - 0.08686881768339709, - 0.09428710307179183, - 0.1015045814078466, - 0.10852759444084098, - 0.11536220407949097, - 0.1220142107282943, - 0.12848917009986108, - 0.134792408641597, - 0.14092903770220686, - 0.14690396655180843, - 0.15272191435884597, - 0.15838742121740867, - 0.16390485830985116, - 0.1692784372817475, - 0.17451221889905671, - 0.17961012105092147, - 0.18457592615563362, - 0.18941328802201546, - 0.19412573821362156, - 0.1987166919588106, - 0.20318945364578556, - 0.20754722193809755, - 0.21179309454286796, - 0.21593007266103278, - 0.2199610651462345, - 0.2238888923965756, - 0.22771629000123267, - 0.231445912161957, - 0.23508033490766292, - 0.23862205911867845, - 0.2420735133757424, - 0.24543705664747917, - 0.24871498082886684, - 0.25190951314210097, - 0.2550228184102454, - 0.25805700121315506, - 0.2610141079343201, - 0.26389612870652945, - 0.26670499926357183, - 0.2694426027045621, - 0.2721107711769275, - 0.27471128748357165, - 0.27724588661926514, - 0.27971625724089505, - 0.2821240430758165, - 0.2844708442722035, - 0.28675821869497176, - 0.28898768317056994, - 0.2911607146836553, - 0.2932787515284428, - 0.29534319441730017, - 0.2973554075489424, - 0.2993167196384335, - 0.30122842491099766, - 0.3030917840615263, - 0.3049080251815066, - 0.30667834465498195, - 0.3084039080250403, - 0.31008585083221957, - 0.3117252794261185, - 0.3133232717514247, - 0.314880878109485, - 0.3163991218964633, - 0.3178790003190806, - 0.31932148508884917, - 0.3207275230956765, - 0.3220980370616438, - 0.3234339261757309, - 0.3247360667102066, - 0.32600531261936083, - 0.32724249612123, - 0.3284484282629134, - 0.32962389947006454, - 0.33076968008109947, - 0.33188652086664117, - 0.3329751535346926, - 0.3340362912220076, - 0.3350706289721107, - 0.3360788442003818, - 0.337061597146628, - 0.33801953131551693, - 0.33895327390525487, - 0.3398634362248641, - 0.34075061410039437, - 0.3416153882704134, - 0.34245832477107263, - 0.34327997531106624, - 0.3440808776367703, - 0.34486155588783984, - 0.34562252094354134, - 0.3463642707600772 - }; - -} diff --git a/src/test/dr/evomodel/substmodel/testNtdBMA.java b/src/test/dr/evomodel/substmodel/testNtdBMA.java deleted file mode 100644 index 49ea74613d..0000000000 --- a/src/test/dr/evomodel/substmodel/testNtdBMA.java +++ /dev/null @@ -1,397 +0,0 @@ -/* - * testNtdBMA.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package test.dr.evomodel.substmodel; - -import junit.framework.TestCase; -import dr.inference.model.Parameter; -import dr.inference.model.Variable; -import dr.oldevomodel.substmodel.FrequencyModel; -import dr.oldevomodel.substmodel.NtdBMA; -import dr.evolution.datatype.Nucleotides; - -/** - * @author Chieh-Hsi Wu - * - * JUnit test for NtdBMA model - */ -public class testNtdBMA extends TestCase { - interface Instance { - double[] getPi(); - - double getLogKappa(); - - double getLogTN(); - - double getLogAC(); - - double getLogAT(); - double getLogGC(); - double getLogGT(); - Variable getModelChoose(); - - double getDistance(); - - double[] getExpectedResult(); - } - - /* - * Results obtained by running the following scilab code, - * - * k = 5 ; piQ = diag([.2, .3, .25, .25]) ; d = 0.1 ; - * % Q matrix with zeroed diagonal - * XQ = [0 1 k 1; 1 0 1 k; k 1 0 1; 1 k 1 0]; - * - * xx = XQ * piQ ; - * - * % fill diagonal and normalize by total substitution rate - * q0 = (xx + diag(-sum(xx,2))) / sum(piQ * sum(xx,2)) ; - * expm(q0 * d) - */ - - //A HKY model - Instance test0 = new Instance() { - public double[] getPi() { - return new double[]{0.25, 0.25, 0.25, 0.25}; - } - - public double getLogKappa() { - return Math.log(2); - } - - public double getLogTN(){ - return Math.log(1.2); - } - - public double getLogAC(){ - return Math.log(0.5); - } - - public double getLogAT(){ - return Math.log(0.5); - } - - public double getLogGC(){ - return Math.log(0.5); - } - public double getLogGT(){ - return Math.log(0.5); - } - - public Variable getModelChoose(){ - return new Variable.I(new int[]{0, 0}); - } - - public double getDistance() { - return 0.1; - } - - public double[] getExpectedResult() { - return new double[]{ - 0.906563342722, 0.023790645491, 0.045855366296, 0.023790645491, - 0.023790645491, 0.906563342722, 0.023790645491, 0.045855366296, - 0.045855366296, 0.023790645491, 0.906563342722, 0.023790645491, - 0.023790645491, 0.045855366296, 0.023790645491, 0.906563342722 - }; - } - }; - - //A TN93 model - Instance test1 = new Instance() { - public double[] getPi() { - return new double[]{0.1, 0.2, 0.3, 0.4}; - } - - public double getLogKappa() { - return Math.log(3)-0.5*Math.log(1.5); - } - - public double getLogTN(){ - return -0.5*Math.log(1.5); - } - - public double getLogAC(){ - return Math.log(0.5); - } - - public double getLogAT(){ - return Math.log(0.5); - } - - public double getLogGC(){ - return Math.log(0.5); - } - public double getLogGT(){ - return Math.log(0.5); - } - - public Variable getModelChoose(){ - return new Variable.I(new int[]{1, 0}); - } - - - public double getDistance() { - return 0.1; - } - - public double[] getExpectedResult() { - return new double[]{ - 0.895550254199242, 0.017687039418335, 0.051388627545752, 0.035374078836670, - 0.008843519709168, 0.865344657365451, 0.026530559127503, 0.099281263797879, - 0.017129542515251, 0.017687039418335, 0.929809339229744, 0.035374078836670, - 0.008843519709168, 0.049640631898940, 0.026530559127503, 0.914985289264390 - }; - } - }; - - //GTR example - Instance test2 = new Instance() { - public double[] getPi() { - return new double[]{0.20, 0.30, 0.25, 0.25}; - } - - public double getLogKappa() { - return Math.log(3)-0.5*Math.log(1.5); - } - - public double getLogTN(){ - return -0.5*Math.log(1.5); - } - - public double getLogAC(){ - return Math.log(1.2); - } - - public double getLogAT(){ - return Math.log(0.6); - } - - public double getLogGC(){ - return Math.log(0.5); - } - public double getLogGT(){ - return Math.log(0.8); - } - - public Variable getModelChoose(){ - return new Variable.I(new int[]{1, 1}); - } - - public double getDistance() { - return 0.1; - } - - public double[] getExpectedResult() { - return new double[]{ - 0.9078362845301, 0.0325116185198, 0.0449673267333, 0.0146847702168, - 0.0216744123465, 0.9006273487178, 0.0122790622489, 0.0654191766868, - 0.0359738613867, 0.0147348746987, 0.9308468616493, 0.0184444022654, - 0.0117478161734, 0.0785030120241, 0.0184444022654, 0.8913047695370 - }; - } - }; - - Instance test3 = new Instance() { - public double[] getPi() { - return new double[]{0.25, 0.25, 0.25, 0.25}; - } - - public double getLogKappa() { - return Math.log(2); - } - - public double getLogTN(){ - return Math.log(1.2); - } - - public double getLogAC(){ - return Math.log(0.5); - } - - public double getLogAT(){ - return Math.log(0.5); - } - - public double getLogGC(){ - return Math.log(0.5); - } - public double getLogGT(){ - return Math.log(0.5); - } - - public Variable getModelChoose(){ - return new Variable.I(new int[]{0, 0}); - } - - public double getDistance() { - return 1.8; - } - - public double[] getExpectedResult() { - return new double[]{ - 0.324927478425, 0.208675277945, 0.257721965686, 0.208675277945, - 0.208675277945, 0.324927478425, 0.208675277945, 0.257721965686, - 0.257721965686, 0.208675277945, 0.324927478425, 0.208675277945, - 0.208675277945, 0.257721965686, 0.208675277945, 0.324927478425 - }; - } - }; - - Instance test4 = new Instance() { - public double[] getPi() { - return new double[]{0.1, 0.2, 0.3, 0.4}; - } - - public double getLogKappa() { - return Math.log(3)-0.5*Math.log(1.5); - } - - public double getLogTN(){ - return -0.5*Math.log(1.5); - } - - public double getLogAC(){ - return Math.log(0.5); - } - - public double getLogAT(){ - return Math.log(0.5); - } - - public double getLogGC(){ - return Math.log(0.5); - } - public double getLogGT(){ - return Math.log(0.5); - } - - public Variable getModelChoose(){ - return new Variable.I(new int[]{1, 0}); - } - - - public double getDistance() { - return 2.5; - } - - public double[] getExpectedResult() { - return new double[]{ - 0.144168843021, 0.180243104854, 0.315101842417, 0.360486209708, - 0.090121552427, 0.217265980316, 0.270364657281, 0.422247809976, - 0.105033947472, 0.180243104854, 0.354236737965, 0.360486209708, - 0.090121552427, 0.211123904988, 0.270364657281, 0.428389885304 - }; - } - }; - - //GTR example - Instance test5 = new Instance() { - public double[] getPi() { - return new double[]{0.20, 0.30, 0.25, 0.25}; - } - - public double getLogKappa() { - return Math.log(3)-0.5*Math.log(1.5); - } - - public double getLogTN(){ - return -0.5*Math.log(1.5); - } - - public double getLogAC(){ - return Math.log(1.2); - } - - public double getLogAT(){ - return Math.log(0.6); - } - - public double getLogGC(){ - return Math.log(0.5); - } - public double getLogGT(){ - return Math.log(0.8); - } - - public Variable getModelChoose(){ - return new Variable.I(new int[]{1, 1}); - } - - public double getDistance() { - return 2.5; - } - - public double[] getExpectedResult() { - return new double[]{ - 0.246055801088, 0.266163561908, 0.273492078437, 0.214288558567, - 0.177442374606, 0.341245862774, 0.202456669039, 0.278855093581, - 0.218793662750, 0.242948002847, 0.333259562500, 0.204998771904, - 0.171430846853, 0.334626112297, 0.204998771904, 0.288944268946 - }; - } - }; - - Instance[] all = {test0,test1,test2,test3,test4,test5}; - - public void testNtdBMA() { - for (Instance test : all) { - Parameter logKappa = new Parameter.Default(1, test.getLogKappa()); - Parameter logTN = new Parameter.Default(1, test.getLogTN()); - Parameter logAC = new Parameter.Default(1, test.getLogAC()); - Parameter logAT = new Parameter.Default(1, test.getLogAT()); - Parameter logGC = new Parameter.Default(1, test.getLogGC()); - Parameter logGT = new Parameter.Default(1, test.getLogGT()); - Variable modelChoose = test.getModelChoose(); - - double[] pi = test.getPi(); - - Parameter freqs = new Parameter.Default(pi); - FrequencyModel f = new FrequencyModel(Nucleotides.INSTANCE, freqs); - NtdBMA ntdBMA = new NtdBMA( - logKappa, - logTN, - logAC, - logAT, - logGC, - logGT, - modelChoose, - f - ); - - double distance = test.getDistance(); - - double[] mat = new double[4 * 4]; - ntdBMA.getTransitionProbabilities(distance, mat); - final double[] result = test.getExpectedResult(); - - for (int k = 0; k < mat.length; ++k) { - assertEquals(mat[k], result[k], 5e-10); - // System.out.print(" " + (mat[k] - result[k])); - } - } - } -} diff --git a/src/test/dr/evomodel/treelikelihood/AncestralStateTreeLikelihoodTest.java b/src/test/dr/evomodel/treelikelihood/AncestralStateTreeLikelihoodTest.java index 8850927ce2..c398f46bdc 100644 --- a/src/test/dr/evomodel/treelikelihood/AncestralStateTreeLikelihoodTest.java +++ b/src/test/dr/evomodel/treelikelihood/AncestralStateTreeLikelihoodTest.java @@ -27,26 +27,39 @@ package test.dr.evomodel.treelikelihood; +import dr.evolution.alignment.PatternList; import dr.evolution.alignment.SimpleAlignment; +import dr.evolution.datatype.DataType; import dr.evolution.datatype.Nucleotides; import dr.evolution.io.NewickImporter; import dr.evolution.sequence.Sequence; import dr.evolution.tree.FlexibleTree; +import dr.evolution.tree.MutableTreeModel; import dr.evolution.tree.TreeTraitProvider; import dr.evolution.tree.TreeUtils; import dr.evolution.util.Taxa; import dr.evolution.util.Taxon; +import dr.evomodel.branchmodel.BranchModel; +import dr.evomodel.branchmodel.HomogeneousBranchModel; +import dr.evomodel.branchratemodel.BranchRateModel; import dr.evomodel.branchratemodel.StrictClockBranchRates; +import dr.evomodel.siteratemodel.DiscretizedSiteRateModel; +import dr.evomodel.siteratemodel.HomogeneousRateDelegate; +import dr.evomodel.siteratemodel.SiteRateModel; +import dr.evomodel.substmodel.FrequencyModel; +import dr.evomodel.substmodel.nucleotide.HKY; +import dr.evomodel.tipstatesmodel.TipStatesModel; import dr.evomodel.tree.DefaultTreeModel; -import dr.oldevomodel.sitemodel.GammaSiteModel; -import dr.oldevomodel.substmodel.FrequencyModel; -import dr.oldevomodel.substmodel.HKY; import dr.evomodel.tree.TreeModel; -import dr.oldevomodel.treelikelihood.AncestralStateTreeLikelihood; +import dr.evomodel.treelikelihood.AncestralStateBeagleTreeLikelihood; +import dr.evomodel.treelikelihood.PartialsRescalingScheme; import dr.inference.model.Parameter; import dr.math.MathUtils; import junit.framework.TestCase; +import java.util.Map; +import java.util.Set; + /** * @author Alexei Drummond * @author Marc Suchard @@ -102,10 +115,16 @@ public void testJointLikelihood() { FrequencyModel f = new FrequencyModel(Nucleotides.INSTANCE, freqs); HKY hky = new HKY(kappa, f); - AncestralStateTreeLikelihood treeLikelihood = new AncestralStateTreeLikelihood( - alignment, treeModel, - new GammaSiteModel(hky), new StrictClockBranchRates(mu), - false, true, + AncestralStateBeagleTreeLikelihood treeLikelihood = new AncestralStateBeagleTreeLikelihood( + alignment, + treeModel, + new HomogeneousBranchModel(hky), + new DiscretizedSiteRateModel(""), + new StrictClockBranchRates(mu), + null, + false, PartialsRescalingScheme.DEFAULT, + false, + null, Nucleotides.INSTANCE, "state", false, @@ -117,7 +136,7 @@ public void testJointLikelihood() { StringBuffer buffer = new StringBuffer(); TreeUtils.newick(treeModel, treeModel.getRoot(), false, TreeUtils.BranchLengthType.LENGTHS_AS_TIME, - null, null, new TreeTraitProvider[] { treeLikelihood }, null, buffer); + null, null, new TreeTraitProvider[] { treeLikelihood }, null, buffer); System.out.println(buffer); diff --git a/src/test/dr/evomodel/treelikelihood/LikelihoodTest.java b/src/test/dr/evomodel/treelikelihood/LikelihoodTest.java index f0be01bae5..4cf4d851c5 100644 --- a/src/test/dr/evomodel/treelikelihood/LikelihoodTest.java +++ b/src/test/dr/evomodel/treelikelihood/LikelihoodTest.java @@ -30,15 +30,22 @@ import dr.evolution.alignment.SitePatterns; import dr.evolution.datatype.Nucleotides; import dr.evolution.tree.TreeUtils; -import dr.oldevomodel.sitemodel.GammaSiteModel; -import dr.oldevomodel.substmodel.FrequencyModel; -import dr.oldevomodel.substmodel.GTR; -import dr.oldevomodel.substmodel.HKY; +import dr.evomodel.branchmodel.HomogeneousBranchModel; +import dr.evomodel.siteratemodel.DiscretizedSiteRateModel; +import dr.evomodel.siteratemodel.GammaSiteRateModel; +import dr.evomodel.siteratemodel.SiteRateModel; +import dr.evomodel.substmodel.FrequencyModel; +import dr.evomodel.substmodel.SubstitutionModel; +import dr.evomodel.substmodel.nucleotide.GTR; +import dr.evomodel.substmodel.nucleotide.HKY; import dr.evomodel.tree.TreeModel; -import dr.oldevomodel.treelikelihood.TreeLikelihood; -import dr.oldevomodelxml.sitemodel.GammaSiteModelParser; -import dr.oldevomodelxml.substmodel.GTRParser; -import dr.oldevomodelxml.substmodel.HKYParser; +import dr.evomodel.treedatalikelihood.BeagleDataLikelihoodDelegate; +import dr.evomodel.treedatalikelihood.PreOrderSettings; +import dr.evomodel.treedatalikelihood.TreeDataLikelihood; +import dr.evomodel.treelikelihood.PartialsRescalingScheme; +import dr.evomodelxml.siteratemodel.GammaSiteRateModelParser; +import dr.evomodelxml.substmodel.GTRParser; +import dr.evomodelxml.substmodel.HKYParser; import dr.inference.model.Parameter; import dr.inference.model.Variable; import junit.framework.Test; @@ -48,6 +55,9 @@ import java.text.NumberFormat; import java.util.Locale; +import static dr.evomodelxml.siteratemodel.SiteModelParser.MUTATION_RATE; +import static dr.evomodelxml.siteratemodel.SiteModelParser.SITE_MODEL; + /** * @author Walter Xie @@ -77,10 +87,26 @@ public void testNewickTree() { System.out.println("\nTest Simple Node to convert Newick Tree:"); String expectedNewickTree = "((((human:0.024003,(chimp:0.010772,bonobo:0.010772):0.013231):0.012035," + "gorilla:0.036038):0.033087,orangutan:0.069125):0.030457,siamang:0.099582);"; - + assertEquals("Fail to covert the correct tree !!!", expectedNewickTree, TreeUtils.newick(treeModel, 6)); } + private TreeDataLikelihood getTreeDataLikelihood(SubstitutionModel substitutionModel, SiteRateModel siteRateModel) { + //siteModel + if (siteRateModel == null) { + siteRateModel = new DiscretizedSiteRateModel(""); + } + + //treeLikelihood + SitePatterns patterns = new SitePatterns(alignment, null, 0, -1, 1, true); + + return new TreeDataLikelihood( + new BeagleDataLikelihoodDelegate(treeModel, patterns, + new HomogeneousBranchModel(substitutionModel), siteRateModel, true, + false, PartialsRescalingScheme.DEFAULT, false, PreOrderSettings.getDefault()), + treeModel, null + ); + } public void testLikelihoodJC69() { @@ -92,20 +118,12 @@ public void testLikelihoodJC69() { FrequencyModel f = new FrequencyModel(Nucleotides.INSTANCE, freqs); HKY hky = new HKY(kappa, f); - //siteModel - GammaSiteModel siteModel = new GammaSiteModel(hky); - Parameter mu = new Parameter.Default(GammaSiteModelParser.MUTATION_RATE, 1.0, 0, Double.POSITIVE_INFINITY); - siteModel.setMutationRateParameter(mu); - - //treeLikelihood - SitePatterns patterns = new SitePatterns(alignment, null, 0, -1, 1, true); - - TreeLikelihood treeLikelihood = new TreeLikelihood(patterns, treeModel, siteModel, null, null, - false, false, true, false, false); + TreeDataLikelihood treeLikelihood = getTreeDataLikelihood(hky, null); assertEquals("treeLikelihoodJC69", format.format(-1992.20564), format.format(treeLikelihood.getLogLikelihood())); } + public void testLikelihoodK80() { System.out.println("\nTest Likelihood using K80:"); // Sub model @@ -116,15 +134,7 @@ public void testLikelihoodK80() { HKY hky = new HKY(kappa, f); //siteModel - GammaSiteModel siteModel = new GammaSiteModel(hky); - Parameter mu = new Parameter.Default(GammaSiteModelParser.MUTATION_RATE, 1.0, 0, Double.POSITIVE_INFINITY); - siteModel.setMutationRateParameter(mu); - - //treeLikelihood - SitePatterns patterns = new SitePatterns(alignment, null, 0, -1, 1, true); - - TreeLikelihood treeLikelihood = new TreeLikelihood(patterns, treeModel, siteModel, null, null, - false, false, true, false, false); + TreeDataLikelihood treeLikelihood = getTreeDataLikelihood(hky, null); assertEquals("treeLikelihoodK80", format.format(-1856.30305), format.format(treeLikelihood.getLogLikelihood())); } @@ -138,16 +148,7 @@ public void testLikelihoodHKY85() { FrequencyModel f = new FrequencyModel(Nucleotides.INSTANCE, freqs); HKY hky = new HKY(kappa, f); - //siteModel - GammaSiteModel siteModel = new GammaSiteModel(hky); - Parameter mu = new Parameter.Default(GammaSiteModelParser.MUTATION_RATE, 1.0, 0, Double.POSITIVE_INFINITY); - siteModel.setMutationRateParameter(mu); - - //treeLikelihood - SitePatterns patterns = new SitePatterns(alignment, null, 0, -1, 1, true); - - TreeLikelihood treeLikelihood = new TreeLikelihood(patterns, treeModel, siteModel, null, null, - false, false, true, false, false); + TreeDataLikelihood treeLikelihood = getTreeDataLikelihood(hky, null); assertEquals("treeLikelihoodHKY85", format.format(-1825.21317), format.format(treeLikelihood.getLogLikelihood())); } @@ -162,16 +163,13 @@ public void testLikelihoodHKY85G() { HKY hky = new HKY(kappa, f); //siteModel - Parameter mu = new Parameter.Default(GammaSiteModelParser.MUTATION_RATE, 1.0, 0, Double.POSITIVE_INFINITY); - Parameter shape = new Parameter.Default(GammaSiteModelParser.GAMMA_SHAPE, 0.137064, 0, 1000.0); + Parameter mu = new Parameter.Default(GammaSiteRateModelParser.MUTATION_RATE, 1.0, 0, Double.POSITIVE_INFINITY); + Parameter shape = new Parameter.Default(GammaSiteRateModelParser.GAMMA_SHAPE, 0.137064, 0, 1000.0); - GammaSiteModel siteModel = new GammaSiteModel(hky, mu, shape, 4, null); + GammaSiteRateModel siteRateModel = new GammaSiteRateModel(SITE_MODEL, mu, 1, shape, 4, GammaSiteRateModel.DiscretizationType.EQUAL, null); //treeLikelihood - SitePatterns patterns = new SitePatterns(alignment, null, 0, -1, 1, true); - - TreeLikelihood treeLikelihood = new TreeLikelihood(patterns, treeModel, siteModel, null, null, - false, false, true, false, false); + TreeDataLikelihood treeLikelihood = getTreeDataLikelihood(hky, siteRateModel); assertEquals("treeLikelihoodHKY85G", format.format(-1789.75936), format.format(treeLikelihood.getLogLikelihood())); } @@ -186,16 +184,13 @@ public void testLikelihoodHKY85I() { HKY hky = new HKY(kappa, f); //siteModel - Parameter mu = new Parameter.Default(GammaSiteModelParser.MUTATION_RATE, 1.0, 0, Double.POSITIVE_INFINITY); - Parameter invar = new Parameter.Default(GammaSiteModelParser.PROPORTION_INVARIANT, 0.701211, 0, 1.0); + Parameter mu = new Parameter.Default(GammaSiteRateModelParser.MUTATION_RATE, 1.0, 0, Double.POSITIVE_INFINITY); + Parameter invar = new Parameter.Default(GammaSiteRateModelParser.PROPORTION_INVARIANT, 0.701211, 0, 1.0); - GammaSiteModel siteModel = new GammaSiteModel(hky, mu, null, 4, invar); + GammaSiteRateModel siteRateModel = new GammaSiteRateModel(SITE_MODEL, mu, 1, null, 1, GammaSiteRateModel.DiscretizationType.EQUAL, invar); //treeLikelihood - SitePatterns patterns = new SitePatterns(alignment, null, 0, -1, 1, true); - - TreeLikelihood treeLikelihood = new TreeLikelihood(patterns, treeModel, siteModel, null, null, - false, false, true, false, false); + TreeDataLikelihood treeLikelihood = getTreeDataLikelihood(hky, siteRateModel); assertEquals("treeLikelihoodHKY85I", format.format(-1789.91240), format.format(treeLikelihood.getLogLikelihood())); } @@ -210,17 +205,14 @@ public void testLikelihoodHKY85GI() { HKY hky = new HKY(kappa, f); //siteModel - Parameter mu = new Parameter.Default(GammaSiteModelParser.MUTATION_RATE, 1.0, 0, Double.POSITIVE_INFINITY); - Parameter shape = new Parameter.Default(GammaSiteModelParser.GAMMA_SHAPE, 0.587649, 0, 1000.0); - Parameter invar = new Parameter.Default(GammaSiteModelParser.PROPORTION_INVARIANT, 0.486548, 0, 1.0); + Parameter mu = new Parameter.Default(GammaSiteRateModelParser.MUTATION_RATE, 1.0, 0, Double.POSITIVE_INFINITY); + Parameter shape = new Parameter.Default(GammaSiteRateModelParser.GAMMA_SHAPE, 0.587649, 0, 1000.0); + Parameter invar = new Parameter.Default(GammaSiteRateModelParser.PROPORTION_INVARIANT, 0.486548, 0, 1.0); - GammaSiteModel siteModel = new GammaSiteModel(hky, mu, shape, 4, invar); + GammaSiteRateModel siteRateModel = new GammaSiteRateModel(SITE_MODEL, mu, 1, shape, 4, GammaSiteRateModel.DiscretizationType.EQUAL, invar); //treeLikelihood - SitePatterns patterns = new SitePatterns(alignment, null, 0, -1, 1, true); - - TreeLikelihood treeLikelihood = new TreeLikelihood(patterns, treeModel, siteModel, null, null, - false, false, true, false, false); + TreeDataLikelihood treeLikelihood = getTreeDataLikelihood(hky, siteRateModel); assertEquals("treeLikelihoodHKY85GI", format.format(-1789.63923), format.format(treeLikelihood.getLogLikelihood())); } @@ -239,16 +231,7 @@ public void testLikelihoodGTR() { Variable rateGTValue = new Parameter.Default(GTRParser.G_TO_T, 1.0, 1.0E-8, Double.POSITIVE_INFINITY); GTR gtr = new GTR(rateACValue, rateAGValue, rateATValue, rateCGValue, rateCTValue, rateGTValue, f); - //siteModel - Parameter mu = new Parameter.Default(GammaSiteModelParser.MUTATION_RATE, 1.0, 0, Double.POSITIVE_INFINITY); - - GammaSiteModel siteModel = new GammaSiteModel(gtr, mu, null, 4, null); - - //treeLikelihood - SitePatterns patterns = new SitePatterns(alignment, null, 0, -1, 1, true); - - TreeLikelihood treeLikelihood = new TreeLikelihood(patterns, treeModel, siteModel, null, null, - false, false, true, false, false); + TreeDataLikelihood treeLikelihood = getTreeDataLikelihood(gtr, null); assertEquals("treeLikelihoodGTR", format.format(-1969.14584), format.format(treeLikelihood.getLogLikelihood())); } @@ -268,16 +251,12 @@ public void testLikelihoodGTRI() { GTR gtr = new GTR(rateACValue, rateAGValue, rateATValue, rateCGValue, rateCTValue, rateGTValue, f); //siteModel - Parameter mu = new Parameter.Default(GammaSiteModelParser.MUTATION_RATE, 1.0, 0, Double.POSITIVE_INFINITY); - Parameter invar = new Parameter.Default(GammaSiteModelParser.PROPORTION_INVARIANT, 0.5, 0, 1.0); - - GammaSiteModel siteModel = new GammaSiteModel(gtr, mu, null, 4, invar); + Parameter mu = new Parameter.Default(GammaSiteRateModelParser.MUTATION_RATE, 1.0, 0, Double.POSITIVE_INFINITY); + Parameter invar = new Parameter.Default(GammaSiteRateModelParser.PROPORTION_INVARIANT, 0.701211, 0, 1.0); - //treeLikelihood - SitePatterns patterns = new SitePatterns(alignment, null, 0, -1, 1, true); + GammaSiteRateModel siteRateModel = new GammaSiteRateModel(SITE_MODEL, mu, 1, null, 1, GammaSiteRateModel.DiscretizationType.EQUAL, invar); - TreeLikelihood treeLikelihood = new TreeLikelihood(patterns, treeModel, siteModel, null, null, - false, false, true, false, false); + TreeDataLikelihood treeLikelihood = getTreeDataLikelihood(gtr, siteRateModel); assertEquals("treeLikelihoodGTRI", format.format(-1948.84175), format.format(treeLikelihood.getLogLikelihood())); } @@ -297,16 +276,12 @@ public void testLikelihoodGTRG() { GTR gtr = new GTR(rateACValue, rateAGValue, rateATValue, rateCGValue, rateCTValue, rateGTValue, f); //siteModel - Parameter mu = new Parameter.Default(GammaSiteModelParser.MUTATION_RATE, 1.0, 0, Double.POSITIVE_INFINITY); - Parameter shape = new Parameter.Default(GammaSiteModelParser.GAMMA_SHAPE, 0.5, 0, 100.0); + Parameter mu = new Parameter.Default(GammaSiteRateModelParser.MUTATION_RATE, 1.0, 0, Double.POSITIVE_INFINITY); + Parameter shape = new Parameter.Default(GammaSiteRateModelParser.GAMMA_SHAPE, 0.587649, 0, 1000.0); - GammaSiteModel siteModel = new GammaSiteModel(gtr, mu, shape, 4, null); + GammaSiteRateModel siteRateModel = new GammaSiteRateModel(SITE_MODEL, mu, 1, shape, 4, GammaSiteRateModel.DiscretizationType.EQUAL, null); - //treeLikelihood - SitePatterns patterns = new SitePatterns(alignment, null, 0, -1, 1, true); - - TreeLikelihood treeLikelihood = new TreeLikelihood(patterns, treeModel, siteModel, null, null, - false, false, true, false, false); + TreeDataLikelihood treeLikelihood = getTreeDataLikelihood(gtr, siteRateModel); assertEquals("treeLikelihoodGTRG", format.format(-1949.03601), format.format(treeLikelihood.getLogLikelihood())); } @@ -326,17 +301,13 @@ public void testLikelihoodGTRGI() { GTR gtr = new GTR(rateACValue, rateAGValue, rateATValue, rateCGValue, rateCTValue, rateGTValue, f); //siteModel - Parameter mu = new Parameter.Default(GammaSiteModelParser.MUTATION_RATE, 1.0, 0, Double.POSITIVE_INFINITY); - Parameter shape = new Parameter.Default(GammaSiteModelParser.GAMMA_SHAPE, 0.5, 0, 100.0); - Parameter invar = new Parameter.Default(GammaSiteModelParser.PROPORTION_INVARIANT, 0.5, 0, 1.0); - - GammaSiteModel siteModel = new GammaSiteModel(gtr, mu, shape, 4, invar); + Parameter mu = new Parameter.Default(GammaSiteRateModelParser.MUTATION_RATE, 1.0, 0, Double.POSITIVE_INFINITY); + Parameter shape = new Parameter.Default(GammaSiteRateModelParser.GAMMA_SHAPE, 0.587649, 0, 1000.0); + Parameter invar = new Parameter.Default(GammaSiteRateModelParser.PROPORTION_INVARIANT, 0.486548, 0, 1.0); - //treeLikelihood - SitePatterns patterns = new SitePatterns(alignment, null, 0, -1, 1, true); + GammaSiteRateModel siteRateModel = new GammaSiteRateModel(SITE_MODEL, mu, 1, shape, 4, GammaSiteRateModel.DiscretizationType.EQUAL, invar); - TreeLikelihood treeLikelihood = new TreeLikelihood(patterns, treeModel, siteModel, null, null, - false, false, true, false, false); + TreeDataLikelihood treeLikelihood = getTreeDataLikelihood(gtr, siteRateModel); assertEquals("treeLikelihoodGTRGI", format.format(-1947.58294), format.format(treeLikelihood.getLogLikelihood())); } diff --git a/src/test/dr/evomodel/treelikelihood/PMDTestProblem.java b/src/test/dr/evomodel/treelikelihood/PMDTestProblem.java deleted file mode 100644 index b7f5b5cd5f..0000000000 --- a/src/test/dr/evomodel/treelikelihood/PMDTestProblem.java +++ /dev/null @@ -1,349 +0,0 @@ -/* - * PMDTestProblem.java - * - * Copyright © 2002-2024 the BEAST Development Team - * http://beast.community/about - * - * This file is part of BEAST. - * See the NOTICE file distributed with this work for additional - * information regarding copyright ownership and licensing. - * - * BEAST is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * BEAST is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAST; if not, write to the - * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, - * Boston, MA 02110-1301 USA - * - */ - -package test.dr.evomodel.treelikelihood; - -import dr.evolution.alignment.SitePatterns; -import dr.evolution.datatype.Nucleotides; -import dr.evomodel.branchratemodel.StrictClockBranchRates; -import dr.evomodel.coalescent.CoalescentLikelihood; -import dr.evomodel.coalescent.demographicmodel.ConstantPopulationModel; -import dr.evomodel.coalescent.TreeIntervals; -import dr.evomodel.operators.ExchangeOperator; -import dr.evomodel.operators.SubtreeSlideOperator; -import dr.evomodel.operators.WilsonBalding; -import dr.evomodel.tree.DefaultTreeModel; -import dr.oldevomodel.sitemodel.GammaSiteModel; -import dr.oldevomodel.substmodel.FrequencyModel; -import dr.oldevomodel.substmodel.HKY; -import dr.evomodel.tipstatesmodel.SequenceErrorModel; -import dr.evomodel.tipstatesmodel.TipStatesModel; -import dr.oldevomodel.treelikelihood.TreeLikelihood; -import dr.evomodelxml.coalescent.demographicmodel.ConstantPopulationModelParser; -import dr.oldevomodelxml.sitemodel.GammaSiteModelParser; -import dr.oldevomodelxml.substmodel.HKYParser; -import dr.evomodelxml.tipstatesmodel.SequenceErrorModelParser; -import dr.oldevomodelxml.treelikelihood.TreeLikelihoodParser; -import dr.inference.loggers.ArrayLogFormatter; -import dr.inference.loggers.MCLogger; -import dr.inference.loggers.TabDelimitedFormatter; -import dr.inference.mcmc.MCMC; -import dr.inference.mcmc.MCMCOptions; -import dr.inference.model.CompoundLikelihood; -import dr.inference.model.Likelihood; -import dr.inference.model.OneOnXPrior; -import dr.inference.model.Parameter; -import dr.inference.operators.*; -import dr.inference.trace.ArrayTraceList; -import dr.inference.trace.Trace; -import dr.inference.trace.TraceCorrelation; -import dr.inferencexml.model.CompoundLikelihoodParser; -import dr.math.MathUtils; -import junit.framework.Test; -import junit.framework.TestSuite; -import test.dr.inference.trace.TraceCorrelationAssert; - -import java.util.ArrayList; -import java.util.List; - -/** - * @author Walter Xie - * convert testPMD.xml in the folder /example - */ -public class PMDTestProblem extends TraceCorrelationAssert { - - public PMDTestProblem(String name) { - super(name); - } - - public void setUp() throws Exception { - super.setUp(); - - MathUtils.setSeed(666); - - createAlignment(NUMBER_TAXON_SEQUENCE, Nucleotides.INSTANCE); - } - - - public void testPMD() throws Exception { - Parameter popSize = new Parameter.Default(ConstantPopulationModelParser.POPULATION_SIZE, 496432.69917113904, 0, Double.POSITIVE_INFINITY); - ConstantPopulationModel constantModel = createRandomInitialTree(popSize); - - TreeIntervals intervalList = new TreeIntervals(treeModel, null, null); - CoalescentLikelihood coalescent = new CoalescentLikelihood(intervalList, constantModel); - coalescent.setId("coalescent"); - - // clock model - Parameter rateParameter = new Parameter.Default(StrictClockBranchRates.RATE, 4.0E-7, 0, 100.0); - StrictClockBranchRates branchRateModel = new StrictClockBranchRates(rateParameter); - - // Sub model - Parameter freqs = new Parameter.Default(new double[]{0.25, 0.25, 0.25, 0.25}); - Parameter kappa = new Parameter.Default(HKYParser.KAPPA, 1.0, 1.0E-8, Double.POSITIVE_INFINITY); - - FrequencyModel f = new FrequencyModel(Nucleotides.INSTANCE, freqs); - HKY hky = new HKY(kappa, f); - - //siteModel - GammaSiteModel siteModel = new GammaSiteModel(hky); - Parameter mu = new Parameter.Default(GammaSiteModelParser.MUTATION_RATE, 1.0, 0, Double.POSITIVE_INFINITY); - siteModel.setMutationRateParameter(mu); - - // SequenceErrorModel - Parameter ageRelatedRateParameter = new Parameter.Default(SequenceErrorModelParser.AGE_RELATED_RATE, 4.0E-7, 0, 100.0); - - TipStatesModel aDNADamageModel = new SequenceErrorModel(null, null, SequenceErrorModel.ErrorType.TRANSITIONS_ONLY, - null, ageRelatedRateParameter, null); - - //treeLikelihood - SitePatterns patterns = new SitePatterns(alignment, null, 0, -1, 1, true); - - TreeLikelihood treeLikelihood = new TreeLikelihood(patterns, treeModel, siteModel, branchRateModel, aDNADamageModel, - false, false, true, false, false); - treeLikelihood.setId(TreeLikelihoodParser.TREE_LIKELIHOOD); - - // Operators - OperatorSchedule schedule = new SimpleOperatorSchedule(); - - MCMCOperator operator = new ScaleOperator(kappa, 0.75); - operator.setWeight(1.0); - schedule.addOperator(operator); - - operator = new ScaleOperator(rateParameter, 0.75); - operator.setWeight(3.0); - schedule.addOperator(operator); - - Parameter allInternalHeights = ((DefaultTreeModel)treeModel).createNodeHeightsParameter(true, true, false); - operator = new UpDownOperator(new Scalable[]{new Scalable.Default(rateParameter)}, - new Scalable[] {new Scalable.Default(allInternalHeights)}, 0.75, 3.0, AdaptationMode.ADAPTATION_ON); - schedule.addOperator(operator); - - operator = new ScaleOperator(popSize, 0.75); - operator.setWeight(3.0); - schedule.addOperator(operator); - - operator = new ScaleOperator(ageRelatedRateParameter, 0.75); - operator.setWeight(3.0); - schedule.addOperator(operator); - - Parameter rootHeight = ((DefaultTreeModel)treeModel).getRootHeightParameter(); - rootHeight.setId(TREE_HEIGHT); - operator = new ScaleOperator(rootHeight, 0.75); - operator.setWeight(3.0); - schedule.addOperator(operator); - - Parameter internalHeights = ((DefaultTreeModel)treeModel).createNodeHeightsParameter(false, true, false); - operator = new UniformOperator(internalHeights, 30.0); - schedule.addOperator(operator); - - operator = new SubtreeSlideOperator(((DefaultTreeModel)treeModel), 15.0, 49643.2699171139, true, false, false, false, AdaptationMode.ADAPTATION_ON, AdaptableMCMCOperator.DEFAULT_ADAPTATION_TARGET); - schedule.addOperator(operator); - - operator = new ExchangeOperator(ExchangeOperator.NARROW, treeModel, 15.0); -// operator.doOperation(); - schedule.addOperator(operator); - - operator = new ExchangeOperator(ExchangeOperator.WIDE, treeModel, 3.0); -// operator.doOperation(); - schedule.addOperator(operator); - - operator = new WilsonBalding(treeModel, 3.0); -// operator.doOperation(); - schedule.addOperator(operator); - - operator = new DeltaExchangeOperator(freqs, new int[] {1, 1, 1, 1}, 0.01, 1.0, false, AdaptationMode.ADAPTATION_ON); // ??? correct? - schedule.addOperator(operator); - - //CompoundLikelihood - OneOnXPrior likelihood1 = new OneOnXPrior(); - likelihood1.addData(popSize); - OneOnXPrior likelihood2 = new OneOnXPrior(); - likelihood2.addData(kappa); - - List likelihoods = new ArrayList(); - likelihoods.add(likelihood1); - likelihoods.add(likelihood2); - likelihoods.add(coalescent); - Likelihood prior = new CompoundLikelihood(0, likelihoods); - prior.setId(CompoundLikelihoodParser.PRIOR); - - likelihoods.clear(); - likelihoods.add(treeLikelihood); - Likelihood likelihood = new CompoundLikelihood(-1, likelihoods); - - likelihoods.clear(); - likelihoods.add(prior); - likelihoods.add(likelihood); - Likelihood posterior = new CompoundLikelihood(0, likelihoods); - posterior.setId(CompoundLikelihoodParser.POSTERIOR); - - // Log - ArrayLogFormatter formatter = new ArrayLogFormatter(false); - - MCLogger[] loggers = new MCLogger[2]; - loggers[0] = new MCLogger(formatter, 1000, false); - loggers[0].add(posterior); - loggers[0].add(treeLikelihood); - loggers[0].add(rootHeight); - loggers[0].add(rateParameter); - loggers[0].add(ageRelatedRateParameter); - loggers[0].add(popSize); - loggers[0].add(kappa); - loggers[0].add(coalescent); - - loggers[1] = new MCLogger(new TabDelimitedFormatter(System.out), 10000, false); - loggers[1].add(posterior); - loggers[1].add(treeLikelihood); - loggers[1].add(rootHeight); - loggers[1].add(rateParameter); - - // MCMC - MCMC mcmc = new MCMC("mcmc1"); - MCMCOptions options = new MCMCOptions(1000000); - - mcmc.setShowOperatorAnalysis(true); - mcmc.init(options, posterior, schedule, loggers); - mcmc.run(); - - // time - System.out.println(mcmc.getTimer().toString()); - - // Tracer - List traces = formatter.getTraces(); - ArrayTraceList traceList = new ArrayTraceList("PMDTest", traces, 0); - - for (int i = 1; i < traces.size(); i++) { - traceList.analyseTrace(i); - } - -// -// -// - - TraceCorrelation kappaStats = traceList.getCorrelationStatistics(traceList.getTraceIndex(HKYParser.KAPPA)); - assertExpectation(HKYParser.KAPPA, kappaStats, 10); - - TraceCorrelation rateStats = traceList.getCorrelationStatistics(traceList.getTraceIndex(StrictClockBranchRates.RATE)); - assertExpectation(StrictClockBranchRates.RATE, rateStats, 1.5E-7); - - TraceCorrelation ageRateStats = traceList.getCorrelationStatistics(traceList.getTraceIndex(SequenceErrorModelParser.AGE_RELATED_RATE)); - assertExpectation(SequenceErrorModelParser.AGE_RELATED_RATE, ageRateStats, 0.7E-7); - } - - public static Test suite() { - return new TestSuite(PMDTestProblem.class); - } -} - -/* -****************** BEAST result: - -Operator analysis -Operator Tuning Count Time Time/Op Pr(accept) Performance suggestion -scale(clock.rate) 0.573 358210 685526 1.91 0.2564 good -up:clock.rate down:nodeHeights(treeModel) 0.996 357898 429449 1.2 0.1839 good -scale(errorModel.ageRate) 0.615 357844 684979 1.91 0.2616 good -scale(constant.popSize) 0.631 357294 7663 0.02 0.2435 good -scale(treeModel.rootHeight) 0.644 358109 45734 0.13 0.2387 good -uniform(nodeHeights(treeModel)) 3579577 932944 0.26 0.7178 high -subtreeSlide(treeModel) 12118.431787556 280311 0.16 0.1591 good -Narrow Exchange(treeModel) 1789693 248656 0.14 0.3825 good -Wide Exchange(treeModel) 357376 13339 0.04 0.0063 low -wilsonBalding(treeModel) 357423 104544 0.29 0.018 slightly low -scale(kappa) 0.339 119624 228792 1.91 0.2783 good -frequencies 0.081 119396 228543 1.91 0.2664 good - - - -2.227766388888889 hours - -burnIn = -1 -maxState = 10000000 - -statistic mean hpdLower hpdUpper ESS -posterior -5642.41 -5676.88 -5579.19 156.182 -prior -2369.96 -2411.87 -2316.7 86.1602 * -likelihood -3272.46 -3281.91 -3247.88 249.224 -clock.rate 1.42656E-7 1.06654E-7 1.82082E-7 227.675 -errorModel.ageRate 7.12553E-8 5.91987E-8 8.39501E-8 1273.19 -treeModel.rootHeight 1.35663E5 97420.0 1.75097E5 138.118 -constant.popSize 94500.1 63793.2 1.15728E5 126.347 -kappa 11.0776 6.40144 16.5056 6722.02 -treeLikelihood -3272.46 -3281.91 -3247.88 249.224 -coalescent -2356.18 -2397.88 -2303.19 86.1716 * - - * WARNING: The results of this MCMC analysis may be invalid as - one or more statistics had very low effective sample sizes (ESS) -E[clock.rate]=1.5E-7 -WARNING: 1.42656E-7 +- 1.3489E-9 -E[errorModel.ageRate]=7E-8 -WARNING: 7.12553E-8 +- 2.16332E-10 - - -****************************** Java Result: - -Operator analysis -Operator Tuning Count Time Time/Op Pr(accept) Performance suggestion -scale(kappa) 0.384 12009 59970 4.99 0.3266 good -scale(rate) 0.599 36245 181150 5.0 0.2856 good -up:rate down:nodeHeights(null) 0.993 36147 101812 2.82 0.0962 slightly low Try setting scaleFactor to about 0.9965 -scale(populationSize) 0.627 36263 1572 0.04 0.2424 good -scale(ageRelatedErrorRate) 0.635 36062 180121 4.99 0.2823 good -scale(treeModel.rootHeight) 0.679 36251 8469 0.23 0.2907 good -uniform(nodeHeights(null)) 361046 212919 0.59 0.7182 high -subtreeSlide(null) 24252.175181239 58974 0.33 0.0902 slightly low Try decreasing size to about 12126.087614484664 -Narrow Exchange(null) 180508 56685 0.31 0.3857 good -Wide Exchange(null) 35991 3409 0.09 0.0086 low -wilsonBalding(null) 36104 24678 0.68 0.0222 slightly low - -java.lang.NullPointerException - at dr.util.NumberFormatter.formatToFieldWidth(NumberFormatter.java:92) - at dr.inference.mcmc.MCMC.formattedOperatorName(MCMC.java:313) - at dr.inference.mcmc.MCMC.showOperatorAnalysis(MCMC.java:299) - at dr.inference.mcmc.MCMC.access$300(MCMC.java:50) - at dr.inference.mcmc.MCMC$1.finished(MCMC.java:241) - at dr.inference.markovchain.MarkovChain.fireFinished(MarkovChain.java:533) - at dr.inference.markovchain.MarkovChain.terminateChain(MarkovChain.java:350) - at dr.inference.mcmc.MCMC.chain(MCMC.java:194) - at dr.inference.mcmc.MCMC.run(MCMC.java:152) - at test.dr.evomodel.treelikelihood.PMDTest.testPMD(PMDTest.java:201) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) - at com.intellij.junit3.JUnit3IdeaTestRunner.doRun(JUnit3IdeaTestRunner.java:108) - at com.intellij.junit3.JUnit3IdeaTestRunner.startRunnerWithArgs(JUnit3IdeaTestRunner.java:42) - at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:165) - at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:60) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) - at com.intellij.rt.execution.application.AppMain.main(AppMain.java:110) - - -Process finished with exit code -1 - - -*/ \ No newline at end of file diff --git a/src/test/dr/evomodel/treelikelihood/SequenceLikelihoodTest.java b/src/test/dr/evomodel/treelikelihood/SequenceLikelihoodTest.java index 27ef2195ba..35da30312d 100644 --- a/src/test/dr/evomodel/treelikelihood/SequenceLikelihoodTest.java +++ b/src/test/dr/evomodel/treelikelihood/SequenceLikelihoodTest.java @@ -35,13 +35,7 @@ import dr.evolution.util.Date; import dr.evolution.util.Taxon; import dr.evolution.util.Units; -import dr.oldevomodel.sitemodel.GammaSiteModel; -import dr.oldevomodel.substmodel.FrequencyModel; -import dr.oldevomodel.substmodel.HKY; import dr.evomodel.tree.TreeModel; -import dr.oldevomodel.treelikelihood.TreeLikelihood; -import dr.oldevomodelxml.sitemodel.GammaSiteModelParser; -import dr.oldevomodelxml.substmodel.HKYParser; import dr.inference.model.Parameter; import test.dr.inference.trace.TraceCorrelationAssert; @@ -131,23 +125,24 @@ protected void createAlignmentWithAllUniquePatterns(Object[][] taxa_sequence, Da } protected double[] computeSitePatternLikelihoods(SitePatterns patterns) { + throw new UnsupportedOperationException("Not implemented - uses oldevomodel.treelikelihood, now deleted"); // Sub model - Parameter freqs = new Parameter.Default(alignment.getStateFrequencies()); - Parameter kappa = new Parameter.Default(HKYParser.KAPPA, 29.739445, 0, 100); - - FrequencyModel f = new FrequencyModel(Nucleotides.INSTANCE, freqs); - HKY hky = new HKY(kappa, f); - - //siteModel - GammaSiteModel siteModel = new GammaSiteModel(hky); - Parameter mu = new Parameter.Default(GammaSiteModelParser.MUTATION_RATE, 1.0, 0, Double.POSITIVE_INFINITY); - siteModel.setMutationRateParameter(mu); - - //treeLikelihood - TreeLikelihood treeLikelihood = new TreeLikelihood(patterns, treeModel, siteModel, null, null, - false, false, true, false, false); - - return treeLikelihood.getPatternLogLikelihoods(); +// Parameter freqs = new Parameter.Default(alignment.getStateFrequencies()); +// Parameter kappa = new Parameter.Default(HKYParser.KAPPA, 29.739445, 0, 100); +// +// FrequencyModel f = new FrequencyModel(Nucleotides.INSTANCE, freqs); +// HKY hky = new HKY(kappa, f); +// +// //siteModel +// GammaSiteModel siteModel = new GammaSiteModel(hky); +// Parameter mu = new Parameter.Default(GammaSiteModelParser.MUTATION_RATE, 1.0, 0, Double.POSITIVE_INFINITY); +// siteModel.setMutationRateParameter(mu); +// +// //treeLikelihood +// TreeLikelihood treeLikelihood = new TreeLikelihood(patterns, treeModel, siteModel, null, null, +// false, false, true, false, false); +// +// return treeLikelihood.getPatternLogLikelihoods(); } protected double computeSumOfPatterns(SitePatterns patterns) { diff --git a/src/test/dr/integration/PathSampling.java b/src/test/dr/integration/PathSampling.java index 3d2275b89e..94752578df 100644 --- a/src/test/dr/integration/PathSampling.java +++ b/src/test/dr/integration/PathSampling.java @@ -30,9 +30,9 @@ import dr.evolution.sequence.Sequence; import dr.evolution.datatype.Nucleotides; import dr.evolution.datatype.DataType; +import dr.evomodel.substmodel.FrequencyModel; +import dr.evomodel.substmodel.nucleotide.HKY; import dr.inference.model.Parameter; -import dr.oldevomodel.substmodel.HKY; -import dr.oldevomodel.substmodel.FrequencyModel; import dr.math.distributions.GammaDistribution; import dr.math.LogTricks; diff --git a/src/version.txt b/src/version.txt new file mode 100644 index 0000000000..6275565b2a --- /dev/null +++ b/src/version.txt @@ -0,0 +1,3 @@ +File created by build process. Do not edit by hand +${version} +${extra_release_tag} \ No newline at end of file