/** return log(|psi|) * * PhaseValue is the phase for the complex wave function */ TrialWaveFunction::RealType TrialWaveFunction::evaluateLog(ParticleSet& P) { P.G = 0.0; P.L = 0.0; ValueType logpsi(0.0); PhaseValue=0.0; vector<OrbitalBase*>::iterator it(Z.begin()); vector<OrbitalBase*>::iterator it_end(Z.end()); //WARNING: multiplication for PhaseValue is not correct, fix this!! for(; it!=it_end; ++it) { logpsi += (*it)->evaluateLog(P, P.G, P.L); PhaseValue += (*it)->PhaseValue; } return LogValue=real(logpsi); }
double calcDistance(const Graph& g, const EdgeWeightMap& edge_weight_map, const VertexVector& vertices) { VertexVector::const_iterator it(vertices.begin()), it_end(vertices.end()); --it_end; EdgeDescriptor edge; double length = 0; for (; it != it_end; ++it) { length += distance(g, edge_weight_map, *it, *boost::next(it)); } length += distance(g, edge_weight_map, vertices.back(), vertices.front()); return length; }
//-------------------------------------------------------------------------- void FLevelFile::loadModels() { HRCFileManager &hrc_mgr( HRCFileManager::getSingleton() ); ModelList &models( m_model_list->getModels() ); ModelList::const_iterator it ( models.begin() ) , it_end( models.end() ); while( it != it_end ) { String hrc_name( it->hrc_name ); Ogre::LogManager::getSingleton().stream() << "Loading Model: " << hrc_name; StringUtil::toLowerCase( hrc_name ); HRCFilePtr hrc( hrc_mgr.load( hrc_name, mGroup ) ); loadAnimations( hrc, it->animations ); m_hrc_files.push_back( hrc ); ++it; } }
//------------------------------------------------------------------------- Ogre::StringVectorPtr LGPArchive::find( const String& pattern, bool recursive, bool dirs ) { LOG_DEBUG( pattern ); //OGRE_LOCK_AUTO_MUTEX Ogre::StringVector* file_names( OGRE_NEW_T( Ogre::StringVector, Ogre::MEMCATEGORY_GENERAL)() ); Ogre::FileInfoListPtr found_infos( findFileInfo( pattern, recursive, dirs ) ); Ogre::FileInfoList::const_iterator it( found_infos->begin() ), it_end( found_infos->end() ); while( it != it_end ) { file_names->push_back( it->filename ); ++it; } return Ogre::StringVectorPtr( file_names, Ogre::SPFM_DELETE_T ); }
//-------------------------------------------------------------------------- void FLevelFile::loadAnimations( const HRCFilePtr &model, const AnimationList &animations ) { AFileManager &a_mgr( AFileManager::getSingleton() ); AnimationList::const_iterator it ( animations.begin() ) , it_end( animations.end() ); while( it != it_end ) { String animation_name; StringUtil::splitBase( it->name, animation_name ); StringUtil::toLowerCase( animation_name ); String animation_filename( animation_name + FF7::EXT_A ); AFilePtr animation( a_mgr.load( animation_filename, model->getGroup() ) ); animation_name = FF7::NameLookup::animation( animation_name ); Ogre::LogManager::getSingleton().stream() << " Adding Animation: " << animation_name; animation->addTo( model->getSkeleton(), animation_name ); ++it; } }
/** evaluate the log value of a many-body wave function * @param P input configuration containing N particles * @param needratio users request ratio evaluation * @param buf anonymous storage for the reusable data * @return the value of \f$ \log( \Pi_i \Psi_i) \f$ many-body wave function * * @if needratio == true * need to update the data from buf, since external objects need to evaluate ratios, e.g., non-local pseudopotentials * @else * evaluate the value only * * Upon return, the gradient and laplacian operators are added by the components. * Each OrbitalBase evaluates PhaseValue and LogValue = log(abs(psi_i)) * Jastrow functions always have PhaseValue=1. */ TrialWaveFunction::RealType TrialWaveFunction::evaluateDeltaLog(ParticleSet& P) { P.G = 0.0; P.L = 0.0; ValueType logpsi(0.0); PhaseValue=0.0; vector<OrbitalBase*>::iterator it(Z.begin()); vector<OrbitalBase*>::iterator it_end(Z.end()); for (; it!=it_end; ++it) { if ((*it)->Optimizable) { logpsi += (*it)->evaluateLog(P, P.G, P.L); PhaseValue += (*it)->PhaseValue; } } convert(logpsi,LogValue); return LogValue; //return LogValue=real(logpsi); }
void QMCCSLinearOptimizeWFmanagerOMP::resetPsi(bool final_reset) { if (OptVariables.size() < OptVariablesForPsi.size()) { for (int i=0; i<equalVarMap.size(); ++i) OptVariablesForPsi[equalVarMap[i][0]]=OptVariables[equalVarMap[i][1]]; } else for (int i=0; i<OptVariables.size(); ++i) OptVariablesForPsi[i]=OptVariables[i]; if (final_reset) { for (int i=0; i<psiClones.size(); ++i) psiClones[i]->stopOptimization(); #pragma omp parallel { int ip = omp_get_thread_num(); MCWalkerConfiguration& wRef(*wClones[ip]); MCWalkerConfiguration::iterator it(wRef.begin()); MCWalkerConfiguration::iterator it_end(wRef.end()); for (; it!=it_end; ++it) (**it).DataSetForDerivatives.clear(); } // is this correct with OMP? // MCWalkerConfiguration::iterator it(W.begin()); // MCWalkerConfiguration::iterator it_end(W.end()); // for (; it!=it_end; ++it) // (**it).DataSetForDerivatives.clear(); } //cout << "######### QMCCSLinearOptimizeWFmanagerOMP::resetPsi " << endl; // OptVariablesForPsi.print(cout); //cout << "-------------------------------------- " << endl; Psi.resetParameters(OptVariablesForPsi); for (int i=0; i<psiClones.size(); ++i) psiClones[i]->resetParameters(OptVariablesForPsi); // for (int i=0; i<psiClones.size(); ++i) // psiClones[i]->reportStatus(app_log()); }
/** main functio to optimize multiple contracted S orbitals */ void GTO2Slater::optimize() { //construct one-dim grid double ri = 1e-5; double rf = 10.0; int npts = 101; string gridType("log"); if(gridPtr) { OhmmsAttributeSet radAttrib; radAttrib.add(gridType,"type"); radAttrib.add(npts,"npts"); radAttrib.add(ri,"ri"); radAttrib.add(rf,"rf"); radAttrib.put(gridPtr); } myGrid.set(ri,rf,npts); //create a numerical grid funtor typedef OneDimCubicSpline<double> RadialOrbitalType; RadialOrbitalType radorb(&myGrid); int L= 0; //Loop over all the constracted S orbitals map<string,xmlNodePtr>::iterator it(sPtr.begin()),it_end(sPtr.end()); while(it != it_end) { //create contracted gaussian GTOType gset(L,Normalized); //read the radfunc's of basisGroup gset.putBasisGroup((*it).second); //convert to a radial functor Transform2GridFunctor<GTOType,RadialOrbitalType> transform(gset, radorb); transform.generate(myGrid.rmin(),myGrid.rmax(),myGrid.size()); //optimize it with the radial functor Any2Slater gto2slater(radorb); gto2slater.optimize(); ++it; } sPtr.clear(); }
/** return log(|psi|) * * PhaseValue is the phase for the complex wave function */ TrialWaveFunction::RealType TrialWaveFunction::evaluateLogOnly(ParticleSet& P) { //TAU_PROFILE("TrialWaveFunction::evaluateLogOnly","ParticleSet& P", TAU_USER); tempP->R=P.R; tempP->L=0.0; tempP->G=0.0; ValueType logpsi(0.0); PhaseValue=0.0; vector<OrbitalBase*>::iterator it(Z.begin()); vector<OrbitalBase*>::iterator it_end(Z.end()); //WARNING: multiplication for PhaseValue is not correct, fix this!! for (; it!=it_end; ++it) { logpsi += (*it)->evaluateLog(*tempP, tempP->G, tempP->L); PhaseValue += (*it)->PhaseValue; } convert(logpsi,LogValue); return LogValue; //return LogValue=real(logpsi); }
int WalkerControlBase::doNotBranch(int iter, MCWalkerConfiguration& W) { MCWalkerConfiguration::iterator it(W.begin()); MCWalkerConfiguration::iterator it_end(W.end()); RealType esum=0.0,e2sum=0.0,wsum=0.0,ecum=0.0, w2sum=0.0; RealType r2_accepted=0.0,r2_proposed=0.0; for(; it!=it_end; ++it) { r2_accepted+=(*it)->Properties(R2ACCEPTED); r2_proposed+=(*it)->Properties(R2PROPOSED); RealType e((*it)->Properties(LOCALENERGY)); int nc= std::min(static_cast<int>((*it)->Multiplicity),MaxCopy); RealType wgt((*it)->Weight); esum += wgt*e; e2sum += wgt*e*e; wsum += wgt; w2sum += wgt*wgt; ecum += e; } //temp is an array to perform reduction operations std::fill(curData.begin(),curData.end(),0); curData[ENERGY_INDEX]=esum; curData[ENERGY_SQ_INDEX]=e2sum; curData[WALKERSIZE_INDEX]=W.getActiveWalkers(); curData[WEIGHT_INDEX]=wsum; curData[EREF_INDEX]=ecum; curData[R2ACCEPTED_INDEX]=r2_accepted; curData[R2PROPOSED_INDEX]=r2_proposed; myComm->allreduce(curData); measureProperties(iter); trialEnergy=EnsembleProperty.Energy; W.EnsembleProperty=EnsembleProperty; //return the current data return W.getGlobalNumWalkers(); }
//------------------------------------------------------------------------------ void Background2D::load( const size_t tile_index, const QGears::AnimationMap& animations ) { QGears::AnimationMap::const_iterator it( animations.begin() ); QGears::AnimationMap::const_iterator it_end( animations.end() ); while( it != it_end ) { const QGears::String& name( it->first ); const QGears::Animation& animation( it->second ); Background2DAnimation* anim( new Background2DAnimation( name, this, tile_index ) ); anim->SetLength( animation.length ); QGears::KeyFrameList::const_iterator itk( animation.key_frames.begin() ); QGears::KeyFrameList::const_iterator itk_end( animation.key_frames.end() ); while( itk != itk_end ) { anim->AddUVKeyFrame( *(itk++) ); } AddAnimation( anim ); ++it; } }
//-------------------------------------------------------------------------------------------------------------- void ImplAlignmentVector::moveAlignment( Position row_offset, Position col_offset) { debug_func_cerr(5); if (isEmpty()) return; if (row_offset + mRowFrom < 0 ) throw AlignlibException( "moving alignment out of bounds in row"); if (col_offset + mColFrom < 0 ) throw AlignlibException( "moving alignment out of bounds in col"); // create copy of mPairs (= copy of pointers) PAIRVECTOR copy(mPairs); PairIterator it(copy.begin()), it_end(copy.end()); size_t needed_size = std::max( mPairs.size(), (size_t)mRowTo + row_offset ); // delete old alignment and allocate needed size mPairs.clear(); mPairs.resize( needed_size, ResiduePair() ); // copy pointers from copy into mPairs for (; it != it_end; ++it) { ResiduePair & p(*it); if (p.mRow != NO_POS) { p.mRow += row_offset; p.mCol += col_offset; mPairs[p.mRow] = p; } } // set new alignment coordinates mRowFrom += row_offset; mRowTo += row_offset; mColFrom += col_offset; mColTo += col_offset; }
int numDirectories(const std::string& path) { // ROS_INFO_STREAM("cnt of path "<<path); int cnt = 0; boost::filesystem::path _path(path); boost::filesystem::path::iterator it(_path.begin()); boost::filesystem::path::iterator it_end(_path.end()); for (; it != it_end; ++it) { // ROS_INFO_STREAM(it->string()); // if (it->string()==".") continue; // because "./" leads to a count of 1 too but should be 0 ++cnt; } if (cnt > 0) { // count is always one more, as last directory // is either '.', or it is a file which doesn't count --cnt; } // ROS_INFO_STREAM("Res: "<<cnt); return cnt; }
TrialWaveFunction::RealType TrialWaveFunction::updateBuffer(ParticleSet& P, PooledData<RealType>& buf, bool fromscratch) { P.G = 0.0; P.L = 0.0; ValueType logpsi(0.0); PhaseValue=0.0; vector<OrbitalBase*>::iterator it(Z.begin()); vector<OrbitalBase*>::iterator it_end(Z.end()); for(int ii=1; it!=it_end; ++it,ii+=TIMER_SKIP) { myTimers[ii]->start(); logpsi += (*it)->updateBuffer(P,buf,fromscratch); PhaseValue += (*it)->PhaseValue; myTimers[ii]->stop(); } LogValue=real(logpsi); buf.put(&(P.G[0][0]), &(P.G[0][0])+TotalDim); buf.put(&(P.L[0]), &(P.L[0])+NumPtcls); return LogValue; }
//------------------------------------------------------------------------- static PyObject *meminfo_vec_t_to_py(meminfo_vec_t &areas) { PYW_GIL_CHECK_LOCKED_SCOPE(); PyObject *py_list = PyList_New(areas.size()); meminfo_vec_t::const_iterator it, it_end(areas.end()); Py_ssize_t i = 0; for ( it=areas.begin(); it!=it_end; ++it, ++i ) { const memory_info_t &mi = *it; // startEA endEA name sclass sbase bitness perm PyList_SetItem(py_list, i, Py_BuildValue("("PY_FMT64 PY_FMT64 "ss" PY_FMT64 "II)", pyul_t(mi.startEA), pyul_t(mi.endEA), mi.name.c_str(), mi.sclass.c_str(), pyul_t(mi.sbase), (unsigned int)(mi.bitness), (unsigned int)mi.perm)); } return py_list; }
//------------------------------------------------------------------------- Ogre::DataStreamPtr LGPArchive::open( const String& filename, bool readOnly ) const { LOG_DEBUG( "file:" + filename + " readOnly: " + Ogre::StringConverter::toString(readOnly) ); Ogre::MemoryDataStream* buffer( nullptr ); if( !m_lgp_file.isNull() ) { FileList::const_iterator it( m_files.begin() ); FileList::const_iterator it_end( m_files.end() ); while( it != it_end ) { if( it->file_name == filename ) { m_lgp_file->seek( it->data_offset ); size_t length( it->data_size ); buffer = new Ogre::MemoryDataStream( length ); m_lgp_file->read( buffer->getPtr(), length ); break; } ++it; } } return Ogre::DataStreamPtr( buffer ); }
///Randomly rotate sgrid_m void NonLocalECPComponent::randomize_grid(ParticleSet::ParticlePos_t& sphere, bool randomize) { if(randomize) { //const RealType twopi(6.28318530718); //RealType phi(twopi*Random()),psi(twopi*Random()),cth(Random()-0.5), RealType phi(TWOPI*((*myRNG)())), psi(TWOPI*((*myRNG)())), cth(((*myRNG)())-0.5); RealType sph(std::sin(phi)),cph(std::cos(phi)), sth(std::sqrt(1.0-cth*cth)),sps(std::sin(psi)), cps(std::cos(psi)); TensorType rmat( cph*cth*cps-sph*sps, sph*cth*cps+cph*sps,-sth*cps, -cph*cth*sps-sph*cps,-sph*cth*sps+cph*cps, sth*sps, cph*sth, sph*sth, cth ); SpherGridType::iterator it(sgridxyz_m.begin()); SpherGridType::iterator it_end(sgridxyz_m.end()); SpherGridType::iterator jt(rrotsgrid_m.begin()); int ic=0; while(it != it_end) {*jt = dot(rmat,*it); ++it; ++jt;} //copy the radomized grid to sphere std::copy(rrotsgrid_m.begin(), rrotsgrid_m.end(), sphere.begin()); } else { //copy sphere to the radomized grid std::copy(sphere.begin(), sphere.end(), rrotsgrid_m.begin()); } }
//------------------------------------------------------------------------- Ogre::FileInfoListPtr LGPArchive::findFileInfo( const String& pattern, bool recursive, bool dirs ) const { LOG_DEBUG( pattern ); //OGRE_LOCK_AUTO_MUTEX Ogre::FileInfoList* file_infos( OGRE_NEW_T( Ogre::FileInfoList, Ogre::MEMCATEGORY_GENERAL)() ); // If pattern contains a directory name, do a full match bool full_match = (pattern.find ('/') != String::npos) || (pattern.find ('\\') != String::npos); Ogre::FileInfoList::const_iterator it( m_file_infos.begin() ), it_end( m_file_infos.end() ); while( it != it_end ) { const String& file_name( full_match ? it->filename : it->basename ); if ( StringUtil::match( file_name, pattern, isCaseSensitive() ) ) { file_infos->push_back( *it ); } ++it; } return Ogre::FileInfoListPtr( file_infos, Ogre::SPFM_DELETE_T ); }
TrialWaveFunction::RealType TrialWaveFunction::updateBuffer(ParticleSet& P , PooledData<RealType>& buf, bool fromscratch) { //TAU_PROFILE("TrialWaveFunction::updateBuffer","(P,..)", TAU_USER); P.G = 0.0; P.L = 0.0; buf.rewind(BufferCursor); ValueType logpsi(0.0); PhaseValue=0.0; vector<OrbitalBase*>::iterator it(Z.begin()); vector<OrbitalBase*>::iterator it_end(Z.end()); for (; it!=it_end; ++it) { logpsi += (*it)->updateBuffer(P,buf,fromscratch); PhaseValue += (*it)->PhaseValue; } convert(logpsi,LogValue); //LogValue=real(logpsi); buf.put(PhaseValue); buf.put(LogValue); buf.put(&(P.G[0][0]), &(P.G[0][0])+TotalDim); buf.put(&(P.L[0]), &(P.L[0])+NumPtcls); return LogValue; }
/** Perform the correlated sampling algorthim. */ QMCCostFunctionSingle::Return_t QMCCostFunctionSingle::correlatedSampling() { typedef MCWalkerConfiguration::Walker_t Walker_t; MCWalkerConfiguration::iterator it(W.begin()); MCWalkerConfiguration::iterator it_end(W.end()); Return_t eloc_new; int iw=0; int totalElements=W.getTotalNum()*OHMMS_DIM; Return_t wgt_tot=0.0; while(it != it_end) { Walker_t& thisWalker(**it); Return_t* restrict saved = Records[iw]; //rewind the buffer to get the data from buffer thisWalker.DataSet.rewind(); //W is updated by thisWalker W.copyFromBuffer(thisWalker.DataSet); Return_t logpsi=0.0; //copy dL from Buffer #if defined(QMC_COMPLEX) thisWalker.DataSet.get(&(dG[0][0]),&(dG[0][0])+totalElements); thisWalker.DataSet.get(dL.begin(),dL.end()); logpsi=Psi.evaluateDeltaLog(W); W.G += dG; #else thisWalker.DataSet.get(dL.begin(),dL.end()); logpsi=Psi.evaluateDeltaLog(W); W.G += thisWalker.Drift; #endif W.L += dL; eloc_new=H_KE.evaluate(W)+saved[ENERGY_FIXED]; Return_t weight = UseWeight?std::exp(2.0*(logpsi-saved[LOGPSI_FREE])):1.0; saved[ENERGY_NEW]=eloc_new; saved[REWEIGHT]=weight; wgt_tot+=weight; ++it; ++iw; } //collect the total weight for normalization and apply maximum weight myComm->allreduce(wgt_tot); for(int i=0; i<SumValue.size(); i++) SumValue[i]=0.0; wgt_tot=1.0/wgt_tot; Return_t wgt_max=MaxWeight*wgt_tot; int nw=W.getActiveWalkers(); for(iw=0; iw<nw;iw++) { Return_t* restrict saved = Records[iw]; Return_t weight=saved[REWEIGHT]*wgt_tot; Return_t eloc_new=saved[ENERGY_NEW]; weight = (weight>wgt_max)? wgt_max:weight; Return_t delE=std::pow(abs(eloc_new-EtargetEff),PowerE); SumValue[SUM_E_BARE] += eloc_new; SumValue[SUM_ESQ_BARE] += eloc_new*eloc_new; SumValue[SUM_ABSE_BARE] += delE; SumValue[SUM_E_WGT] += eloc_new*weight; SumValue[SUM_ESQ_WGT] += eloc_new*eloc_new*weight; SumValue[SUM_ABSE_WGT] += delE*weight; SumValue[SUM_WGT] += weight; SumValue[SUM_WGTSQ] += weight*weight; } //collect everything myComm->allreduce(SumValue); return SumValue[SUM_WGT]*SumValue[SUM_WGT]/SumValue[SUM_WGTSQ]; }
/** evaluate everything before optimization */ void QMCCostFunctionSingle::checkConfigurations() { dG.resize(W.getTotalNum()); dL.resize(W.getTotalNum()); int numLocWalkers=W.getActiveWalkers(); Records.resize(numLocWalkers,6); typedef MCWalkerConfiguration::Walker_t Walker_t; MCWalkerConfiguration::iterator it(W.begin()); MCWalkerConfiguration::iterator it_end(W.end()); int nat = W.getTotalNum(); int iw=0; int totalElements=W.getTotalNum()*OHMMS_DIM; Etarget=0.0; Return_t e2sum=0.0; while(it != it_end) { Walker_t& thisWalker(**it); //clean-up DataSet to save re-used values thisWalker.DataSet.clear(); //rewind the counter thisWalker.DataSet.rewind(); //MCWalkerConfiguraton::registerData add distance-table data W.registerData(thisWalker,thisWalker.DataSet); Return_t* saved=Records[iw]; #if defined(QMC_COMPLEX) app_error() << " Optimization is not working with complex wavefunctions yet" << endl; app_error() << " Needs to fix TrialWaveFunction::evaluateDeltaLog " << endl; Psi.evaluateDeltaLog(W, saved[LOGPSI_FIXED], saved[LOGPSI_FREE], dG, dL); thisWalker.DataSet.add(&(dG[0][0]),&(dG[0][0])+totalElements); #else Psi.evaluateDeltaLog(W, saved[LOGPSI_FIXED], saved[LOGPSI_FREE], thisWalker.Drift, dL); #endif thisWalker.DataSet.add(dL.first_address(),dL.last_address()); Return_t e=H.evaluate(W); e2sum += e*e; Etarget += saved[ENERGY_TOT] = e; saved[ENERGY_FIXED] = H.getLocalPotential(); ++it; ++iw; } //Need to sum over the processors vector<Return_t> etemp(3); etemp[0]=Etarget; etemp[1]=static_cast<Return_t>(numLocWalkers); etemp[2]=e2sum; myComm->allreduce(etemp); Etarget = static_cast<Return_t>(etemp[0]/etemp[1]); NumSamples = static_cast<int>(etemp[1]); app_log() << " VMC Eavg = " << Etarget << endl; app_log() << " VMC Evar = " << etemp[2]/etemp[1]-Etarget*Etarget << endl; app_log() << " Total weights = " << etemp[1] << endl; setTargetEnergy(Etarget); ReportCounter=0; }
//------------------------------------------------------------------------------------------ void ImplProfile::add( const HAlignandum & source, const HAlignment & map_source2dest, bool is_reverse ) { debug_func_cerr(5); debug_cerr( 3, "adding to profile: is_reverse=" << is_reverse << " this=" << map_source2dest->getRowFrom() << "-" << map_source2dest->getRowTo() << " len=" << getFullLength() << " other=" << map_source2dest->getColFrom() << "-" << map_source2dest->getColTo() << " len=" << source->getFullLength() ); assert( source->getToolkit()->getEncoder()->getAlphabetSize() == getToolkit()->getEncoder()->getAlphabetSize()); if (is_reverse) { assert (map_source2dest->getColTo() <= source->getFullLength() ); assert (map_source2dest->getRowTo() <= getFullLength() ); } else { assert (map_source2dest->getRowTo() <= source->getFullLength() ); assert (map_source2dest->getColTo() <= getFullLength() ); } const HSequence sequence(toSequence( source )); if (sequence) { AlignmentIterator it(map_source2dest->begin()); AlignmentIterator it_end(map_source2dest->end()); if (is_reverse) { for (; it != it_end; ++it) { Position row = it->mCol; Position col = it->mRow; Residue i = sequence->asResidue(row); mWeightedCountMatrix->addValue(col,i,1); } } else { for (; it != it_end; ++it) { Position row = it->mRow; Position col = it->mCol; Residue i = sequence->asResidue(row); mWeightedCountMatrix->addValue(col,i,1); } } } else { const HProfile profile(toProfile(source)); if (profile) { AlignmentIterator it(map_source2dest->begin()); AlignmentIterator it_end(map_source2dest->end()); HWeightedCountMatrix m(profile->getWeightedCountMatrix()); if (is_reverse) { for (; it != it_end; ++it) { Position row = it->mCol; Position col = it->mRow; for (Residue i = 0; i < mProfileWidth; i++) mWeightedCountMatrix->addValue(col,i,(*m)[row][i]); } } else { for (; it != it_end; ++it) { Position row = it->mRow; Position col = it->mCol; for (Residue i = 0; i < mProfileWidth; i++) mWeightedCountMatrix->addValue(col,i,(*m)[row][i]); } } } else throw AlignlibException( "can not guess type of src - neither profile nor sequence"); } if (isPrepared()) { release(); // first release, otherwise it won't calculate anew prepare(); } }
/** evaluate curData and mark the bad/good walkers */ int WalkerControlBase::sortWalkers(MCWalkerConfiguration& W) { MCWalkerConfiguration::iterator it(W.begin()); vector<Walker_t*> bad,good_rn; vector<int> ncopy_rn; NumWalkers=0; MCWalkerConfiguration::iterator it_end(W.end()); RealType esum=0.0,e2sum=0.0,wsum=0.0,ecum=0.0, w2sum=0.0, besum=0.0, bwgtsum=0.0; RealType r2_accepted=0.0,r2_proposed=0.0; int nrn(0),ncr(0); while(it != it_end) { bool inFN=(((*it)->ReleasedNodeAge)==0); if ((*it)->ReleasedNodeAge==1) ncr+=1; int nc= std::min(static_cast<int>((*it)->Multiplicity),MaxCopy); r2_accepted+=(*it)->Properties(R2ACCEPTED); r2_proposed+=(*it)->Properties(R2PROPOSED); RealType e((*it)->Properties(LOCALENERGY)); RealType bfe((*it)->Properties(ALTERNATEENERGY)); RealType rnwgt(0.0); if (inFN) rnwgt=((*it)->Properties(SIGN)); // RealType wgt((*it)->Weight); RealType wgt(0.0); if (inFN) wgt=((*it)->Weight); esum += wgt*e; e2sum += wgt*e*e; wsum += wgt; w2sum += wgt*wgt; ecum += e; besum += bfe*rnwgt*wgt; bwgtsum += rnwgt*wgt; if((nc) && (inFN)) { NumWalkers += nc; good_w.push_back(*it); ncopy_w.push_back(nc-1); } else if (nc) { NumWalkers += nc; nrn+=nc; good_rn.push_back(*it); ncopy_rn.push_back(nc-1); } else { bad.push_back(*it); } ++it; } //temp is an array to perform reduction operations std::fill(curData.begin(),curData.end(),0); //update curData curData[ENERGY_INDEX]=esum; curData[ENERGY_SQ_INDEX]=e2sum; curData[WALKERSIZE_INDEX]=W.getActiveWalkers(); curData[WEIGHT_INDEX]=wsum; curData[EREF_INDEX]=ecum; curData[R2ACCEPTED_INDEX]=r2_accepted; curData[R2PROPOSED_INDEX]=r2_proposed; curData[FNSIZE_INDEX]=static_cast<RealType>(good_w.size()); curData[RNONESIZE_INDEX]=static_cast<RealType>(ncr); curData[RNSIZE_INDEX]=nrn; curData[B_ENERGY_INDEX]=besum; curData[B_WGT_INDEX]=bwgtsum; ////this should be move //W.EnsembleProperty.NumSamples=curData[WALKERSIZE_INDEX]; //W.EnsembleProperty.Weight=curData[WEIGHT_INDEX]; //W.EnsembleProperty.Energy=(esum/=wsum); //W.EnsembleProperty.Variance=(e2sum/wsum-esum*esum); //W.EnsembleProperty.Variance=(e2sum*wsum-esum*esum)/(wsum*wsum-w2sum); //remove bad walkers empty the container for(int i=0; i<bad.size(); i++) delete bad[i]; if (!WriteRN) { if(good_w.empty()) { app_error() << "All the walkers have died. Abort. " << endl; APP_ABORT("WalkerControlBase::sortWalkers"); } int sizeofgood = good_w.size(); //check if the projected number of walkers is too small or too large if(NumWalkers>Nmax) { int nsub=0; int nsub_target=(NumWalkers-nrn)-static_cast<int>(0.9*Nmax); int i=0; while(i< sizeofgood && nsub<nsub_target) { if(ncopy_w[i]) {ncopy_w[i]--; nsub++;} ++i; } NumWalkers -= nsub; } else if(NumWalkers < Nmin) { int nadd=0; int nadd_target = static_cast<int>(Nmin*1.1)-(NumWalkers-nrn); if(nadd_target> sizeofgood) { app_warning() << "The number of walkers is running low. Requested walkers " << nadd_target << " good walkers = " << sizeofgood << endl; } int i=0; while(i< sizeofgood && nadd<nadd_target) { ncopy_w[i]++; ++nadd;++i; } NumWalkers += nadd; } } else { it=good_rn.begin(); it_end=good_rn.end(); int indy(0); while(it!=it_end) { good_w.push_back(*it); ncopy_w.push_back(ncopy_rn[indy]); it++,indy++; } } return NumWalkers; }
int WalkerControlBase::doNotBranch(int iter, MCWalkerConfiguration& W) { MCWalkerConfiguration::iterator it(W.begin()); MCWalkerConfiguration::iterator it_end(W.end()); RealType esum=0.0,e2sum=0.0,wsum=0.0,ecum=0.0, w2sum=0.0, besum=0.0, bwgtsum=0.0; RealType r2_accepted=0.0,r2_proposed=0.0; int nrn(0),ncr(0),nfn(0),ngoodfn(0); for(; it!=it_end;++it) { bool inFN=(((*it)->ReleasedNodeAge)==0); int nc= std::min(static_cast<int>((*it)->Multiplicity),MaxCopy); if ((*it)->ReleasedNodeAge==1) ncr+=1; else if ((*it)->ReleasedNodeAge==0) { nfn+=1; ngoodfn+=nc; } r2_accepted+=(*it)->Properties(R2ACCEPTED); r2_proposed+=(*it)->Properties(R2PROPOSED); RealType e((*it)->Properties(LOCALENERGY)); RealType bfe((*it)->Properties(ALTERNATEENERGY)); RealType rnwgt(0.0); if (inFN) rnwgt=((*it)->Properties(SIGN)); else nrn+=nc; // RealType wgt((*it)->Weight); RealType wgt(0.0); if (inFN) wgt=((*it)->Weight); esum += wgt*e; e2sum += wgt*e*e; wsum += wgt; w2sum += wgt*wgt; ecum += e; besum += bfe*rnwgt*wgt; bwgtsum += rnwgt*wgt; } //temp is an array to perform reduction operations std::fill(curData.begin(),curData.end(),0); curData[ENERGY_INDEX]=esum; curData[ENERGY_SQ_INDEX]=e2sum; curData[WALKERSIZE_INDEX]=W.getActiveWalkers(); curData[WEIGHT_INDEX]=wsum; curData[EREF_INDEX]=ecum; curData[R2ACCEPTED_INDEX]=r2_accepted; curData[R2PROPOSED_INDEX]=r2_proposed; curData[FNSIZE_INDEX]=static_cast<RealType>(nfn); curData[RNONESIZE_INDEX]=static_cast<RealType>(ncr); curData[RNSIZE_INDEX]=nrn; curData[B_ENERGY_INDEX]=besum; curData[B_WGT_INDEX]=bwgtsum; myComm->allreduce(curData); measureProperties(iter); trialEnergy=EnsembleProperty.Energy; W.EnsembleProperty=EnsembleProperty; return W.getActiveWalkers(); }
GridMolecularOrbitals::BasisSetType* GridMolecularOrbitals::addBasisSet(xmlNodePtr cur) { if(!BasisSet) BasisSet = new BasisSetType(IonSys.getSpeciesSet().getTotalNum()); QuantumNumberType nlms; string rnl; //current number of centers int ncenters = CenterID.size(); int activeCenter; int gridmode = -1; bool addsignforM = false; string sph("default"), Morder("gaussian"); //go thru the tree cur = cur->xmlChildrenNode; map<string,RGFBuilderBase*> rbuilderlist; while(cur!=NULL) { string cname((const char*)(cur->name)); if(cname == basis_tag || cname == "atomicBasisSet") { int expandlm = GAUSSIAN_EXPAND; string abasis("invalid"), btype("Numerical"); //Register valid attributes attributes OhmmsAttributeSet aAttrib; aAttrib.add(abasis,"elementType"); aAttrib.add(abasis,"species"); aAttrib.add(btype,"type"); aAttrib.add(sph,"angular"); aAttrib.add(addsignforM,"expM"); aAttrib.add(Morder,"expandYlm"); aAttrib.put(cur); if(abasis == "invalid") continue; if(sph == "spherical") addsignforM=1; //include (-1)^m if(Morder == "gaussian") { expandlm = GAUSSIAN_EXPAND; } else if(Morder == "natural") { expandlm = NATURAL_EXPAND; } else if(Morder == "no") { expandlm = DONOT_EXPAND; } if(addsignforM) LOGMSG("Spherical Harmonics contain (-1)^m factor") else LOGMSG("Spherical Harmonics DO NOT contain (-1)^m factor") //search the species name map<string,int>::iterator it = CenterID.find(abasis); if(it == CenterID.end()) //add the name to the map CenterID { if(btype == "Numerical" || btype == "NG" || btype == "HFNG") { rbuilder = new NumericalRGFBuilder(cur); } else { rbuilder = new Any2GridBuilder(cur); } //CenterID[abasis] = activeCenter = ncenters++; CenterID[abasis]=activeCenter=IonSys.getSpeciesSet().findSpecies(abasis); int Lmax(0); //maxmimum angular momentum of this center int num(0);//the number of localized basis functions of this center //process the basic property: maximun angular momentum, the number of basis functions to be added vector<xmlNodePtr> radGroup; xmlNodePtr cur1 = cur->xmlChildrenNode; xmlNodePtr gptr=0; while(cur1 != NULL) { string cname1((const char*)(cur1->name)); if(cname1 == basisfunc_tag || cname1 == "basisGroup") { radGroup.push_back(cur1); int l=atoi((const char*)(xmlGetProp(cur1, (const xmlChar *)"l"))); Lmax = max(Lmax,l); //expect that only Rnl is given if(expandlm) num += 2*l+1; else num++; } else if(cname1 == "grid") { gptr = cur1; } cur1 = cur1->next; } XMLReport("Adding a center " << abasis << " centerid "<< CenterID[abasis]) XMLReport("Maximum angular momentum = " << Lmax) XMLReport("Number of centered orbitals = " << num) //create a new set of atomic orbitals sharing a center with (Lmax, num) //if(addsignforM) the basis function has (-1)^m sqrt(2)Re(Ylm) CenteredOrbitalType* aos = new CenteredOrbitalType(Lmax,addsignforM); aos->LM.resize(num); aos->NL.resize(num); //Now, add distinct Radial Orbitals and (l,m) channels num=0; rbuilder->setOrbitalSet(aos,abasis); //assign radial orbitals for the new center rbuilder->addGrid(gptr); //assign a radial grid for the new center vector<xmlNodePtr>::iterator it(radGroup.begin()); vector<xmlNodePtr>::iterator it_end(radGroup.end()); while(it != it_end) { cur1 = (*it); xmlAttrPtr att = cur1->properties; while(att != NULL) { string aname((const char*)(att->name)); if(aname == "rid" || aname == "id") //accept id/rid { rnl = (const char*)(att->children->content); } else { map<string,int>::iterator iit = nlms_id.find(aname); if(iit != nlms_id.end()) //valid for n,l,m,s { nlms[(*iit).second] = atoi((const char*)(att->children->content)); } } att = att->next; } XMLReport("\n(n,l,m,s) " << nlms[0] << " " << nlms[1] << " " << nlms[2] << " " << nlms[3]) //add Ylm channels num = expandYlm(rnl,nlms,num,aos,cur1,expandlm); ++it; } //add the new atomic basis to the basis set BasisSet->add(aos,activeCenter); #if !defined(HAVE_MPI) rbuilder->print(abasis,1); #endif if(rbuilder) { delete rbuilder; rbuilder=0; } } else { WARNMSG("Species " << abasis << " is already initialized. Ignore the input.") } } cur = cur->next; }
void BaseD::check_paths_and_reload(char **paths/*=g_cfg.playlist*/, int numpaths/*=g_cfg.num_files*/, bool is_drop_event/*=false*/) { struct { std::string cmd[2] = { UNRAR_TOOLNAME "\" e -y \"", DEC7Z_TOOLNAME "\" e \""}; unsigned index=0; const char * str() { return cmd[index].c_str(); } } extract_cmd; bool rsn_found=false; // Check here if path is RSN for (size_t i=0; i < numpaths; i++) { char *path = paths[i]; char *ext; char *name; ext = strrchr(path, '.'); name = strrchr(path, '\\'); // Windows if (!name) name = strrchr( path, '/' ); // UNIX //assert(name); if (!name) name = path; else { name += 1; // move past '/' character } if (!strcmp(ext, ".rsn") || !strcmp(ext, ".rar") || !strcmp(ext, ".7z")) { rsn_found = true; // not actually used fprintf(stderr, "rsn || 7z found\n"); char *mkdir_cmd = (char*) SDL_malloc(sizeof(char) * (strlen(MKDIR_CMD)+ strlen(File_System_Context::file_system->tmp_path_quoted)+((ext-name+1)+1+5)) ); char *dir_quoted = (char*) SDL_malloc(sizeof(char) * (strlen(File_System_Context::file_system->tmp_path_quoted)+((ext-name+1)+2+5)) ); strcpy(mkdir_cmd, MKDIR_CMD); char *dirp = mkdir_cmd + strlen(MKDIR_CMD); char *sp = mkdir_cmd + strlen(MKDIR_CMD); strcpy(sp, File_System_Context::file_system->tmp_path_quoted); sp += strlen(File_System_Context::file_system->tmp_path_quoted) - 1; // folderp is the game folder inside the tmp dir for (char *folderp = name; folderp != ext; folderp++) { *(sp++) = *folderp; } *(sp++) = PATH_SEP; *(sp++) = '"'; *sp = 0; strcpy (dir_quoted, dirp); //strcat(dir_quoted, "/"); fprintf(stderr, "data_path_quoted = '%s'\n", File_System_Context::file_system->data_path_quoted); fprintf(stderr, "tmp_path_quoted = '%s'\n", File_System_Context::file_system->tmp_path_quoted); fprintf(stderr, "mkdircmd = '%s'\n", mkdir_cmd); fprintf(stderr, "dir = %s\n", dir_quoted); #ifdef _WIN32 fflush(NULL); #endif system(mkdir_cmd); if (!strcmp(ext, ".rsn") || !strcmp(ext, ".rar")) { extract_cmd.index = 0; } else if (!strcmp(ext, ".7z")) { extract_cmd.index = 1; } // data_path_quoted + "unrar e " + path + " " + dir_quoted char *full_extract_cmd = (char*) SDL_malloc(sizeof(char) * ( strlen(File_System_Context::file_system->data_path_quoted) + strlen(extract_cmd.str()) + 3 + strlen(path) + 2 + strlen(dir_quoted) + 1 +10 )); #ifdef _WIN32 full_extract_cmd[0] = '"'; strcpy(full_extract_cmd + 1, File_System_Context::file_system->data_path_quoted); #else strcpy(full_extract_cmd, File_System_Context::file_system->data_path_quoted); #endif full_extract_cmd[strlen(full_extract_cmd)-1] = 0; strcat(full_extract_cmd, extract_cmd.str()); strcat(full_extract_cmd, path); strcat(full_extract_cmd, "\" "); strcat(full_extract_cmd, dir_quoted); // int i = strlen(full_extract_cmd); // full_extract_cmd[i++] = '"'; // full_extract_cmd[i++] = 0; fprintf(stderr, "full_extract_cmd = '%s'\n", full_extract_cmd); #ifdef _WIN32 fflush(NULL); #endif system(full_extract_cmd); SDL_free(full_extract_cmd); FILE *fp; int status; char spc_path[PATH_MAX]; //int count=0; int old_nfd_rsn_spc_path_pos=BaseD::nfd.num_rsn_spc_paths; // count how many paths!! // ls *.spc char *dir_unquoted = &dir_quoted[1]; dir_quoted[strlen(dir_quoted)-1] = 0; typedef std::vector<boost::filesystem::path> vec; vec v; boost::filesystem::path p(dir_unquoted); get_file_list_ext(p, ".spc", v); sort(v.begin(), v.end()); // sort, since directory iteration // is not ordered on some file systems BaseD::nfd.num_rsn_spc_paths += v.size(); BaseD::nfd.rsn_spc_paths=(char**)SDL_realloc( BaseD::nfd.rsn_spc_paths, sizeof(char*) * (BaseD::nfd.num_rsn_spc_paths+1)); if (BaseD::nfd.rsn_spc_paths == NULL) { perror ("realloc"); break; } for (vec::const_iterator it(v.begin()), it_end(v.end()); it != it_end; ++it) { std::cout << "woot" << std::endl; std::string spc_path = dir_unquoted + it->string(); BaseD::nfd.rsn_spc_paths[old_nfd_rsn_spc_path_pos] = (char*) SDL_calloc(spc_path.length()+3, sizeof(char)); strcpy(BaseD::nfd.rsn_spc_paths[old_nfd_rsn_spc_path_pos], spc_path.c_str()); old_nfd_rsn_spc_path_pos++; } //SDL_free(ls_cmd); SDL_free(mkdir_cmd); SDL_free(dir_quoted); } else { char **tmp; if ( (tmp=(char**)SDL_realloc(BaseD::nfd.rsn_spc_paths, sizeof(char*) * (BaseD::nfd.num_rsn_spc_paths+1))) == NULL) { perror ("realloc"); break; } BaseD::nfd.rsn_spc_paths = tmp; BaseD::nfd.rsn_spc_paths[BaseD::nfd.num_rsn_spc_paths] = (char*) SDL_calloc(strlen(path)+3, sizeof(char)); //strcpy(BaseD::nfd.rsn_spc_paths[BaseD::nfd.num_rsn_spc_paths], "\""); strcpy(BaseD::nfd.rsn_spc_paths[BaseD::nfd.num_rsn_spc_paths], path); //strcat(BaseD::nfd.rsn_spc_paths[BaseD::nfd.num_rsn_spc_paths], "\""); //fprintf(stderr, "path = %s\n", BaseD::nfd.rsn_spc_paths[BaseD::nfd.num_rsn_spc_paths]); BaseD::nfd.num_rsn_spc_paths++; } } BaseD::reload(BaseD::nfd.rsn_spc_paths,BaseD::nfd.num_rsn_spc_paths); }
void indel_digt_caller:: get_indel_digt_lhood(const starling_options& opt, const starling_deriv_options& dopt, const starling_sample_options& sample_opt, const double indel_error_prob, const double ref_error_prob, const indel_key& ik, const indel_data& id, const bool is_het_bias, const double het_bias, const bool is_tier2_pass, const bool is_use_alt_indel, double* const lhood) { static const double loghalf(-std::log(2.)); for (unsigned gt(0); gt<STAR_DIINDEL::SIZE; ++gt) lhood[gt] = 0.; const bool is_breakpoint(ik.is_breakpoint()); const double indel_error_lnp(std::log(indel_error_prob)); const double indel_real_lnp(std::log(1.-indel_error_prob)); const double ref_error_lnp(std::log(ref_error_prob)); const double ref_real_lnp(std::log(1.-ref_error_prob)); // typedef read_path_scores::alt_indel_t::const_iterator aiter; typedef indel_data::score_t::const_iterator siter; siter it(id.read_path_lnp.begin()), it_end(id.read_path_lnp.end()); for (; it!=it_end; ++it) { const read_path_scores& path_lnp(it->second); // optionally skip tier2 data: if ((! is_tier2_pass) && (! path_lnp.is_tier1_read)) continue; // get alt path lnp: double alt_path_lnp(path_lnp.ref); #if 0 if (is_use_alt_indel && path_lnp.is_alt && (path_lnp.alt > alt_path_lnp)) { alt_path_lnp=path_lnp.alt; } #else if (is_use_alt_indel and (not path_lnp.alt_indel.empty()) ) { typedef read_path_scores::alt_indel_t::const_iterator aiter; aiter j(path_lnp.alt_indel.begin()), j_end(path_lnp.alt_indel.end()); for (; j!=j_end; ++j) { if (j->second>alt_path_lnp) alt_path_lnp=j->second; } } #endif const double noindel_lnp(log_sum(alt_path_lnp+ref_real_lnp,path_lnp.indel+indel_error_lnp)); const double hom_lnp(log_sum(alt_path_lnp+ref_error_lnp,path_lnp.indel+indel_real_lnp)); // allele ratio convention is that the indel occurs at the // het_allele ratio and the alternate allele occurs at // (1-het_allele_ratio): double log_ref_prob(loghalf); double log_indel_prob(loghalf); if (not is_breakpoint) { static const double het_allele_ratio(0.5); get_het_observed_allele_ratio(path_lnp.read_length,sample_opt.min_read_bp_flank, ik,het_allele_ratio,log_ref_prob,log_indel_prob); } const double het_lnp(log_sum(noindel_lnp+log_ref_prob,hom_lnp+log_indel_prob)); lhood[STAR_DIINDEL::NOINDEL] += integrate_out_sites(dopt,path_lnp.nsite,noindel_lnp,is_tier2_pass); lhood[STAR_DIINDEL::HOM] += integrate_out_sites(dopt,path_lnp.nsite,hom_lnp,is_tier2_pass); lhood[STAR_DIINDEL::HET] += integrate_out_sites(dopt,path_lnp.nsite,het_lnp,is_tier2_pass); #ifdef DEBUG_INDEL_CALL //log_os << std::setprecision(8); //log_os << "INDEL_CALL i,ref_lnp,indel_lnp,lhood(noindel),lhood(hom),lhood(het): " << i << " " << path_lnp.ref << " " << path_lnp.indel << " " << lhood[STAR_DIINDEL::NOINDEL] << " " << lhood[STAR_DIINDEL::HOM] << " " << lhood[STAR_DIINDEL::HET] << "\n"; #endif } if (is_het_bias) { // loop is currently setup to assume a uniform het ratio subgenotype prior const unsigned n_bias_steps(1+static_cast<unsigned>(het_bias/opt.het_bias_max_ratio_inc)); const double ratio_increment(het_bias/static_cast<double>(n_bias_steps)); for (unsigned step(0); step<n_bias_steps; ++step) { const double het_ratio(0.5+(step+1)*ratio_increment); increment_het_ratio_lhood(opt,dopt,sample_opt, indel_error_lnp,indel_real_lnp, ref_error_lnp,ref_real_lnp, ik,id,het_ratio,is_tier2_pass,is_use_alt_indel,lhood); } const unsigned n_het_subgt(1+2*n_bias_steps); const double subgt_log_prior(std::log(static_cast<double>(n_het_subgt))); lhood[STAR_DIINDEL::HET] -= subgt_log_prior; } }
void VMCParticleByParticle::runBlockWithoutDrift() { IndexType step = 0; MCWalkerConfiguration::iterator it_end(W.end()); do { //advanceWalkerByWalker(); MCWalkerConfiguration::iterator it(W.begin()); while(it != it_end) { //MCWalkerConfiguration::WalkerData_t& w_buffer = *(W.DataSet[iwalker]); Walker_t& thisWalker(**it); Buffer_t& w_buffer(thisWalker.DataSet); W.R = thisWalker.R; w_buffer.rewind(); W.copyFromBuffer(w_buffer); Psi.copyFromBuffer(W,w_buffer); RealType psi_old = thisWalker.Properties(SIGN); RealType psi = psi_old; for(int iter=0; iter<nSubSteps; iter++) { makeGaussRandom(deltaR); bool stucked=true; for(int iat=0; iat<W.getTotalNum(); iat++) { PosType dr = m_sqrttau*deltaR[iat]; PosType newpos = W.makeMove(iat,dr); RealType ratio = Psi.ratio(W,iat); //RealType ratio = Psi.ratio(W,iat,dG,dL); RealType prob = std::min(1.0e0,ratio*ratio); //alternatively if(Random() < prob) { stucked=false; ++nAccept; W.acceptMove(iat); Psi.acceptMove(W,iat); //W.G+=dG; //W.L+=dL; } else { ++nReject; W.rejectMove(iat); Psi.rejectMove(iat); } } if(stucked) { ++nAllRejected; } } thisWalker.R = W.R; w_buffer.rewind(); W.updateBuffer(w_buffer); RealType logpsi = Psi.updateBuffer(W,w_buffer); //W.copyToBuffer(w_buffer); //RealType logpsi = Psi.evaluate(W,w_buffer); RealType eloc=H.evaluate(W); thisWalker.resetProperty(logpsi,Psi.getPhase(),eloc); H.saveProperty(thisWalker.getPropertyBase()); ++it; } ++step;++CurrentStep; Estimators->accumulate(W); } while(step<nSteps); }
void VMCParticleByParticle::runBlockWithDrift() { IndexType step = 0; MCWalkerConfiguration::iterator it_end(W.end()); do { //advanceWalkerByWalker(); MCWalkerConfiguration::iterator it(W.begin()); while(it != it_end) { //MCWalkerConfiguration::WalkerData_t& w_buffer = *(W.DataSet[iwalker]); Walker_t& thisWalker(**it); Buffer_t& w_buffer(thisWalker.DataSet); W.R = thisWalker.R; w_buffer.rewind(); W.copyFromBuffer(w_buffer); Psi.copyFromBuffer(W,w_buffer); RealType psi_old = thisWalker.Properties(SIGN); RealType psi = psi_old; //create a 3N-Dimensional Gaussian with variance=1 makeGaussRandom(deltaR); bool moved = false; for(int iat=0; iat<W.getTotalNum(); iat++) { PosType dr = m_sqrttau*deltaR[iat]+thisWalker.Drift[iat]; PosType newpos = W.makeMove(iat,dr); //RealType ratio = Psi.ratio(W,iat); RealType ratio = Psi.ratio(W,iat,dG,dL); G = W.G+dG; //RealType forwardGF = exp(-0.5*dot(deltaR[iat],deltaR[iat])); //dr = (*it)->R[iat]-newpos-Tau*G[iat]; //RealType backwardGF = exp(-oneover2tau*dot(dr,dr)); RealType logGf = -0.5e0*dot(deltaR[iat],deltaR[iat]); RealType scale=getDriftScale(Tau,G); //COMPLEX WARNING //dr = thisWalker.R[iat]-newpos-scale*G[iat]; dr = thisWalker.R[iat]-newpos-scale*real(G[iat]); RealType logGb = -m_oneover2tau*dot(dr,dr); RealType prob = std::min(1.0e0,ratio*ratio*exp(logGb-logGf)); //alternatively if(Random() < prob) { moved = true; ++nAccept; W.acceptMove(iat); Psi.acceptMove(W,iat); W.G = G; W.L += dL; //thisWalker.Drift = scale*G; assignDrift(scale,G,thisWalker.Drift); } else { ++nReject; W.rejectMove(iat); Psi.rejectMove(iat); } } if(moved) { w_buffer.rewind(); W.copyToBuffer(w_buffer); psi = Psi.evaluate(W,w_buffer); thisWalker.R = W.R; RealType eloc=H.evaluate(W); thisWalker.resetProperty(log(abs(psi)), psi,eloc); H.saveProperty(thisWalker.getPropertyBase()); } else { ++nAllRejected; } ++it; } ++step;++CurrentStep; Estimators->accumulate(W); //if(CurrentStep%100 == 0) updateWalkers(); } while(step<nSteps); }
GTOMolecularOrbitals::BasisSetType* GTOMolecularOrbitals::addBasisSet(xmlNodePtr cur) { if(!BasisSet) BasisSet = new BasisSetType(IonSys.getSpeciesSet().getTotalNum()); QuantumNumberType nlms; string rnl; //current number of centers int ncenters = CenterID.size(); int activeCenter; int gridmode = -1; bool addsignforM = true; string sph("spherical"), Morder("gaussian"); //go thru the tree cur = cur->xmlChildrenNode; while(cur!=NULL) { string cname((const char*)(cur->name)); if(cname == basis_tag || cname == "atomicBasisSet") { int expandlm = GAUSSIAN_EXPAND; string abasis("invalid"), norm("no"); //Register valid attributes attributes OhmmsAttributeSet aAttrib; aAttrib.add(abasis,"elementType"); aAttrib.add(abasis,"species"); aAttrib.add(sph,"angular"); aAttrib.add(addsignforM,"expM"); aAttrib.add(Morder,"expandYlm"); aAttrib.add(norm,"normalized"); aAttrib.put(cur); if(norm == "yes") Normalized=true; else Normalized=false; if(abasis == "invalid") continue; if(sph == "spherical") addsignforM=true; //include (-1)^m if(sph == "cartesian") addsignforM=false; if(Morder == "gaussian") { expandlm = GAUSSIAN_EXPAND; } else if(Morder == "natural"){ expandlm = NATURAL_EXPAND; } else if(Morder == "no") { expandlm = DONOT_EXPAND; } if(addsignforM) LOGMSG("Spherical Harmonics contain (-1)^m factor") else LOGMSG("Spherical Harmonics DO NOT contain (-1)^m factor") map<string,int>::iterator it = CenterID.find(abasis); //search the species name if(it == CenterID.end()) {//add the name to the map CenterID //CenterID[abasis] = activeCenter = ncenters++; CenterID[abasis]=activeCenter=IonSys.getSpeciesSet().findSpecies(abasis); int Lmax(0); //maxmimum angular momentum of this center int num(0);//the number of localized basis functions of this center //process the basic property: maximun angular momentum, the number of basis functions to be added vector<xmlNodePtr> radGroup; xmlNodePtr cur1 = cur->xmlChildrenNode; xmlNodePtr gptr=0; while(cur1 != NULL) { string cname1((const char*)(cur1->name)); if(cname1 == basisfunc_tag || cname1 == "basisGroup") { radGroup.push_back(cur1); int l=atoi((const char*)(xmlGetProp(cur1, (const xmlChar *)"l"))); Lmax = max(Lmax,l); if(expandlm) num += 2*l+1; else num++; } cur1 = cur1->next; } LOGMSG("Adding a center " << abasis << " centerid "<< CenterID[abasis]) LOGMSG("Maximum angular momentum = " << Lmax) LOGMSG("Number of centered orbitals = " << num) //create a new set of atomic orbitals sharing a center with (Lmax, num) //if(addsignforM) the basis function has (-1)^m sqrt(2)Re(Ylm) CenteredOrbitalType* aos = new CenteredOrbitalType(Lmax,addsignforM); aos->LM.resize(num); aos->NL.resize(num); //Now, add distinct Radial Orbitals and (l,m) channels num=0; vector<xmlNodePtr>::iterator it(radGroup.begin()); vector<xmlNodePtr>::iterator it_end(radGroup.end()); while(it != it_end) { cur1 = (*it); xmlAttrPtr att = cur1->properties; while(att != NULL) { string aname((const char*)(att->name)); if(aname == "rid" || aname == "id") { //accept id/rid rnl = (const char*)(att->children->content); } else { map<string,int>::iterator iit = nlms_id.find(aname); if(iit != nlms_id.end()) { //valid for n,l,m,s nlms[(*iit).second] = atoi((const char*)(att->children->content)); } } att = att->next; } LOGMSG("\n(n,l,m,s) " << nlms[0] << " " << nlms[1] << " " << nlms[2] << " " << nlms[3]) //add Ylm channels num = expandYlm(rnl,nlms,num,aos,cur1,expandlm); ++it; } LOGMSG("Checking the order of angular momentum ") std::copy(aos->LM.begin(), aos->LM.end(), ostream_iterator<int>(app_log()," ")); app_log() << endl; //add the new atomic basis to the basis set BasisSet->add(aos,activeCenter); }else { WARNMSG("Species " << abasis << " is already initialized. Ignore the input.") } } cur = cur->next; }