本文整理汇总了C++中TreeTemplate类的典型用法代码示例。如果您正苦于以下问题:C++ TreeTemplate类的具体用法?C++ TreeTemplate怎么用?C++ TreeTemplate使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了TreeTemplate类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。
示例1: get_abayes_tree
string Alignment::get_abayes_tree() {
TreeTemplate<Node> tree = TreeTemplate<Node>(likelihood->getTree());
std::map<int, nniIDs> nniMap;
for (auto& node : tree.getNodes()) {
if (node->hasFather() && node->getFather()->hasFather()) {
auto search = nniMap.find(node->getFatherId());
if (search == nniMap.end()) {
nniMap[node->getFatherId()].rearr1 = node->getId();
}
else {
search->second.rearr2 = node->getId();
};
}
}
for (auto entry : nniMap) {
double lnl1 = -likelihood->testNNI(entry.second.rearr1);
double lnl2 = -likelihood->testNNI(entry.second.rearr2);
bpp::Number<double> abayes = 1 / (1 + exp(lnl1) + exp(lnl2));
tree.setBranchProperty(entry.first, TreeTools::BOOTSTRAP, abayes);
}
string s = TreeTools::treeToParenthesis(tree, true, TreeTools::BOOTSTRAP);
s.erase(s.find_last_not_of(" \n\r\t")+1);
return s;
}
开发者ID:kgori,项目名称:bpp,代码行数:27,代码来源:Alignment.cpp
示例2: main
int main() {
TreeTemplate<Node>* tree = TreeTemplateTools::parenthesisToTree("((A:0.001, B:0.002):0.003,C:0.01,D:0.1);");
cout << tree->getNumberOfLeaves() << endl;
vector<int> ids = tree->getNodesId();
//-------------
NucleicAlphabet* alphabet = new DNA();
SubstitutionModel* model = new GTR(alphabet, 1, 0.2, 0.3, 0.4, 0.4, 0.1, 0.35, 0.35, 0.2);
//DiscreteDistribution* rdist = new GammaDiscreteDistribution(4, 0.4, 0.4);
DiscreteDistribution* rdist = new ConstantDistribution(1.0);
HomogeneousSequenceSimulator simulator(model, rdist, tree);
unsigned int n = 100000;
map<int, RowMatrix<unsigned int> > counts;
for (size_t j = 0; j < ids.size() - 1; ++j) //ignore root, the last id
counts[ids[j]].resize(4, 4);
for (unsigned int i = 0; i < n; ++i) {
RASiteSimulationResult* result = simulator.dSimulate();
for (size_t j = 0; j < ids.size() - 1; ++j) { //ignore root, the last id
result->getMutationPath(ids[j]).getEventCounts(counts[ids[j]]);
}
delete result;
}
map<int, RowMatrix<double> >freqs;
map<int, double> sums;
for (size_t k = 0; k < ids.size() - 1; ++k) { //ignore root, the last id
RowMatrix<double>* freqsP = &freqs[ids[k]];
RowMatrix<unsigned int>* countsP = &counts[ids[k]];
freqsP->resize(4, 4);
for (unsigned int i = 0; i < 4; ++i)
for (unsigned int j = 0; j < 4; ++j)
(*freqsP)(i, j) = static_cast<double>((*countsP)(i, j)) / (static_cast<double>(n));
//For now we simply compare the total number of substitutions:
sums[ids[k]] = MatrixTools::sumElements(*freqsP);
cout << "Br" << ids[k] << " BrLen = " << tree->getDistanceToFather(ids[k]) << " counts = " << sums[ids[k]] << endl;
MatrixTools::print(*freqsP);
}
//We should compare this matrix with the expected one!
for (size_t k = 0; k < ids.size() - 1; ++k) { //ignore root, the last id
if (abs(sums[ids[k]] - tree->getDistanceToFather(ids[k])) > 0.01) {
delete tree;
delete alphabet;
delete model;
delete rdist;
return 1;
}
}
//-------------
delete tree;
delete alphabet;
delete model;
delete rdist;
//return (abs(obs - 0.001) < 0.001 ? 0 : 1);
return 0;
}
开发者ID:KhaosResearch,项目名称:MORPHY,代码行数:59,代码来源:test_detailed_simulations.cpp
示例3: treeToParenthesis
string TreeTemplateTools::treeToParenthesis(const TreeTemplate<Node>& tree, bool writeId)
{
ostringstream s;
s << "(";
const Node* node = tree.getRootNode();
if (node->hasNoSon())
{
s << node->getName();
for (size_t i = 0; i < node->getNumberOfSons(); ++i)
{
s << "," << nodeToParenthesis(*node->getSon(i), writeId);
}
}
else
{
s << nodeToParenthesis(*node->getSon(0), writeId);
for (size_t i = 1; i < node->getNumberOfSons(); ++i)
{
s << "," << nodeToParenthesis(*node->getSon(i), writeId);
}
}
s << ")";
if (node->hasDistanceToFather())
s << ":" << node->getDistanceToFather();
s << ";" << endl;
return s.str();
}
开发者ID:jbloomlab,项目名称:phydms,代码行数:27,代码来源:TreeTemplateTools.cpp
示例4: getRadius
double TreeTemplateTools::getRadius(TreeTemplate<Node>& tree)
{
TreeTemplateTools::midRoot(tree, MIDROOT_SUM_OF_SQUARES, false);
Moments_ moments = getSubtreeMoments_(tree.getRootNode());
double radius = moments.sum / moments.numberOfLeaves;
return radius;
}
开发者ID:jbloomlab,项目名称:phydms,代码行数:7,代码来源:TreeTemplateTools.cpp
示例5: throw
TreeTemplate<Node>* TreeTemplateTools::parenthesisToTree(const string& description, bool bootstrap, const string& propertyName, bool withId, bool verbose) throw (Exception)
{
string::size_type semi = description.rfind(';');
if (semi == string::npos)
throw Exception("TreeTemplateTools::parenthesisToTree(). Bad format: no semi-colon found.");
string content = description.substr(0, semi);
unsigned int nodeCounter = 0;
Node* node = parenthesisToNode(content, nodeCounter, bootstrap, propertyName, withId, verbose);
TreeTemplate<Node>* tree = new TreeTemplate<Node>();
tree->setRootNode(node);
if (!withId)
{
tree->resetNodesId();
}
if (verbose) {
(*ApplicationTools::message) << " nodes loaded.";
ApplicationTools::message->endLine();
}
return tree;
}
开发者ID:jbloomlab,项目名称:phydms,代码行数:20,代码来源:TreeTemplateTools.cpp
示例6: AbstractLikelihoodTree
RecursiveLikelihoodTree::RecursiveLikelihoodTree(const SubstitutionProcess& process, bool usepatterns) :
AbstractLikelihoodTree(process),
vTree_(),
patternLinks_(),
usePatterns_(usepatterns),
initializedAboveLikelihoods_(false)
{
TreeTemplate<Node> tree = process.getParametrizableTree().getTree();
RecursiveLikelihoodNode* rCN = TreeTemplateTools::cloneSubtree<RecursiveLikelihoodNode>(*tree.getRootNode());
TreeTemplate<RecursiveLikelihoodNode>* pTC = new TreeTemplate<RecursiveLikelihoodNode>(rCN);
for (size_t i = 0; i < nbClasses_; i++)
{
TreeTemplate<RecursiveLikelihoodNode>* pTC2 = pTC->clone();
vTree_.push_back(pTC2);
}
delete pTC;
}
开发者ID:jbloomlab,项目名称:phydms,代码行数:21,代码来源:RecursiveLikelihoodTree.cpp
示例7:
Tree::Tree( const TreeTemplate& tmpl ) :
mPosition( 0.0, 0.0, 0.0 ),
mAngle( 0.0, 0.0, 0.0 ),
mScale( 1.0, 1.0, 1.0 ),
mNodes( 0 ),
mNodeNumber( 0 ),
mTime( 0.0 ){
mNodeNumber = tmpl.nodeNumber();
mNodes = new Node[ mNodeNumber ];
for ( int i = 0; i < mNodeNumber; ++i ){
Node& dst = mNodes[ i ];
const NodeTemplate* src = tmpl.node( i );
//パラメータを移す
dst.setTranslation( *src->translation() );
dst.setRotation( *src->rotation() );
dst.setScale( *src->scale() );
dst.setName( src->name()->c_str() );
dst.setBatch( src->batch() );
//[長男-兄弟形式から子配列形式への変換]
//子の数を数える
int child = src->child();
int childNumber = 0;
while ( child >= 0 ){
++childNumber;
child = tmpl.node( child )->brother();
}
//子をアロケート
dst.setChildNumber( childNumber );
//子を充填する
child = src->child();
int j = 0;
while ( child >= 0 ){
dst.setChild( j, mNodes + child );
child = tmpl.node( child )->brother();
++j;
}
}
}
开发者ID:rainbow23,项目名称:GameLib2008,代码行数:39,代码来源:Tree.cpp
示例8: nodes
TreeTemplate<Node>* TreeTemplateTools::getRandomTree(vector<string>& leavesNames, bool rooted)
{
if (leavesNames.size() == 0)
return 0; // No taxa.
// This vector will contain all nodes.
// Start with all leaves, and then group nodes randomly 2 by 2.
// Att the end, contains only the root node of the tree.
vector<Node*> nodes(leavesNames.size());
// Create all leaves nodes:
for (size_t i = 0; i < leavesNames.size(); ++i)
{
nodes[i] = new Node(leavesNames[i]);
}
// Now group all nodes:
while (nodes.size() > (rooted ? 2 : 3))
{
// Select random nodes:
size_t pos1 = RandomTools::giveIntRandomNumberBetweenZeroAndEntry<size_t>(nodes.size());
Node* node1 = nodes[pos1];
nodes.erase(nodes.begin() + static_cast<ptrdiff_t>(pos1));
size_t pos2 = RandomTools::giveIntRandomNumberBetweenZeroAndEntry<size_t>(nodes.size());
Node* node2 = nodes[pos2];
nodes.erase(nodes.begin() + static_cast<ptrdiff_t>(pos2));
// Add new node:
Node* parent = new Node();
parent->addSon(node1);
parent->addSon(node2);
nodes.push_back(parent);
}
// Return tree with last node as root node:
Node* root = new Node();
for (size_t i = 0; i < nodes.size(); ++i)
{
root->addSon(nodes[i]);
}
TreeTemplate<Node>* tree = new TreeTemplate<Node>(root);
tree->resetNodesId();
return tree;
}
开发者ID:jbloomlab,项目名称:phydms,代码行数:39,代码来源:TreeTemplateTools.cpp
示例9: main
int main() {
TreeTemplate<Node>* tree = TreeTemplateTools::parenthesisToTree("(((A:0.01, B:0.01):0.02,C:0.03):0.01,D:0.04);");
vector<string> seqNames = tree->getLeavesNames();
vector<int> ids = tree->getNodesId();
//-------------
const NucleicAlphabet* alphabet = &AlphabetTools::DNA_ALPHABET;
SubstitutionModel* model = new T92(alphabet, 3.);
DiscreteDistribution* rdist = new GammaDiscreteDistribution(4, 1.0);
rdist->aliasParameters("alpha", "beta");
VectorSiteContainer sites(alphabet);
sites.addSequence(BasicSequence("A", "AAATGGCTGTGCACGTC", alphabet));
sites.addSequence(BasicSequence("B", "AACTGGATCTGCATGTC", alphabet));
sites.addSequence(BasicSequence("C", "ATCTGGACGTGCACGTG", alphabet));
sites.addSequence(BasicSequence("D", "CAACGGGAGTGCGCCTA", alphabet));
try {
fitModelH(model, rdist, *tree, sites, 93.017264552603336369, 71.265543199977557265);
} catch (Exception& ex) {
cerr << ex.what() << endl;
return 1;
}
try {
fitModelHClock(model, rdist, *tree, sites, 92.27912072473920090943, 71.26554020984087856050);
} catch (Exception& ex) {
cerr << ex.what() << endl;
return 1;
}
//-------------
delete tree;
delete model;
delete rdist;
return 0;
}
开发者ID:KhaosResearch,项目名称:MORPHY,代码行数:37,代码来源:test_likelihood_clock.cpp
示例10: nodeToParenthesis
string TreeTemplateTools::treeToParenthesis(const TreeTemplate<Node>& tree, bool bootstrap, const string& propertyName)
{
ostringstream s;
s << "(";
const Node* node = tree.getRootNode();
if (node->hasNoSon())
{
s << node->getName();
for (size_t i = 0; i < node->getNumberOfSons(); i++)
{
s << "," << nodeToParenthesis(*node->getSon(i), bootstrap, propertyName);
}
}
else
{
s << nodeToParenthesis(*node->getSon(0), bootstrap, propertyName);
for (size_t i = 1; i < node->getNumberOfSons(); i++)
{
s << "," << nodeToParenthesis(*node->getSon(i), bootstrap, propertyName);
}
}
s << ")";
if (bootstrap)
{
if (node->hasBranchProperty(TreeTools::BOOTSTRAP))
s << (dynamic_cast<const Number<double>*>(node->getBranchProperty(TreeTools::BOOTSTRAP))->getValue());
}
else
{
if (node->hasBranchProperty(propertyName))
{
const BppString* ppt = dynamic_cast<const BppString*>(node->getBranchProperty(propertyName));
if (ppt)
s << *ppt;
else
throw Exception("TreeTemplateTools::nodeToParenthesis. Property should be a BppString.");
}
}
s << ";" << endl;
return s.str();
}
开发者ID:jbloomlab,项目名称:phydms,代码行数:41,代码来源:TreeTemplateTools.cpp
示例11: throw
void NexusIOTree::read(std::istream& in, std::vector<Tree*>& trees) const throw (Exception)
{
// Checking the existence of specified file
if (! in) { throw IOException ("NexusIOTree::read(). Failed to read from stream"); }
//Look for the TREES block:
string line = "";
while (TextTools::toUpper(line) != "BEGIN TREES;")
{
if (in.eof())
throw Exception("NexusIOTree::read(). No trees block was found.");
line = TextTools::removeSurroundingWhiteSpaces(FileTools::getNextLine(in));
}
string cmdName = "", cmdArgs = "";
bool cmdFound = NexusTools::getNextCommand(in, cmdName, cmdArgs, false);
if (! cmdFound)
throw Exception("NexusIOTree::read(). Missing tree command.");
cmdName = TextTools::toUpper(cmdName);
//Look for the TRANSLATE command:
map<string, string> translation;
bool hasTranslation = false;
if (cmdName == "TRANSLATE")
{
//Parse translation:
StringTokenizer st(cmdArgs, ",");
while (st.hasMoreToken())
{
string tok = TextTools::removeSurroundingWhiteSpaces(st.nextToken());
NestedStringTokenizer nst(tok, "'", "'", " \t");
if (nst.numberOfRemainingTokens() != 2)
throw Exception("NexusIOTree::read(). Unvalid translation description.");
string name = nst.nextToken();
string tln = nst.nextToken();
translation[name] = tln;
}
hasTranslation = true;
cmdFound = NexusTools::getNextCommand(in, cmdName, cmdArgs, false);
if (! cmdFound)
throw Exception("NexusIOTree::read(). Missing tree command.");
else
cmdName = TextTools::toUpper(cmdName);
}
//Now parse the trees:
while (cmdFound && cmdName != "END")
{
if (cmdName != "TREE")
throw Exception("NexusIOTree::read(). Unvalid command found: " + cmdName);
string::size_type pos = cmdArgs.find("=");
if (pos == string::npos)
throw Exception("NexusIOTree::read(). unvalid format, should be tree-name=tree-description");
string description = cmdArgs.substr(pos + 1);
TreeTemplate<Node>* tree = TreeTemplateTools::parenthesisToTree(description + ";", true);
//Now translate leaf names if there is a translation:
//(we assume that all trees share the same translation! ===> check!)
if (hasTranslation)
{
vector<Node*> leaves = tree->getLeaves();
for (size_t i = 0; i < leaves.size(); i++)
{
string name = leaves[i]->getName();
if (translation.find(name) == translation.end())
{
throw Exception("NexusIOTree::read(). No translation was given for this leaf: " + name);
}
leaves[i]->setName(translation[name]);
}
}
trees.push_back(tree);
cmdFound = NexusTools::getNextCommand(in, cmdName, cmdArgs, false);
if (cmdFound) cmdName = TextTools::toUpper(cmdName);
}
}
开发者ID:KhaosResearch,项目名称:MORPHY,代码行数:76,代码来源:NexusIoTree.cpp
示例12: Exception
void TreeTemplateTools::midRoot(TreeTemplate<Node>& tree, short criterion, bool forceBranchRoot)
{
if (criterion != MIDROOT_VARIANCE && criterion != MIDROOT_SUM_OF_SQUARES)
throw Exception("TreeTemplateTools::midRoot(). Illegal criterion value '" + TextTools::toString(criterion) + "'");
if (tree.isRooted())
tree.unroot();
Node* ref_root = tree.getRootNode();
//
// The bestRoot object records :
// -- the current best branch : .first
// -- the current best value of the criterion : .second["value"]
// -- the best position of the root on the branch : .second["position"]
// 0 is toward the original root, 1 is away from it
//
pair<Node*, map<string, double> > best_root_branch;
best_root_branch.first = ref_root; // nota: the root does not correspond to a branch as it has no father
best_root_branch.second ["position"] = -1;
best_root_branch.second ["score"] = numeric_limits<double>::max();
// find the best root
getBestRootInSubtree_(tree, criterion, ref_root, best_root_branch);
tree.rootAt(ref_root); // back to the original root
// reroot
const double pos = best_root_branch.second["position"];
if (pos < 1e-6 or pos > 1 - 1e-6)
// The best root position is on a node (this is often the case with the sum of squares criterion)
tree.rootAt(pos < 1e-6 ? best_root_branch.first->getFather() : best_root_branch.first);
else
// The best root position is somewhere on a branch (a new Node is created)
{
Node* new_root = new Node();
new_root->setId( TreeTools::getMPNUId(tree, tree.getRootId()) );
double root_branch_length = best_root_branch.first->getDistanceToFather();
Node* best_root_father = best_root_branch.first->getFather();
best_root_father->removeSon(best_root_branch.first);
best_root_father->addSon(new_root);
new_root->addSon(best_root_branch.first);
new_root->setDistanceToFather(max(pos * root_branch_length, 1e-6));
best_root_branch.first->setDistanceToFather(max((1 - pos) * root_branch_length, 1e-6));
// The two branches leaving the root must have the same branch properties
const vector<string> branch_properties = best_root_branch.first->getBranchPropertyNames();
for (vector<string>::const_iterator p = branch_properties.begin(); p != branch_properties.end(); ++p)
{
new_root->setBranchProperty(*p, *best_root_branch.first->getBranchProperty(*p));
}
tree.rootAt(new_root);
}
if (forceBranchRoot) // if we want the root to be on a branch, not on a node
{
Node* orig_root = tree.getRootNode();
vector<Node*> root_sons = orig_root->getSons();
if (root_sons.size() > 2)
{
Node* nearest = root_sons.at(0);
for (vector<Node*>::iterator n = root_sons.begin(); n !=
root_sons.end(); ++n)
{
if ((**n).getDistanceToFather() < nearest->getDistanceToFather())
nearest = *n;
}
const double d = nearest->getDistanceToFather();
Node* new_root = new Node();
new_root->setId( TreeTools::getMPNUId(tree, tree.getRootId()) );
orig_root->removeSon(nearest);
orig_root->addSon(new_root);
new_root->addSon(nearest);
new_root->setDistanceToFather(d / 2.);
nearest->setDistanceToFather(d / 2.);
const vector<string> branch_properties = nearest->getBranchPropertyNames();
for (vector<string>::const_iterator p = branch_properties.begin(); p != branch_properties.end(); ++p)
{
new_root->setBranchProperty(*p, *nearest->getBranchProperty(*p));
}
tree.rootAt(new_root);
}
}
}
开发者ID:jbloomlab,项目名称:phydms,代码行数:85,代码来源:TreeTemplateTools.cpp
示例13: main
int main() {
TreeTemplate<Node>* tree = TreeTemplateTools::parenthesisToTree("(((A:0.1, B:0.2):0.3,C:0.1):0.2,(D:0.3,(E:0.2,F:0.05):0.1):0.1);");
vector<string> seqNames= tree->getLeavesNames();
vector<int> ids = tree->getNodesId();
//-------------
const NucleicAlphabet* alphabet = &AlphabetTools::DNA_ALPHABET;
FrequenciesSet* rootFreqs = new GCFrequenciesSet(alphabet);
SubstitutionModel* model = new T92(alphabet, 3.);
std::vector<std::string> globalParameterNames;
globalParameterNames.push_back("T92.kappa");
//Very difficult to optimize on small datasets:
DiscreteDistribution* rdist = new GammaDiscreteRateDistribution(4, 1.0);
ParametrizableTree* parTree = new ParametrizableTree(*tree);
FrequenciesSet* rootFreqs2 = rootFreqs->clone();
DiscreteDistribution* rdist2 = rdist->clone();
SubstitutionModel* model2=model->clone();
map<string, string> alias;
SubstitutionModelSet* modelSet = SubstitutionModelSetTools::createNonHomogeneousModelSet(model, rootFreqs, tree, alias, globalParameterNames);
unique_ptr<SubstitutionModelSet> modelSetSim(modelSet->clone());
NonHomogeneousSubstitutionProcess* subPro= NonHomogeneousSubstitutionProcess::createNonHomogeneousSubstitutionProcess(model2, rdist2, rootFreqs2, parTree, globalParameterNames);
// Simulation
size_t nsites = 1000;
unsigned int nrep = 20;
size_t nmodels = modelSet->getNumberOfModels();
vector<double> thetas(nmodels);
vector<double> thetasEst1(nmodels);
vector<double> thetasEst2(nmodels);
vector<double> thetasEst1n(nmodels);
vector<double> thetasEst2n(nmodels);
for (size_t i = 0; i < nmodels; ++i) {
double theta = RandomTools::giveRandomNumberBetweenZeroAndEntry(0.99) + 0.005;
cout << "Theta" << i << " set to " << theta << endl;
modelSetSim->setParameterValue("T92.theta_" + TextTools::toString(i + 1), theta);
//subPro->setParameterValue("T92.theta_" + TextTools::toString(i + 1), theta);
thetas[i] = theta;
}
NonHomogeneousSequenceSimulator simulator(modelSetSim.get(), rdist, tree);
NonHomogeneousSubstitutionProcess* subPro2 = subPro->clone();
for (unsigned int j = 0; j < nrep; j++) {
OutputStream* profiler = new StlOutputStream(new ofstream("profile.txt", ios::out));
OutputStream* messenger = new StlOutputStream(new ofstream("messages.txt", ios::out));
//Simulate data:
unique_ptr<SiteContainer> sites(simulator.simulate(nsites));
//Now fit model:
unique_ptr<SubstitutionModelSet> modelSet2(modelSet->clone());
RNonHomogeneousTreeLikelihood tl(*tree, *sites.get(), modelSet, rdist, true, true, false);
tl.initialize();
RNonHomogeneousTreeLikelihood tl2(*tree, *sites.get(), modelSet2.get(), rdist, true, true, true);
tl2.initialize();
SubstitutionProcess* nsubPro=subPro->clone();
SubstitutionProcess* nsubPro2=subPro2->clone();
RecursiveLikelihoodTreeCalculation* tlComp = new RecursiveLikelihoodTreeCalculation(*sites->clone(), nsubPro, true, false);
SingleProcessPhyloLikelihood ntl(nsubPro, tlComp, true);
RecursiveLikelihoodTreeCalculation* tlComp2 = new RecursiveLikelihoodTreeCalculation(*sites->clone(), nsubPro2, true);
SingleProcessPhyloLikelihood ntl2(nsubPro2, tlComp2, true);
for (size_t i = 0; i < nmodels; ++i) {
ntl.setParameterValue("T92.theta_" + TextTools::toString(i + 1), thetas[i]);
ntl2.setParameterValue("T92.theta_" + TextTools::toString(i + 1), thetas[i]);
}
cout << setprecision(10) << "OldTL init: " << tl.getValue() << "\t" << tl2.getValue() << endl;
cout << setprecision(10) << "NewTL init: " << ntl.getValue() << "\t" << ntl2.getValue() << endl;
unsigned int c1 = OptimizationTools::optimizeNumericalParameters2(
&tl, tl.getParameters(), 0,
0.0001, 10000, messenger, profiler, false, false, 1, OptimizationTools::OPTIMIZATION_NEWTON);
unsigned int c2 = OptimizationTools::optimizeNumericalParameters2(
&tl2, tl2.getParameters(), 0,
0.0001, 10000, messenger, profiler, false, false, 1, OptimizationTools::OPTIMIZATION_NEWTON);
unsigned int nc1 = OptimizationTools::optimizeNumericalParameters2(
&ntl, ntl.getParameters(), 0,
0.0001, 10000, messenger, profiler, false, false, 1, OptimizationTools::OPTIMIZATION_NEWTON);
//.........这里部分代码省略.........
开发者ID:jbloomlab,项目名称:phydms,代码行数:101,代码来源:test_likelihood_nh.cpp
示例14: main
int main() {
TreeTemplate<Node>* tree = TreeTemplateTools::parenthesisToTree("((A:0.001, B:0.002):0.008,C:0.01,D:0.1);");
vector<int> ids = tree->getNodesId();
ids.pop_back(); //Ignore root
//-------------
CodonAlphabet* alphabet = new CodonAlphabet(&AlphabetTools::DNA_ALPHABET);
GeneticCode* gc = new StandardGeneticCode(&AlphabetTools::DNA_ALPHABET);
CodonSubstitutionModel* model = new YN98(gc, CodonFrequenciesSet::getFrequenciesSetForCodons(CodonFrequenciesSet::F0, gc));
//SubstitutionModel* model = new CodonRateSubstitutionModel(
// gc,
// new JCnuc(dynamic_cast<CodonAlphabet*>(alphabet)->getNucleicAlphabet()));
cout << model->getNumberOfStates() << endl;
MatrixTools::printForR(model->getGenerator(), "g");
DiscreteDistribution* rdist = new ConstantDistribution(1.0);
HomogeneousSequenceSimulator simulator(model, rdist, tree);
TotalSubstitutionRegister* totReg = new TotalSubstitutionRegister(model);
DnDsSubstitutionRegister* dndsReg = new DnDsSubstitutionRegister(model);
unsigned int n = 20000;
vector< vector<double> > realMap(n);
vector< vector< vector<double> > > realMapTotal(n);
vector< vector< vector<double> > > realMapDnDs(n);
VectorSiteContainer sites(tree->getLeavesNames(), alphabet);
for (unsigned int i = 0; i < n; ++i) {
ApplicationTools::displayGauge(i, n-1, '=');
RASiteSimulationResult* result = simulator.dSimulateSite();
realMap[i].resize(ids.size());
realMapTotal[i].resize(ids.size());
realMapDnDs[i].resize(ids.size());
for (size_t j = 0; j < ids.size(); ++j) {
realMap[i][j] = static_cast<double>(result->getSubstitutionCount(ids[j]));
realMapTotal[i][j].resize(totReg->getNumberOfSubstitutionTypes());
realMapDnDs[i][j].resize(dndsReg->getNumberOfSubstitutionTypes());
result->getSubstitutionCount(ids[j], *totReg, realMapTotal[i][j]);
result->getSubstitutionCount(ids[j], *dndsReg, realMapDnDs[i][j]);
if (realMapTotal[i][j][0] != realMap[i][j]) {
cerr << "Error, total substitution register provides wrong result." << endl;
return 1;
}
//if (abs(VectorTools::sum(realMapDetailed[i][j]) - realMap[i][j]) > 0.000001) {
// cerr << "Error, detailed substitution register provides wrong result." << endl;
// return 1;
//}
}
auto_ptr<Site> site(result->getSite(*model));
site->setPosition(static_cast<int>(i));
sites.addSite(*site, false);
delete result;
}
ApplicationTools::displayTaskDone();
//-------------
//Now build the substitution vectors with the true model:
//Fasta fasta;
//fasta.write("Simulations.fasta", sites);
DRHomogeneousTreeLikelihood drhtl(*tree, sites, model, rdist);
drhtl.initialize();
cout << drhtl.getValue() << endl;
SubstitutionCount* sCountAna = new LaplaceSubstitutionCount(model, 10);
Matrix<double>* m = sCountAna->getAllNumbersOfSubstitutions(0.001,1);
cout << "Analytical total count:" << endl;
MatrixTools::print(*m);
delete m;
ProbabilisticSubstitutionMapping* probMapAna =
SubstitutionMappingTools::computeSubstitutionVectors(drhtl, ids, *sCountAna);
SubstitutionCount* sCountTot = new NaiveSubstitutionCount(model, totReg);
m = sCountTot->getAllNumbersOfSubstitutions(0.001,1);
cout << "Simple total count:" << endl;
MatrixTools::print(*m);
delete m;
ProbabilisticSubstitutionMapping* probMapTot =
SubstitutionMappingTools::computeSubstitutionVectors(drhtl, ids, *sCountTot);
SubstitutionCount* sCountDnDs = new NaiveSubstitutionCount(model, dndsReg);
m = sCountDnDs->getAllNumbersOfSubstitutions(0.001,1);
cout << "Detailed count, type 1:" << endl;
MatrixTools::print(*m);
delete m;
ProbabilisticSubstitutionMapping* probMapDnDs =
SubstitutionMappingTools::computeSubstitutionVectors(drhtl, ids, *sCountDnDs);
SubstitutionCount* sCountUniTot = new UniformizationSubstitutionCount(model, totReg);
m = sCountUniTot->getAllNumbersOfSubstitutions(0.001,1);
cout << "Total count, uniformization method:" << endl;
MatrixTools::print(*m);
delete m;
ProbabilisticSubstitutionMapping* probMapUniTot =
SubstitutionMappingTools::computeSubstitutionVectors(drhtl, ids, *sCountUniTot);
SubstitutionCount* sCountUniDnDs = new UniformizationSubstitutionCount(model, dndsReg);
m = sCountUniDnDs->getAllNumbersOfSubstitutions(0.001,2);
cout << "Detailed count, uniformization method, type 2:" << endl;
MatrixTools::print(*m);
delete m;
ProbabilisticSubstitutionMapping* probMapUniDnDs =
SubstitutionMappingTools::computeSubstitutionVectors(drhtl, ids, *sCountUniDnDs);
//.........这里部分代码省略.........
开发者ID:matsen,项目名称:bpp-phyl,代码行数:101,代码来源:test_mapping_codon.cpp
示例15: getSubtreeMoments_
void TreeTemplateTools::getBestRootInSubtree_(TreeTemplate<Node>& tree, short criterion, Node* node, pair<Node*, map<string, double> >& bestRoot)
{
const vector<Node*> sons = node->getSons(); // copy
tree.rootAt(node);
// Try to place the root on each branch downward node
for (vector<Node*>::const_iterator son = sons.begin(); son != sons.end(); ++son)
{
// Compute the moment of the subtree on son's side
Moments_ son_moment = getSubtreeMoments_(*son);
// Compute the moment of the subtree on node's side
tree.rootAt(*son);
Moments_ node_moment = getSubtreeMoments_(node);
tree.rootAt(node);
/*
* Get the position of the root on this branch that
* minimizes the root-to-leaves distances variance.
*
* This variance can be written in the form A x^2 + B x + C
*/
double min_criterion_value;
double best_position; // 0 is toward the root, 1 is away from it
const TreeTemplateTools::Moments_& m1 = node_moment;
const TreeTemplateTools::Moments_& m2 = son_moment;
const double d = (**son).getDistanceToFather();
const double n1 = m1.numberOfLeaves;
const double n2 = m2.numberOfLeaves;
double A = 0, B = 0, C = 0;
if (criterion == MIDROOT_SUM_OF_SQUARES)
{
A = (n1 + n2) * d * d;
B = 2 * d * (m1.sum - m2.sum) - 2 * n2 * d * d;
C = m1.squaresSum + m2.squaresSum
+ 2 * m2.sum * d
+ n2 * d * d;
}
else if (criterion == MIDROOT_VARIANCE)
{
A = 4 * n1 * n2 * d * d;
B = 4 * d * ( n2 * m1.sum - n1 * m2.sum - d * n1 * n2);
C = (n1 + n2) * (m1.squaresSum + m2.squaresSum) + n1 * d * n2 * d
+ 2 * n1 * d * m2.sum - 2 * n2 * d * m1.sum
- (m1.sum + m2.sum) * (m1.sum + m2.sum);
}
if (A < 1e-20)
{
min_criterion_value = numeric_limits<double>::max();
best_position = 0.5;
}
else
{
min_criterion_value = C - B * B / (4 * A);
best_position = -B / (2 * A);
if (best_position < 0)
{
best_position = 0;
min_criterion_value = C;
}
else if (best_position > 1)
{
best_position = 1;
min_criterion_value = A + B + C;
}
}
// Is this branch is the best seen, update 'bestRoot'
if (min_criterion_value < bestRoot.second["score"])
{
bestRoot.first = *son;
bestRoot.second["position"] = best_position;
bestRoot.second["score"] = min_criterion_value;
}
// Recurse
TreeTemplateTools::getBestRootInSubtree_(tree, criterion, *son, bestRoot);
}
}
开发者ID:jbloomlab,项目名称:phydms,代码行数:82,代码来源:TreeTemplateTools.cpp
示例16: throw
TreeTemplate<Node>* BipartitionList::toTree() const throw (Exception)
{
BipartitionList* sortedBipL;
vector<int*> sortedBitBipL;
int* bip;
vector<Node*> vecNd, sonNd;
vector<bool> alive;
size_t lword, nbword, nbint, ii;
/* check, copy and prepare bipartition list */
if (!BipartitionList::areAllCompatible())
throw Exception("Trying to build a tree from incompatible bipartitions");
sortedBipL = dynamic_cast<BipartitionList*>(clone());
for (size_t i = 0; i < sortedBipL->getNumberOfBipartitions(); i++)
{
if (sortedBipL->getPartitionSize(i) > sortedBipL->getNumberOfElements() / 2)
sortedBipL->flip(i);
}
sortedBipL->sortByPartitionSize();
sortedBipL->removeRedundantBipartitions();
sortedBitBipL = sortedBipL->getBitBipartitionList();
for (size_t i = 0; i < sortedBipL->getNumberOfBipartitions(); i++)
{
alive.push_back(true);
}
vecNd.resize(sortedBipL->getNumberOfBipartitions() + 1);
lword = static_cast<size_t>(BipartitionTools::LWORD);
nbword = (elements_.size() + lword - 1) / lword;
nbint = nbword * lword / (CHAR_BIT * sizeof(int));
bip = new int[1]; bip[0] = 0;
/* main loop: create one node per bipartition */
for (size_t i = 0; i < sortedBipL->getNumberOfBipartitions(); i++)
{
if (sortedBipL->getPartitionSize(i) == 1)
{ // terminal
for (size_t j = 0; j < sortedBipL->getNumberOfElements(); j++)
{
if (BipartitionTools::testBit(sortedBitBipL[i], static_cast<int>(j)))
{
vecNd[i] = new Node(elements_[j]);
break;
}
}
}
else
{ // internal
sonNd.clear();
for (size_t j = 0; j < i; j++)
{
if (alive[j])
{
for (ii = 0; ii < nbint; ii++)
{
BipartitionTools::bitOr(bip, sortedBitBipL[j] + ii, sortedBitBipL[i] + ii, 1);
if (bip[0] != sortedBitBipL[i][ii])
break;
}
if (ii == nbint)
{
sonNd.push_back(vecNd[j]);
alive[j] = false;
}
}
}
vecNd[i] = new Node();
for (size_t k = 0; k < sonNd.size(); k++)
{
vecNd[i]->addSon(sonNd[k]);
}
}
}
/* create last node, which joins alive bipartitions = fatherless nodes */
Node* rootNd = new Node();
for (size_t i = 0; i < sortedBipL->getNumberOfBipartitions(); i++)
{
if (alive[i])
rootNd->addSon(vecNd[i]);
}
/* construct tree and return */
TreeTemplate<Node>* tr = new TreeTemplate<Node>(rootNd);
tr->resetNodesId();
delete sortedBipL;
return tr;
}
开发者ID:jbloomlab,项目名称:phydms,代码行数:90,代码来源:BipartitionList.cpp
示例17: computeNormProperties
void ClusterTools::computeNormProperties(TreeTemplate<Node>& tree, const ProbabilisticSubstitutionMapping & mapping)
{
double min;
computeNormProperties_(tree.getRootNode(), mapping, min);
}
开发者ID:jydu,项目名称:comap,代码行数:5,代码来源:ClusterTools.cpp
示例18: throw
ProbabilisticRewardMapping* RewardMappingTools::computeRewardVectors(
const DRTreeLikelihood& drtl,
const vector<int>& nodeIds,
Reward& reward,
bool verbose) throw (Exception)
{
// Preamble:
if (!drtl.isInitialized())
throw Exception("RewardMappingTools::computeRewardVectors(). Likelihood object is not initialized.");
// A few variables we'll need:
const TreeTemplate<Node> tree(drtl.getTree());
const SiteContainer* sequences = drtl.getData();
const DiscreteDistribution* rDist = drtl.getRateDistribution();
size_t nbSites = sequences->getNumberOfSites();
size_t nbDistinctSites = drtl.getLikelihoodData()->getNumberOfDistinctSites();
size_t nbStates = sequences->getAlphabet()->getSize();
size_t nbClasses = rDist->getNumberOfCategories();
vector<const Node*> nodes = tree.getNodes();
const vector<size_t>* rootPatternLinks
= &drtl.getLikelihoodData()->getRootArrayPositions();
nodes.pop_back(); // Remove root node.
size_t nbNodes = nodes.size();
// We create a new ProbabilisticRewardMapping object:
ProbabilisticRewardMapping* rewards = new ProbabilisticRewardMapping(tree, &reward, nbSites);
// Store likelihood for each rate for each site:
VVVdouble lik;
drtl.computeLikelihoodAtNode(tree.getRootId(), lik);
Vdouble Lr(nbDistinctSites, 0);
Vdouble rcProbs = rDist->getProbabilities();
Vdouble rcRates = rDist->getCategories();
for (size_t i = 0; i < nbDistinctSites; i++)
{
VVdouble* lik_i = &lik[i];
for (size_t c = 0; c < nbClasses; c++)
{
Vdouble* lik_i_c = &(*lik_i)[c];
double rc = rDist->getProbability(c);
for (size_t s = 0; s < nbStates; s++)
{
Lr[i] += (*lik_i_c)[s] * rc;
}
}
}
// Compute the reward for each class and each branch in the tree:
if (verbose)
ApplicationTools::displayTask("Compute joint node-pairs likelihood", true);
for (size_t l = 0; l < nbNodes; ++l)
{
// For each node,
const Node* currentNode = nodes[l];
if (nodeIds.size() > 0 && !VectorTools::contains(nodeIds, currentNode->getId()))
continue;
const Node* father = currentNode->getFather();
double d = currentNode->getDistanceToFather();
if (verbose)
ApplicationTools::displayGauge(l, nbNodes - 1);
Vdouble rewardsForCurrentNode(nbDistinctSites);
// Now we've got to compute likelihoods in a smart manner... ;)
VVVdouble likelihoodsFatherConstantPart(nbDistinctSites);
for (size_t i = 0; i < nbDistinctSites; i++)
{
VVdouble* likelihoodsFatherConstantPart_i = &likelihoodsFatherConstantPart[i];
likelihoodsFatherConstantPart_i->resize(nbClasses);
for (size_t c = 0; c < nbClasses; c++)
{
Vdouble* likelihoodsFatherConstantPart_i_c = &(*likelihoodsFatherConstantPart_i)[c];
likelihoodsFatherConstantPart_i_c->resize(nbStates);
double rc = rDist->getProbability(c);
for (size_t s = 0; s < nbStates; s++)
{
// (* likelihoodsFatherConstantPart_i_c)[s] = rc * model->freq(s);
// freq is already accounted in the array
(*likelihoodsFatherConstantPart_i_c)[s] = rc;
}
}
}
// First, what will remain constant:
size_t nbSons = father->getNumberOfSons();
for (size_t n = 0; n < nbSons; n++)
{
const Node* currentSon = father->getSon(n);
if (currentSon->getId() != currentNode->getId())
{
const VVVdouble* likelihoodsFather_son = &drtl.getLikelihoodData()->getLikelihoodArray(father->getId(), currentSon->getId());
// Now iterate over all site partitions:
auto_ptr<TreeLikelihood::ConstBranchModelIterator> mit(drtl.getNewBranchModelIterator(currentSon->getId()));
VVVdouble pxy;
//.........这里部分代码省略.........
开发者ID:matsen,项目名称:bpp-phyl,代码行数:101,代码来源:RewardMappingTools.cpp
示例19: main
int main() {
TreeTemplate<Node>* tree = TreeTemplateTools::parenthesisToTree("(((A:0.1, B:0.2):0.3,C:0.1):0.2,(D:0.3,(E:0.2,F:0.05):0.1):0.1);");
vector<string> seqNames= tree->getLeavesNames();
vector<int> ids = tree->getNodesId();
//-------------
const NucleicAlphabet* alphabet = &a
|
请发表评论