Chain ModelGetter::GetModel() { const int MAX_LEN = 1024 ; char cur_line[1024] ; Chain chain ; while (!infile_.eof()) { double model[6] ; infile_.getline(cur_line, MAX_LEN) ; int num_read = sscanf(cur_line, "%lf %lf %lf %lf %lf %lf", &model[0], &model[1], &model[2], &model[3], &model[4], &model[5]) ; if (num_read < 6) break ; // Now add the data to the chain Joint J(Joint::RotZ) ; Vector rot_axis(model[3], model[4], model[5]) ; // KDL doesn't need vector to be normalized. It even behaves nicely with vector=[0 0 0] double rot_ang = rot_axis.Norm() ; Rotation R(Rotation::Rot(rot_axis, rot_ang)) ; Vector trans(model[0], model[1], model[2]) ; chain.addSegment(Segment(J, Frame(R, trans))) ; } return chain ; }
/** get all chains from the matching */ const RamAutoIndex::ChainOrderMap RamAutoIndex::getChainsFromMatching(const RamMaxMatching::Matchings& match, const SearchSet& nodes) { ASSERT(nodes.size() > 0); // Get all unmatched nodes from A const SearchSet& umKeys = getUnmatchedKeys(match, nodes); // Case: if no unmatched nodes then we have an anti-chain if (umKeys.size() == 0){ for (SearchSet::const_iterator nit = nodes.begin(); nit != nodes.end(); ++nit) { std::set<SearchColumns> a; a.insert(*nit); chainToOrder.push_back(a); return chainToOrder; } } ASSERT(umKeys.size() > 0); // A worklist of used nodes SearchSet usedKeys; // Case: nodes < umKeys or if nodes == umKeys then anti chain - this is handled by this loop for (SearchSet::iterator it = umKeys.begin(); it != umKeys.end(); ++it) { Chain c = getChain(*it, match); ASSERT(c.size() > 0); chainToOrder.push_back(c); } ASSERT(chainToOrder.size() > 0); return chainToOrder; }
void SolverTest::FkPosAndIkPosLocal(Chain& chain,ChainFkSolverPos& fksolverpos, ChainIkSolverPos& iksolverpos) { JntArray q(chain.getNrOfJoints()); for(unsigned int i=0; i<chain.getNrOfJoints(); i++) { random(q(i)); } JntArray q_init(chain.getNrOfJoints()); double tmp; for(unsigned int i=0; i<chain.getNrOfJoints(); i++) { random(tmp); q_init(i)=q(i)+0.1*tmp; } JntArray q_solved(q); Frame F1,F2; CPPUNIT_ASSERT(0==fksolverpos.JntToCart(q,F1)); CPPUNIT_ASSERT(0 <= iksolverpos.CartToJnt(q_init,F1,q_solved)); CPPUNIT_ASSERT(0==fksolverpos.JntToCart(q_solved,F2)); CPPUNIT_ASSERT_EQUAL(F1,F2); //CPPUNIT_ASSERT_EQUAL(q,q_solved); }
void SolverTest::FkPosAndJacLocal(Chain& chain,ChainFkSolverPos& fksolverpos,ChainJntToJacSolver& jacsolver) { double deltaq = 1E-4; Frame F1,F2; JntArray q(chain.getNrOfJoints()); Jacobian jac(chain.getNrOfJoints()); for(unsigned int i=0; i<chain.getNrOfJoints(); i++) { random(q(i)); } jacsolver.JntToJac(q,jac); for (unsigned int i=0; i< q.rows() ; i++) { // test the derivative of J towards qi double oldqi = q(i); q(i) = oldqi+deltaq; CPPUNIT_ASSERT(0==fksolverpos.JntToCart(q,F2)); q(i) = oldqi-deltaq; CPPUNIT_ASSERT(0==fksolverpos.JntToCart(q,F1)); q(i) = oldqi; // check Jacobian : Twist Jcol1 = diff(F1,F2,2*deltaq); Twist Jcol2(Vector(jac(0,i),jac(1,i),jac(2,i)), Vector(jac(3,i),jac(4,i),jac(5,i))); //CPPUNIT_ASSERT_EQUAL(true,Equal(Jcol1,Jcol2,epsJ)); CPPUNIT_ASSERT_EQUAL(Jcol1,Jcol2); } }
void SolverTest::FkVelAndIkVelLocal(Chain& chain, ChainFkSolverVel& fksolvervel, ChainIkSolverVel& iksolvervel) { JntArray q(chain.getNrOfJoints()); JntArray qdot(chain.getNrOfJoints()); for(unsigned int i=0; i<chain.getNrOfJoints(); i++) { random(q(i)); random(qdot(i)); } JntArrayVel qvel(q,qdot); JntArray qdot_solved(chain.getNrOfJoints()); FrameVel cart; CPPUNIT_ASSERT(0==fksolvervel.JntToCart(qvel,cart)); int ret = iksolvervel.CartToJnt(qvel.q,cart.deriv(),qdot_solved); CPPUNIT_ASSERT(0<=ret); qvel.deriv()=qdot_solved; if(chain.getNrOfJoints()<=6) CPPUNIT_ASSERT(Equal(qvel.qdot,qdot_solved,1e-5)); else { FrameVel cart_solved; CPPUNIT_ASSERT(0==fksolvervel.JntToCart(qvel,cart_solved)); CPPUNIT_ASSERT(Equal(cart.deriv(),cart_solved.deriv(),1e-5)); } }
bool KDLColladaLibraryJointsExporter::doExport(vector <Chain>& kdlChains) { if (kdlChains.empty()) { LOG(DEBUG) << "KDL Chains array is empty, has nothing to export"; return false; } LOG(WARNING) << "Taking first element from the KDL chain array"; Chain kdlChain = kdlChains[0]; openLibrary(); unsigned int jointNr = kdlChain.getNrOfSegments(); for (unsigned int i = 0; i < jointNr; i++) { Segment segment = kdlChain.getSegment(i); Joint kdlJoint = segment.getJoint(); string uniqueId = defaultJointIdPrefix + toString(i); COLLADASW::Joint colladaJoint = makeColladaSWJoint(COLLADASW::LibraryJoints::mSW, kdlJoint, uniqueId); LOG(INFO) << "Joint id: " << colladaJoint.getJointId(); LOG(INFO) << "Joint name: " << colladaJoint.getJointName(); addJoint(colladaJoint); joints.push_back(colladaJoint); } closeLibrary(); return true; }
void score_res(ScoreBase * scoring, std::string filename, std::string score_type = "pairing") { Chain chain; int i, j, l; chain_read_model(chain, filename); l = chain.size(); //JN_JN_OUT << l << std::endl; for (i = 0; i < l; i++) { for (j = 0; j < l; j++) { if (i == j) JN_OUT << 0 << "\t"; else { scoring->en_bp(chain[i], chain[j]); if (score_type == "pairing") JN_OUT << scoring->m_en_pairing << "\t"; else if (score_type == "stacking") JN_OUT << scoring->m_en_stacking << "\t"; else if (score_type == "wc") JN_OUT << scoring->m_en_wc << "\t"; else if (score_type == "nwc") JN_OUT << scoring->m_en_nwc << "\t"; else { LOG << "Illegal score type: " << score_type << std::endl; throw "error!"; } } } JN_OUT << std::endl; } }
int main () { Chain ch; ch.start.init(); ch.chainBuilder (&ch.start, 5); ch.chainWalker (&ch.start); }
// Merges two chains void Board::mergeChains(Chain *node, int otherID, Move m) { // Find the chain to merge into the first chain Chain *temp = nullptr; int tempIndex = searchChainsByID(temp, otherID); // Update the chain id array when merging for (int i = 0; i < temp->size; i++) { Move idChange = temp->squares[i]; chainID[index(getX(idChange), getY(idChange))] = node->id; node->add(idChange); } // Remove the move played from the other list of liberties temp->removeLiberty(temp->findLiberty(m)); // And then merge the two lists for (int i = 0; i < temp->liberties; i++) { // If the liberty is not a repeat if (node->findLiberty(temp->libertyList[i]) == -1) node->addLiberty(temp->libertyList[i]); } // Delete the chain "temp" now since it has been fully merged in delete temp; chainList.removeFast(tempIndex); }
void TestPart2(){ Chain<string> a, b; a.ReadChain(); // User provides input for Chain a. cout <<"A: "<< a <<endl; cout <<"A.size: "<< a.Size()<<endl; b.ReadChain(); // User provides input for Chain b. cout <<"B: "<< b << endl; cout <<"B.size: "<< b.Size()<<endl; cout <<"A+B: "<<a + b << endl; // Concatenates the two Chains. Chain<string> d = a + b; cout <<"D: "<< d << endl; cout <<"D.size: "<< d.Size()<<endl; cout <<"D+: "<< d + "hi_there" <<endl; // Adds an element to the end. cout <<"D+.size: "<< d.Size()<<endl; cout <<"A[2]: "<< a[2] << endl; // Should print the 3rd element. // Throw an exception (or even abort()) if is out of // range. b[1] = "b_string"; // Should change the 2nd element to “b_string” cout <<"B: "<< b << endl; b[0] = "a_string"; cout <<"B: "<< b <<endl; cout <<"B.size: "<< b.Size()<<endl; } // End of TestPart2
size_t Board::removeCapturedStones (StoneColor colorToCapture) { LOG_FUNCTION(cout, "Board::removeCapturedStones"); size_t captureCount = 0; // A set of points that we've already examined. This helps prevents some // bad recursion and keeps a chain from being "found" once for each stone // in the chain. // ConstPointSet alreadyVisited; for (size_t row = 0; row < m_points.size(); ++row) { for (size_t column = 0; column < m_points[row].size(); ++column) { const Point & thePoint = m_points.at(row).at(column); // If the point we are considering has already been visited, // then Chain's ctor will throw a PointVisitedAlreadyException // object. We can safely swallow that exception and move on // to the next point. // try { Chain currentChain {thePoint, *this, &alreadyVisited}; gLogger.log(LogLevel::kMedium, cout, "Discovered chain"); // " : ", chain); // If the chain we are looking at is the color we should consider capturing and // the chain has no liberties, then capture it // if (currentChain.color() == colorToCapture && currentChain.libertyCount() == 0) { captureCount += currentChain.size(); // For each point in the chain, remove the stone from the board // at those coordniates // currentChain.forEachPoint([this](const Point & point) { LOG_BUSY_FUNCTION(cout, "Chain::removeCapturedStones::lambda_doStoneRemoval"); m_points[point.coordinates.row][point.coordinates.column].removeStone(); }); } } catch (const Chain::PointVisitedAlreadyException & ex) { gLogger.log(LogLevel::kFirehose, cout, "Skipping ", thePoint); } } } // If we ended up only capturing one stone, the 'Ko' rule might affect // the next move, so remember that fact! // m_koState.first = (captureCount == 1); return captureCount; }
void reset(){ for (int i =0;i<chain.num();++i){ chain.link(i).pos(0,2,offset); chain.link(i).rot() = Gen::rot(Biv::xz * PIOVERFOUR); } }
int VerifyJacobian::ComputeMaxError(const std::string& model_file, const std::string& joint_params_file, const std::string& jacobians_file, double& max_error) { int result ; result = model_getter_.OpenFile(model_file) ; if (result < 0) return -1 ; result = joint_params_getter_.OpenFile(joint_params_file) ; if (result < 0) return -1 ; result = jacobians_getter_.OpenFile(jacobians_file) ; if (result < 0) return -1 ; Chain chain = model_getter_.GetModel() ; const unsigned int J = chain.getNrOfJoints() ; JntArray joint_array(J) ; result = joint_params_getter_.GetNextJointArray(joint_array) ; if (result < 0) return -1 ; LinkParamJacobian jac_actual ; jac_actual.twists_.resize(J) ; result = jacobians_getter_.GetNextJacobian(jac_actual) ; // Compute the jacobian using KDL functions LinkParamJacobian jac_computed ; jac_computed.twists_.resize(J) ; LinkParamJacobianSolver jac_solver ; jac_solver.JointsToCartesian(chain, joint_array, jac_computed) ; max_error = 0.0 ; for (unsigned int i=0; i < jac_computed.twists_.size(); i++) { for (unsigned int j=0; j<3; j++) { for (unsigned int k=0; k<3; k++) { double cur_error ; cur_error = fabs( jac_computed.twists_[i].trans_[j].vel(k) - jac_actual.twists_[i].trans_[j].vel(k) ) ; if (cur_error > max_error) max_error = cur_error ; cur_error = fabs( jac_computed.twists_[i].rot_[j].vel(k) - jac_actual.twists_[i].rot_[j].vel(k) ) ; if (cur_error > max_error) max_error = cur_error ; } } } return 0 ; }
bool Tree::addChain(const Chain& chain, const std::string& hook_name) { string parent_name = hook_name; for (unsigned int i = 0; i < chain.getNrOfSegments(); i++) { if (this->addSegment(chain.getSegment(i), parent_name)) parent_name = chain.getSegment(i).getName(); else return false; } return true; }
void Module::set ( Log_Entry &e ) { for ( int i = 0; i < e.size(); ++i ) { const char *s, *v; e.get( i, &s, &v ); if ( ! strcmp( s, ":chain" ) ) { /* This trickiness is because we may need to know the name of our chain before we actually get added to it. */ int i; sscanf( v, "%X", &i ); Chain *t = (Chain*)Loggable::find( i ); assert( t ); chain( t ); } } for ( int i = 0; i < e.size(); ++i ) { const char *s, *v; e.get( i, &s, &v ); /* if ( ! strcmp( s, ":name" ) ) */ /* label( v ); */ if ( ! strcmp( s, ":parameter_values" ) ) { set_parameters( v ); } else if ( ! ( strcmp( s, ":is_default" ) ) ) { is_default( atoi( v ) ); } else if ( ! ( strcmp( s, ":active" ) ) ) { bypass( ! atoi( v ) ); } else if ( ! strcmp( s, ":chain" ) ) { int i; sscanf( v, "%X", &i ); Chain *t = (Chain*)Loggable::find( i ); assert( t ); t->add( this ); } } }
// method calculates error between two chains, used in finduniquecombination method // // Chain upper: the first chain, uses i values // Chain lower: the second chain, uses i-1 values // // returns: double of error amount double SearchStrategy::assignmentError(Chain upper, Chain lower) { double AiM1 = (lower.first()).getCAIM()[0]; double BiM1 = (lower.first()).getCBIM()[0]; double Ai = (upper.last()).getCAI()[0]; double Bi = (upper.last()).getCBI()[0]; double squashedError = abs((AiM1 - Ai) / Ai) + abs((BiM1 - Bi)/ Bi); return squashedError; }
Chain operator+( const Chain & b) const { Chain result( size()+b.size()); auto leftover = ctl::detail::chain_add( rbegin(), rend(), b.rbegin(), b.rend(), result.rbegin(), std::bind(Less(), std::placeholders::_2, std::placeholders::_1), Chain::coeff_tag()); result._chain.erase( leftover, result.rend()); return result; }
int FastaReader::getIndex(Chain &_ch, std::string _posId, std::string _key){ Position &pos = _ch.getPosition(_posId); // get fasta seq. string fasta = getSequence(_key); #ifdef __BOOST__ int posIndex = _ch.getPositionIndex(&pos); // Find index of first non '-' character boost::regex re("^-*(!-)"); boost::cmatch matches; if (!boost::regex_match(fasta.c_str(),matches,re)) { cerr << "ERROR 9234 with boost match"<<endl; exit(9234); } //cout << "Match: "<<matches.position()<< " fasta AA is: "<<fasta[matches.position()]<<endl; // Go from matches[0].first to posIndex OR end of string int index = matches.position(); int posIndex_counter = posIndex; while (index != fasta.size()){ if (fasta[index] != '-'){ posIndex_counter--; } // Check if we are here! if (posIndex_counter == 0){ break; } index++; } if (posIndex_counter == 0){ // Check it the position and this index have the same AA, if not then probably there is an issue. if (MslTools::getOneLetterCode(pos.getResidueName()) != MslTools::stringf("%c",fasta[index])){ cerr << "ERROR 9255 Position AA is: "<<MslTools::getOneLetterCode(pos.getResidueName())<< " and Fasta AA is: "<<fasta[index]<<endl; exit(9255); } // Return the index return index; } #endif return -1; }
int main(int argc, const char* argv[]) { stringstream strm; strm << "line (5.12,0.11,-2.5),(10,-7.5,2.4)"; string str = strm.str(); PtrStrVec str_vec = string_splitter(str); Chain* ch = new Chain(str_vec); double* params = ch->solve(); /*Solid* s = factory(5,RGB(0,0,0),params); delete s;*/ delete [] params; delete ch; delete str_vec; return 0; };
bool Tree::addChain(const Chain& chain, const std::string& chain_name, const std::string& hook_name) { string parent_name = hook_name; for (unsigned int i = 0; i < chain.getNrOfSegments(); i++) { ostringstream segment_name; segment_name << chain_name << "Segment" << i; if (this->addSegment(chain.getSegment(i), segment_name.str(), parent_name)) parent_name = segment_name.str(); else return false; } return true; }
std::string operator()(const std::vector<std::string> & argvec) { if (argvec.size() != 4) { return interp->RunCommand("help alias") + "\n(Please refer to the help documentation for proper invocation)"; } // First get the alias name std::string cmd = argvec[1]; std::vector<std::string> cmds; // Next get the arguments. Chain argSrc = argvec[2].c_str(); std::vector<std::string> args; argSrc.SetDelimiters(","); while(argSrc.LinksLeft()) { args.push_back(argSrc.GetLink().c_str()); argSrc++; } Chain src = argvec[3].c_str(); src.SetDelimiters(","); while(src.LinksLeft()) { cmds.push_back(src.GetLink().c_str()); src++; } interp->AddCommand(cmd, new SubCommand(cmds, args, interp)); return std::string("Set new command: ") + cmd; }
void ConstellationBoundaries::render() { for (vector<Chain*>::iterator iter = chains.begin(); iter != chains.end(); iter++) { Chain* chain = *iter; glBegin(GL_LINE_STRIP); for (Chain::iterator citer = chain->begin(); citer != chain->end(); citer++) { glVertex(*citer); } glEnd(); } }
bool Tree::getChain(const std::string& chain_root, const std::string& chain_tip, Chain& chain)const { // clear chain chain = Chain(); // walk down from chain_root and chain_tip to the root of the tree vector<SegmentMap::key_type> parents_chain_root, parents_chain_tip; for (SegmentMap::const_iterator s=getSegment(chain_root); s!=segments.end(); s=s->second.parent){ parents_chain_root.push_back(s->first); if (s->first == root_name) break; } if (parents_chain_root.empty() || parents_chain_root.back() != root_name) return false; for (SegmentMap::const_iterator s=getSegment(chain_tip); s!=segments.end(); s=s->second.parent){ parents_chain_tip.push_back(s->first); if (s->first == root_name) break; } if (parents_chain_tip.empty() || parents_chain_tip.back() != root_name) return false; // remove common part of segment lists SegmentMap::key_type last_segment = root_name; while (!parents_chain_root.empty() && !parents_chain_tip.empty() && parents_chain_root.back() == parents_chain_tip.back()){ last_segment = parents_chain_root.back(); parents_chain_root.pop_back(); parents_chain_tip.pop_back(); } parents_chain_root.push_back(last_segment); // add the segments from the root to the common frame for (unsigned int s=0; s<parents_chain_root.size()-1; s++){ Segment seg = getSegment(parents_chain_root[s])->second.segment; Frame f_tip = seg.pose(0.0).Inverse(); Joint jnt = seg.getJoint(); if (jnt.getType() == Joint::RotX || jnt.getType() == Joint::RotY || jnt.getType() == Joint::RotZ || jnt.getType() == Joint::RotAxis) jnt = Joint(jnt.getName(), f_tip*jnt.JointOrigin(), f_tip.M*jnt.JointAxis(), Joint::RotAxis); else if (jnt.getType() == Joint::TransX || jnt.getType() == Joint::TransY || jnt.getType() == Joint::TransZ || jnt.getType() == Joint::TransAxis) jnt = Joint(jnt.getName(),f_tip*jnt.JointOrigin(), f_tip.M*jnt.JointAxis(), Joint::TransAxis); chain.addSegment(Segment(getSegment(parents_chain_root[s+1])->second.segment.getName(), jnt, f_tip, getSegment(parents_chain_root[s+1])->second.segment.getInertia())); } // add the segments from the common frame to the tip frame for (int s=parents_chain_tip.size()-1; s>-1; s--){ chain.addSegment(getSegment(parents_chain_tip[s])->second.segment); } return true; }
ChainIkSolverPos_LMA_JL_Mimic::ChainIkSolverPos_LMA_JL_Mimic(const Chain& _chain, const JntArray& _q_min, const JntArray& _q_max, ChainFkSolverPos& _fksolver, ChainIkSolverPos_LMA& _iksolver, unsigned int _maxiter, double _eps, bool _position_ik) : chain(_chain), q_min(_q_min), q_min_mimic(chain.getNrOfJoints()), q_max(_q_max), q_max_mimic(chain.getNrOfJoints()), q_temp(chain.getNrOfJoints()), fksolver(_fksolver), iksolver(_iksolver), delta_q(_chain.getNrOfJoints()), maxiter(_maxiter), eps(_eps), position_ik(_position_ik) { mimic_joints.resize(chain.getNrOfJoints()); for(std::size_t i=0; i < mimic_joints.size(); ++i) { mimic_joints[i].reset(i); } }
Chain FullMorphologyChainTransformer::ForwardTransform(Chain& chain) const { int oldLength = chain.GetSize(); if (oldLength == 0) { return chain; } // Create tokens const vector<wstring>& oldTokens = chain.GetTokens(); vector<wstring> tokens(2 * oldLength - 1); for (size_t nodeIndex = 0; nodeIndex + 1 < oldTokens.size(); ++nodeIndex) { tokens[2 * nodeIndex + 1] = L"copy_" + oldTokens[nodeIndex]; tokens[2 * nodeIndex] = std::move(oldTokens[nodeIndex]); } // Create labels const vector<wstring>& oldLabels = chain.GetLabels(); vector<wstring> labels(2 * oldLength - 1); for (size_t nodeIndex = 0; nodeIndex + 1 < oldLabels.size(); ++nodeIndex) { const wstring& fullLabel = oldLabels[nodeIndex]; if (fullLabel.size() > 0) { vector<wstring> splitted; splitted = Tools::Split(fullLabel, L"@"); labels[2 * nodeIndex] = fullLabel; labels[2 * nodeIndex + 1] = L"POS_" + splitted[0]; } } labels[labels.size() - 1] = oldLabels.back(); // Create features const vector<vector<wstring> >& oldFeatures = chain.GetFeatures(); vector<vector<wstring> > features(2 * oldLength - 1); for (size_t nodeIndex = 0; nodeIndex + 1 < oldLabels.size(); ++nodeIndex) { features[2 * nodeIndex] = oldFeatures[nodeIndex]; features[2 * nodeIndex + 1] = std::move(oldFeatures[nodeIndex]); } features[features.size() - 1] = oldFeatures.back(); // Return chain Chain transformed( std::move(tokens) , std::move(features) , std::move(labels) , vector<vector<wstring> >()); return transformed; }
ChainIkSolverPos_NR::ChainIkSolverPos_NR(const Chain& _chain,ChainFkSolverPos& _fksolver,ChainIkSolverVel& _iksolver, unsigned int _maxiter, double _eps): chain(_chain),nj (chain.getNrOfJoints()), iksolver(_iksolver),fksolver(_fksolver), delta_q(_chain.getNrOfJoints()), maxiter(_maxiter),eps(_eps) { }
typename CollapsedAKQReducedCubSComplexSupplier<Traits>::Chain CollapsedAKQReducedCubSComplexSupplier<Traits>::GetBoundary(const Id& cellId) { OutputSComplex* outputComplex = _algorithm->getStrategy()->getOutputComplex(); Cell cell = (*outputComplex)[cellId]; Chain boundary; BdCells bdCells = outputComplex->iterators().bdCells(cell); typename BdCells::iterator it = bdCells.begin(); typename BdCells::iterator itEnd = bdCells.end(); for ( ; it != itEnd; ++it) { int ci = outputComplex->coincidenceIndex(cell, *it); assert(ci != 0); boundary.push_back(std::pair<Id, int>(it->getId(), ci)); } return boundary; }
int main(int argc, const char *argv[]) { Chain<int> X; int numbers[] = { 216, 521, 425, 116, 91, 515, 124, 34, 96, 24}; for (int i = 0; i < 10; i++) X.Insert(0, numbers[i]); std::cout<<"X is "<<X<<std::endl; X.BinSort(9, GeWei); std::cout<<"after BinSort, X is "<<X<<std::endl; X.BinSort(9, ShiWei); std::cout<<"after BinSort, X is "<<X<<std::endl; X.BinSort(9, BaiWei); std::cout<<"after BinSort, X is "<<X<<std::endl; return 0; }
// 1/4/2016 // 'demographicPara' is a 1x6 matrix. long double MaxPosterior::computeLogJointDensity_MPI_overSubLoci(Eigen::MatrixXd demographicPara, IM im, popTree* poptree, Chain coldCh, unsigned int nProcs, unsigned int crr_procID) { // std::cout <<"In computeLogJointDensity_MPI_overSubLoci()\n"; poptree->replacePara(demographicPara); coldCh.compute_partialJointPosteriorDensity_overSubLoci(poptree, im, crr_procID, nProcs); std::vector<long double> logExpectationOfEachCoalProb = coldCh.get_logExpectationOfCoalProb(); unsigned int numSubLoci = coldCh.getNumSubLoci(); // std::cout <<"numSubLoci ="<<numSubLoci <<"\n"; long double posterior = 1; if(numSubLoci != logExpectationOfEachCoalProb.size()) { std::cout << "** Error In MaxPosterior::computeJointDensity_MPI_overSubSample() **\n"; std::cout << "numSubLoci = " << numSubLoci << " expectationOfEachCoalProb.size() = " << logExpectationOfEachCoalProb.size() <<"\n\n"; } long double local_logPosterior_subLoci =0; long double global_logPosterior = 0; for(unsigned int lc=0; lc< numSubLoci; lc++) { local_logPosterior_subLoci += logExpectationOfEachCoalProb.at(lc); } MPI::COMM_WORLD.Barrier(); MPI::COMM_WORLD.Allreduce(&local_logPosterior_subLoci, &global_logPosterior, 1, MPI_LONG_DOUBLE, MPI_SUM); MPI::COMM_WORLD.Barrier(); long double logPosterior = 0; if(crr_procID ==0) { Eigen::Vector3d paraMax = im.get_paraMax(); double priorPopTree = poptree->computeJointPrior(paraMax); //posterior = exp(global_logPosterior+log(priorPopTree)); logPosterior = global_logPosterior; // +log(priorPopTree); // std::cout <<"log(priorPopTree) = " << log(priorPopTree) <<"\n"; } // std::cout << "crr_procID=" << crr_procID << " logPosterior = " << logPosterior <<"\n"; return logPosterior; }
/** * Runs the epoch simulation for the period and updates the variables. * * Similar to: siena07models.cpp mlPeriod() * * @param m Period. */ void MetropolisHastingsSimulation::simulatePeriod(const int m) { MLSimulation* pSim = new MLSimulation(lpData, lpModel); // Update simulations pSim->simpleRates(lpModel->simpleRates()); pSim->currentPermutationLength(lpModel->currentPermutationLength(m)); pSim->missingNetworkProbability( static_cast<const Model*>(lpModel)->missingNetworkProbability(m)); pSim->missingBehaviorProbability( static_cast<const Model*>(lpModel)->missingBehaviorProbability(m)); LOGS(Priority::VERBOSE)<<"\nSimple rates: "<<pSim->simpleRates() <<"\nCurrent permutation length: "<<pSim->currentPermutationLength() <<"\nMissing network probability: "<<pSim->missingNetworkProbability() <<"\nMissing behavior probability: "<<pSim->missingBehaviorProbability(); pSim->pChain(lpModel->rChainStore(m).back()->copyChain()); lpModel->needScores(false); lpModel->needDerivatives(false); lpModel->numberMLSteps(lNRunMH[m]); LOGS(Priority::VERBOSE)<<"\nNum steps: "<<lpModel->numberMLSteps(); pSim->runEpoch(m); // Run through current state of chain and calculate scores and derivatives. lpModel->needScores(true); // !onlyLoglik (bayes) lpModel->needDerivatives(lNeedsDerivative); pSim->updateProbabilities(pSim->pChain(), pSim->pChain()->pFirst()->pNext(), pSim->pChain()->pLast()->pPrevious()); // Store chain on Model. Chain* pChain = pSim->pChain(); pChain->createInitialStateDifferences(); pSim->createEndStateDifferences(); lpModel->chainStore(*pChain, m); lpModel->currentPermutationLength(m, pSim->currentPermutationLength()); // Add up period results. addSingleScores(lScores[0], m, *pSim); addSingleDerivatives(lDerivative[0], m, *pSim); LOGS(Priority::DEBUG)<<"Scores: "<<lScores[0].transpose(); }