QMCPACK
QMC Driver group

QMC drivers that implement QMC algorithms. More...

+ Collaboration diagram for QMC Driver group:

Classes

class  CSVMC
 
Implements the VMC algorithm using umbrella sampling. More...
 
class  CSVMCUpdateAll
 
Implements the VMC algorithm using umbrella sampling. More...
 
class  CSVMCUpdatePbyP
 
Implements the VMC algorithm More...
 
class  CSVMCUpdatePbyPWithDriftFast
 
Implements the VMC algorithm with drift. More...
 
class  DMC
 DMC driver using OpenMP paragra. More...
 
class  DMCBatched
 
Implements a DMC using particle-by-particle threaded and batched moves. More...
 
class  QMCDriver
 abstract base class for QMC engines More...
 
class  QMCDriverNew
 QMCDriverNew Base class for Unified Drivers. More...
 
class  RMC
 
Implements a RMC using threaded execution. More...
 
class  RMCUpdateAllWithDrift
 
Implements the RMC algorithm using all electron moves More...
 
class  RMCUpdatePbyPWithDrift
 
Implements the RMC algorithm using all electron moves More...
 
class  SOVMCUpdateAll
 
Implements the Spin VMC algorithm using particle-by-particle move. More...
 
class  SOVMCUpdatePbyP
 
Implements the VMC algorithm using particle-by-particle move, including spin-moves More...
 
class  VMC
 
Implements a VMC using particle-by-particle move. More...
 
class  VMCBatched
 
Implements a VMC using particle-by-particle move. More...
 
class  VMCUpdateAll
 
Implements the VMC algorithm using particle-by-particle move. More...
 
class  VMCUpdatePbyP
 
Implements the VMC algorithm using particle-by-particle move. More...
 
class  CostFunctionCrowdData
 Implements wave-function optimization. More...
 
class  QMCCostFunction
 Implements wave-function optimization. More...
 
class  QMCCostFunctionBase
 Implements wave-function optimization. More...
 
class  QMCFixedSampleLinearOptimize
 Implements wave-function optimization. More...
 

Detailed Description

QMC drivers that implement QMC algorithms.


Class Documentation

◆ qmcplusplus::CSVMC

class qmcplusplus::CSVMC


Implements the VMC algorithm using umbrella sampling.

Energy difference method with multiple H/Psi. Consult S. Chiesa's note.

Definition at line 34 of file CSVMC.h.

+ Inheritance diagram for CSVMC:
+ Collaboration diagram for CSVMC:

Public Member Functions

 CSVMC (const ProjectData &project_data, MCWalkerConfiguration &w, TrialWaveFunction &psi, QMCHamiltonian &h, Communicate *comm)
 Constructor. More...
 
bool run () override
 Run the CSVMC algorithm. More...
 
bool put (xmlNodePtr cur) override
 allocate internal data here before run() is called More...
 
QMCRunType getRunType () override
 
- Public Member Functions inherited from QMCDriver
 QMCDriver (const ProjectData &project_data, MCWalkerConfiguration &w, TrialWaveFunction &psi, QMCHamiltonian &h, Communicate *comm, const std::string &QMC_driver_type, bool enable_profiling=false)
 Constructor. More...
 
 ~QMCDriver () override
 
int current () const
 return current step More...
 
void setUpdateMode (bool pbyp) override
 set the update mode More...
 
void setStatus (const std::string &aname, const std::string &h5name, bool append) override
 Set the status of the QMCDriver. More...
 
void add_H_and_Psi (QMCHamiltonian *h, TrialWaveFunction *psi) override
 add QMCHamiltonian/TrialWaveFunction pair for multiple More...
 
void process (xmlNodePtr cur) override
 initialize with xmlNode More...
 
xmlNodePtr getQMCNode ()
 return a xmlnode with update More...
 
void putWalkers (std::vector< xmlNodePtr > &wset) override
 Read walker configurations from *.config.h5 files. More...
 
void putTraces (xmlNodePtr txml) override
 
void requestTraces (bool traces) override
 
void putWalkerLogs (xmlNodePtr wlxml) override
 
void requestWalkerLogs (bool allow_walker_logs_) override
 
std::string getEngineName () override
 
template<class PDT >
void setValue (const std::string &aname, PDT x)
 
void setBranchEngine (std::unique_ptr< BranchEngineType > &&be) override
 set the BranchEngineType More...
 
std::unique_ptr< BranchEngineTypegetBranchEngine () override
 return BranchEngineType* More...
 
int addObservable (const std::string &aname)
 
RealType getObservable (int i)
 
void setTau (RealType i)
 
void setWalkerOffsets ()
 set global offsets of the walkers More...
 
RefVector< RandomBase< FullPrecRealType > > getRngRefs () const
 return the random generators More...
 
RandomBase< FullPrecRealType > & getRng (int i) override
 return the i-th random generator More...
 
unsigned long getDriverMode () override
 
- Public Member Functions inherited from QMCDriverInterface
virtual ~QMCDriverInterface ()
 
virtual void setBranchEngine (std::unique_ptr< BranchEngineType > &&be)
 
- Public Member Functions inherited from MPIObjectBase
 MPIObjectBase (Communicate *c)
 constructor with communicator More...
 
int rank () const
 return the rank of the communicator More...
 
int getGroupID () const
 return the group id of the communicator More...
 
CommunicategetCommunicator () const
 return myComm More...
 
CommunicategetCommRef () const
 return a TEMPORARY reference to Communicate More...
 
mpi_comm_type getMPI () const
 return MPI communicator if one wants to use MPI directly More...
 
bool is_manager () const
 return true if the rank == 0 More...
 
const std::string & getName () const
 return the name More...
 
void setName (const std::string &aname)
 
- Public Member Functions inherited from CloneManager
 CloneManager ()
 Constructor. More...
 
virtual ~CloneManager ()
 virtual destructor More...
 
void makeClones (MCWalkerConfiguration &w, TrialWaveFunction &psi, QMCHamiltonian &ham)
 
void makeClones (MCWalkerConfiguration &w, std::vector< TrialWaveFunction *> &psi, std::vector< QMCHamiltonian *> &ham)
 
void makeClones (MCWalkerConfiguration &wg, TrialWaveFunction &guide)
 
void makeClones (TrialWaveFunction &guide)
 
RealType acceptRatio () const
 

Private Member Functions

 CSVMC (const CSVMC &)=delete
 Copy Constructor (disabled) More...
 
CSVMCoperator= (const CSVMC &)=delete
 Copy operator (disabled). More...
 
void resetRun ()
 

Private Attributes

std::string UseDrift
 
int prevSteps
 
int prevStepsBetweenSamples
 
int equilBlocks
 blocks over which normalization factors are accumulated More...
 
CSEnergyEstimatormultiEstimator
 
CSUpdateBaseMover
 

Additional Inherited Members

- Public Types inherited from QMCDriver
enum  { QMC_UPDATE_MODE, QMC_MULTIPLE, QMC_OPTIMIZE, QMC_WARMUP }
 enumeration coupled with QMCMode More...
 
using Walker_t = MCWalkerConfiguration::Walker_t
 
using Buffer_t = Walker_t::Buffer_t
 
using FullPrecRealType = QMCTraits::FullPrecRealType
 
- Public Types inherited from QMCDriverInterface
using BranchEngineType = SimpleFixedNodeBranch
 
using FullPrecRealType = QMCTraits::FullPrecRealType
 
- Public Types inherited from QMCTraits
enum  { DIM = OHMMS_DIM, DIM_VGL = OHMMS_DIM + 2 }
 
using QTBase = QMCTypes< OHMMS_PRECISION, DIM >
 
using QTFull = QMCTypes< OHMMS_PRECISION_FULL, DIM >
 
using RealType = QTBase::RealType
 
using ComplexType = QTBase::ComplexType
 
using ValueType = QTBase::ValueType
 
using PosType = QTBase::PosType
 
using GradType = QTBase::GradType
 
using TensorType = QTBase::TensorType
 
using IndexType = OHMMS_INDEXTYPE
 define other types More...
 
using FullPrecRealType = QTFull::RealType
 
using FullPrecValueType = QTFull::ValueType
 
using PropertySetType = RecordNamedProperty< FullPrecRealType >
 define PropertyList_t More...
 
using PtclGrpIndexes = std::vector< std::pair< int, int > >
 
- Public Types inherited from MPIObjectBase
using mpi_comm_type = Communicate::mpi_comm_type
 
- Static Public Member Functions inherited from CloneManager
static void clearClones ()
 
- Public Attributes inherited from QMCDriver
std::bitset< QMC_MODE_MAXqmc_driver_mode
 bits to classify QMCDriver More...
 
bool allow_traces
 whether to allow traces More...
 
xmlNodePtr traces_xml
 traces xml More...
 
bool allow_walker_logs
 whether to allow traces More...
 
xmlNodePtr walker_logs_xml
 traces xml More...
 
EstimatorManagerBaseEstimators
 Observables manager. More...
 
std::unique_ptr< TraceManagerTraces
 Traces manager. More...
 
std::unique_ptr< WalkerLogManagerwlog_manager_
 Traces manager. More...
 
- Protected Member Functions inherited from QMCDriver
bool putQMCInfo (xmlNodePtr cur)
 Parses the xml input file for parameter definitions for a single qmc simulation. More...
 
void addWalkers (int nwalkers)
 Add walkers to the end of the ensemble of walkers. More...
 
void recordBlock (int block) override
 record the state of the block More...
 
bool finalize (int block, bool dumpwalkers=true)
 finalize a qmc section More...
 
std::string getRotationName (std::string RootName)
 
std::string getLastRotationName (std::string RootName)
 
const std::string & get_root_name () const override
 
- Protected Member Functions inherited from CloneManager
RefVector< WalkerLogCollectorgetWalkerLogCollectorRefs ()
 
- Protected Attributes inherited from QMCDriver
const ProjectDataproject_data_
 top-level project data information More...
 
std::unique_ptr< BranchEngineTypebranchEngine
 branch engine More...
 
DriftModifierBaseDriftModifier
 drift modifer More...
 
bool ResetRandom
 randomize it More...
 
bool AppendRun
 flag to append or restart the run More...
 
bool DumpConfig
 flag to turn off dumping configurations More...
 
bool IsQMCDriver
 true, if it is a real QMC engine More...
 
int MyCounter
 the number of times this QMCDriver is executed More...
 
int kDelay
 the number to delay updates by More...
 
int Period4CheckPoint
 period of dumping walker configurations and everything else for restart More...
 
int Period4CheckProperties
 period of dumping walker positions and IDs for Forward Walking More...
 
int Period4WalkerDump
 period of recording walker configurations More...
 
int Period4ConfigDump
 period of recording walker positions and IDs for forward walking afterwards More...
 
IndexType CurrentStep
 current step More...
 
IndexType nBlocks
 maximum number of blocks More...
 
IndexType nSteps
 maximum number of steps More...
 
IndexType nSubSteps
 number of steps between a step: VMCs do not evaluate energies More...
 
IndexType nWarmupSteps
 number of warmup steps More...
 
IndexType nAccept
 counter for number of moves accepted More...
 
IndexType nReject
 counter for number of moves /rejected More...
 
IndexType nBlocksBetweenRecompute
 the number of blocks between recomptePsi More...
 
IndexType nTargetWalkers
 the number of walkers More...
 
IndexType nTargetSamples
 the number of saved samples More...
 
IndexType nStepsBetweenSamples
 alternate method of setting QMC run parameters More...
 
RealType nSamplesPerThread
 samples per thread More...
 
RealType nTargetPopulation
 target population More...
 
RealType Tau
 timestep More...
 
int MaxCPUSecs
 maximum cpu in secs More...
 
RealType m_oneover2tau
 Time-step factor $ 1/(2\tau)$. More...
 
RealType m_sqrttau
 Time-step factor $ \sqrt{\tau}$. More...
 
xmlNodePtr qmcNode
 pointer to qmc node in xml file More...
 
const std::string QMCType
 type of QMC driver More...
 
std::string h5FileRoot
 the root of h5File More...
 
std::string RootName
 root of all the output files More...
 
ParameterSet m_param
 store any parameter that has to be read from a file More...
 
MCWalkerConfigurationW
 walker ensemble More...
 
TrialWaveFunctionPsi
 trial function More...
 
QMCHamiltonianH
 Hamiltonian. More...
 
std::unique_ptr< HDFWalkerOutputwOut
 record engine for walkers More...
 
std::vector< TrialWaveFunction * > Psi1
 a list of TrialWaveFunctions for multiple method More...
 
std::vector< QMCHamiltonian * > H1
 a list of QMCHamiltonians for multiple method More...
 
UPtrVector< RandomBase< FullPrecRealType > > Rng
 Random number generators. More...
 
std::vector< xmlNodePtr > mcwalkerNodePtr
 a list of mcwalkerset element More...
 
ParticleSet::ParticlePos drift
 temporary storage for drift More...
 
ParticleSet::ParticlePos deltaR
 temporary storage for random displacement More...
 
RealType SpinMass
 spin mass for spinor calcs More...
 
int rotation
 
- Protected Attributes inherited from MPIObjectBase
CommunicatemyComm
 pointer to Communicate More...
 
std::string ClassName
 class Name More...
 
std::string myName
 name of the object More...
 
- Protected Attributes inherited from CloneManager
const IndexType NumThreads
 number of threads More...
 
std::vector< QMCUpdateBase * > Movers
 update engines More...
 
std::vector< EstimatorManagerBase * > estimatorClones
 estimator managers More...
 
std::vector< TraceManager * > traceClones
 trace managers More...
 
UPtrVector< WalkerLogCollectorwlog_collectors
 trace collectors More...
 
UPtrVector< CSUpdateBaseCSMovers
 
std::vector< int > wPerRank
 Walkers per MPI rank. More...
 
- Static Protected Attributes inherited from CloneManager
static UPtrVector< MCWalkerConfigurationwClones_uptr
 walkers More...
 
static std::vector< MCWalkerConfiguration * > wClones
 
static UPtrVector< MCWalkerConfigurationwgClones
 
static UPtrVector< TrialWaveFunctionpsiClones_uptr
 trial wavefunctions More...
 
static std::vector< TrialWaveFunction * > psiClones
 
static UPtrVector< TrialWaveFunctionguideClones_uptr
 guide wavefunctions More...
 
static std::vector< TrialWaveFunction * > guideClones
 
static UPtrVector< QMCHamiltonianhClones_uptr
 Hamiltonians. More...
 
static std::vector< QMCHamiltonian * > hClones
 
static std::vector< UPtrVector< MCWalkerConfiguration > > WPoolClones_uptr
 
static std::vector< std::vector< MCWalkerConfiguration * > > WPoolClones
 
static std::vector< UPtrVector< TrialWaveFunction > > PsiPoolClones_uptr
 
static std::vector< std::vector< TrialWaveFunction * > > PsiPoolClones
 
static std::vector< UPtrVector< QMCHamiltonian > > HPoolClones_uptr
 
static std::vector< std::vector< QMCHamiltonian * > > HPoolClones
 

Constructor & Destructor Documentation

◆ CSVMC() [1/2]

CSVMC ( const ProjectData project_data,
MCWalkerConfiguration w,
TrialWaveFunction psi,
QMCHamiltonian h,
Communicate comm 
)

Constructor.

Definition at line 37 of file CSVMC.cpp.

References ParameterSet::add(), CSVMC::equilBlocks, QMCDriver::m_param, QMCDriver::qmc_driver_mode, QMCDriver::QMC_MULTIPLE, QMCDriver::RootName, and CSVMC::UseDrift.

42  : QMCDriver(project_data, w, psi, h, comm, "CSVMC"), UseDrift("yes"), multiEstimator(0), Mover(0)
43 {
44  RootName = "csvmc";
45  m_param.add(UseDrift, "useDrift");
46  m_param.add(UseDrift, "usedrift");
47  m_param.add(UseDrift, "use_drift");
48  equilBlocks = -1;
49  m_param.add(equilBlocks, "equilBlocks");
51 }
int equilBlocks
blocks over which normalization factors are accumulated
Definition: CSVMC.h:53
QMCDriver(const ProjectData &project_data, MCWalkerConfiguration &w, TrialWaveFunction &psi, QMCHamiltonian &h, Communicate *comm, const std::string &QMC_driver_type, bool enable_profiling=false)
Constructor.
Definition: QMCDriver.cpp:44
std::string RootName
root of all the output files
Definition: QMCDriver.h:317
ParameterSet m_param
store any parameter that has to be read from a file
Definition: QMCDriver.h:320
std::bitset< QMC_MODE_MAX > qmc_driver_mode
bits to classify QMCDriver
Definition: QMCDriver.h:93
CSUpdateBase * Mover
Definition: CSVMC.h:63
CSEnergyEstimator * multiEstimator
Definition: CSVMC.h:62
void add(PDT &aparam, const std::string &aname_in, std::vector< PDT > candidate_values={}, TagStatus status=TagStatus::OPTIONAL)
add a new parameter corresponding to an xmlNode <parameter>
std::string UseDrift
Definition: CSVMC.h:49

◆ CSVMC() [2/2]

CSVMC ( const CSVMC )
privatedelete

Copy Constructor (disabled)

Member Function Documentation

◆ getRunType()

QMCRunType getRunType ( )
inlineoverridevirtual

Implements QMCDriverInterface.

Definition at line 46 of file CSVMC.h.

References qmcplusplus::CSVMC.

◆ operator=()

CSVMC& operator= ( const CSVMC )
privatedelete

Copy operator (disabled).

◆ put()

bool put ( xmlNodePtr  q)
overridevirtual

allocate internal data here before run() is called

Author
SIMONE

See QMCDriver::process

Implements QMCDriverInterface.

Definition at line 58 of file CSVMC.cpp.

References ParameterSet::add(), qmcplusplus::app_log(), qmcplusplus::ceil(), QMCDriver::CurrentStep, QMCDriver::DumpConfig, ParameterSet::get(), WalkerConfigurations::getActiveWalkers(), QMCDriver::m_param, MPIObjectBase::myComm, QMCDriver::MyCounter, QMCDriver::nBlocks, QMCDriver::nSamplesPerThread, QMCDriver::nSteps, QMCDriver::nStepsBetweenSamples, QMCDriver::nSubSteps, QMCDriver::nTargetPopulation, QMCDriver::nTargetSamples, omp_get_max_threads(), QMCDriver::Period4CheckPoint, QMCDriver::Period4WalkerDump, CSVMC::prevSteps, CSVMC::prevStepsBetweenSamples, ParameterSet::put(), qmcplusplus::qmc_common, QMCState::qmc_counter, Communicate::size(), QMCDriver::Tau, and QMCDriver::W.

59 {
60  int target_min = -1;
61  ParameterSet p;
62  p.add(target_min, "minimumtargetwalkers");
63  p.add(target_min, "minimumsamples");
64  p.put(q);
65 
66  app_log() << "\n<vmc function=\"put\">"
67  << "\n qmc_counter=" << qmc_common.qmc_counter << " my_counter=" << MyCounter << std::endl;
69  {
70  nSteps = prevSteps;
72  }
73  else
74  {
75  int nw = W.getActiveWalkers();
76  //compute samples and overwrite steps for the given samples
77  int Nthreads = omp_get_max_threads();
78  int Nprocs = myComm->size();
79  //target samples set by samples or samplesperthread/dmcwalkersperthread
80  nTargetPopulation = std::max(nTargetPopulation, nSamplesPerThread * Nprocs * Nthreads);
81  nTargetSamples = static_cast<int>(std::ceil(nTargetPopulation));
82 
83  if (nTargetSamples)
84  {
85  int nwtot = nw * Nprocs; //total number of walkers used by this qmcsection
86  nTargetSamples = std::max(nwtot, nTargetSamples);
87  if (target_min > 0)
88  {
89  nTargetSamples = std::max(nTargetSamples, target_min);
90  nTargetPopulation = std::max(nTargetPopulation, static_cast<RealType>(target_min));
91  }
92  nTargetSamples = ((nTargetSamples + nwtot - 1) / nwtot) *
93  nwtot; // nTargetSamples are always multiples of total number of walkers
94  nSamplesPerThread = nTargetSamples / Nprocs / Nthreads;
95  int ns_target = nTargetSamples * nStepsBetweenSamples; //total samples to generate
96  int ns_per_step = Nprocs * nw; //total samples per step
97  nSteps = std::max(nSteps, (ns_target / ns_per_step + nBlocks - 1) / nBlocks);
99  }
100  else
101  {
102  Period4WalkerDump = nStepsBetweenSamples = (nBlocks + 1) * nSteps; //some positive number, not used
103  nSamplesPerThread = 0;
104  }
105  }
106  prevSteps = nSteps;
108 
109  app_log() << " time step = " << Tau << std::endl;
110  app_log() << " blocks = " << nBlocks << std::endl;
111  app_log() << " steps = " << nSteps << std::endl;
112  app_log() << " substeps = " << nSubSteps << std::endl;
113  app_log() << " current = " << CurrentStep << std::endl;
114  app_log() << " target samples = " << nTargetPopulation << std::endl;
115  app_log() << " walkers/mpi = " << W.getActiveWalkers() << std::endl << std::endl;
116  app_log() << " stepsbetweensamples = " << nStepsBetweenSamples << std::endl;
117 
118  m_param.get(app_log());
119 
120  if (DumpConfig)
121  {
122  app_log() << " DumpConfig==true Configurations are dumped to config.h5 with a period of " << Period4CheckPoint
123  << " blocks" << std::endl;
124  }
125  else
126  {
127  app_log() << " DumpConfig==false Nothing (configurations, state) will be saved." << std::endl;
128  }
129 
130  if (Period4WalkerDump > 0)
131  app_log() << " Walker Samples are dumped every " << Period4WalkerDump << " steps." << std::endl;
132 
133  app_log() << "</vmc>" << std::endl;
134  app_log().flush();
135 
136  return true;
137 }
size_t getActiveWalkers() const
return the number of active walkers
bool DumpConfig
flag to turn off dumping configurations
Definition: QMCDriver.h:226
std::ostream & app_log()
Definition: OutputManager.h:65
RealType nSamplesPerThread
samples per thread
Definition: QMCDriver.h:293
int prevStepsBetweenSamples
Definition: CSVMC.h:51
IndexType CurrentStep
current step
Definition: QMCDriver.h:263
int size() const
return the number of tasks
Definition: Communicate.h:118
bool put(std::istream &is) override
read from std::istream
Definition: ParameterSet.h:42
ParameterSet m_param
store any parameter that has to be read from a file
Definition: QMCDriver.h:320
IndexType nSubSteps
number of steps between a step: VMCs do not evaluate energies
Definition: QMCDriver.h:272
IndexType nSteps
maximum number of steps
Definition: QMCDriver.h:269
class to handle a set of parameters
Definition: ParameterSet.h:27
MakeReturn< UnaryNode< FnCeil, typename CreateLeaf< Vector< T1, C1 > >::Leaf_t > >::Expression_t ceil(const Vector< T1, C1 > &l)
omp_int_t omp_get_max_threads()
Definition: OpenMP.h:26
Communicate * myComm
pointer to Communicate
Definition: MPIObjectBase.h:62
bool get(std::ostream &os) const override
write to a std::ostream
Definition: ParameterSet.h:35
int qmc_counter
init for <qmc> section
Definition: qmc_common.h:31
MCWalkerConfiguration & W
walker ensemble
Definition: QMCDriver.h:323
void add(PDT &aparam, const std::string &aname_in, std::vector< PDT > candidate_values={}, TagStatus status=TagStatus::OPTIONAL)
add a new parameter corresponding to an xmlNode <parameter>
IndexType nTargetSamples
the number of saved samples
Definition: QMCDriver.h:289
int Period4CheckPoint
period of dumping walker configurations and everything else for restart
Definition: QMCDriver.h:242
RealType nTargetPopulation
target population
Definition: QMCDriver.h:295
RealType Tau
timestep
Definition: QMCDriver.h:299
IndexType nStepsBetweenSamples
alternate method of setting QMC run parameters
Definition: QMCDriver.h:291
IndexType nBlocks
maximum number of blocks
Definition: QMCDriver.h:266
int Period4WalkerDump
period of recording walker configurations
Definition: QMCDriver.h:255
QMCState qmc_common
a unique QMCState during a run
Definition: qmc_common.cpp:111
int MyCounter
the number of times this QMCDriver is executed
Definition: QMCDriver.h:235

◆ resetRun()

void resetRun ( )
private

Definition at line 210 of file CSVMC.cpp.

References APP_ABORT, qmcplusplus::app_log(), WalkerConfigurations::begin(), QMCDriver::branchEngine, RandomNumberControl::Children, copy(), CloneManager::CSMovers, QMCDriver::DriftModifier, CloneManager::estimatorClones, QMCDriver::Estimators, FairDivideLow(), WalkerConfigurations::getActiveWalkers(), QMCDriver::H1, CloneManager::HPoolClones, CloneManager::makeClones(), CloneManager::Movers, QMCDriver::nSamplesPerThread, QMCDriver::nTargetSamples, CloneManager::NumThreads, QMCDriver::nWarmupSteps, QMCDriver::Psi1, CloneManager::PsiPoolClones, QMCDriver::qmc_driver_mode, QMCDriver::QMC_UPDATE_MODE, QMCDriver::qmcNode, QMCDriver::Rng, CloneManager::traceClones, QMCDriver::Traces, CSVMC::UseDrift, QMCDriver::W, CloneManager::wClones, and CloneManager::wPerRank.

Referenced by CSVMC::run().

211 {
212  H1[0]->setPrimary(true);
213  IndexType nPsi = Psi1.size();
214  for (int ipsi = 1; ipsi < nPsi; ipsi++)
215  H1[ipsi]->setPrimary(false);
216 
217 
218  makeClones(W, Psi1, H1);
220 
221  if (NumThreads > 1)
222  APP_ABORT("OpenMP Parallelization for CSVMC not working at the moment");
223 
224  app_log() << " Initial partition of walkers ";
225  copy(wPerRank.begin(), wPerRank.end(), std::ostream_iterator<int>(app_log(), " "));
226  app_log() << std::endl;
227 
228 
229  if (Movers.empty())
230  {
231  CSMovers.resize(NumThreads);
232  estimatorClones.resize(NumThreads, nullptr);
233  traceClones.resize(NumThreads, nullptr);
234  Rng.resize(NumThreads);
235 
236  // hdf_archive::hdf_archive() is not thread-safe
237  for (int ip = 0; ip < NumThreads; ++ip)
238  estimatorClones[ip] = new EstimatorManagerBase(*Estimators);
239 
240 #pragma omp parallel for
241  for (int ip = 0; ip < NumThreads; ++ip)
242  {
243  std::ostringstream os;
244  estimatorClones[ip]->resetTargetParticleSet(*wClones[ip]);
245  estimatorClones[ip]->setCollectionMode(false);
246 #if !defined(REMOVE_TRACEMANAGER)
247  traceClones[ip] = Traces->makeClone();
248 #endif
249  Rng[ip] = RandomNumberControl::Children[ip]->makeClone();
251  {
252  if (UseDrift == "yes")
253  {
254  os << " Using particle-by-particle update with drift " << std::endl;
255  CSMovers[ip] = std::make_unique<CSVMCUpdatePbyPWithDriftFast>(*wClones[ip], PsiPoolClones[ip], HPoolClones[ip], *Rng[ip]);
256  }
257  else
258  {
259  os << " Using particle-by-particle update with no drift" << std::endl;
260  CSMovers[ip] = std::make_unique<CSVMCUpdatePbyP>(*wClones[ip], PsiPoolClones[ip], HPoolClones[ip], *Rng[ip]);
261  }
262  }
263  else
264  {
265  if (UseDrift == "yes")
266  {
267  os << " Using walker-by-walker update with Drift " << std::endl;
268  CSMovers[ip] = std::make_unique<CSVMCUpdateAllWithDrift>(*wClones[ip], PsiPoolClones[ip], HPoolClones[ip], *Rng[ip]);
269  }
270  else
271  {
272  os << " Using walker-by-walker update " << std::endl;
273  CSMovers[ip] = std::make_unique<CSVMCUpdateAll>(*wClones[ip], PsiPoolClones[ip], HPoolClones[ip], *Rng[ip]);
274  }
275  }
276  if (ip == 0)
277  app_log() << os.str() << std::endl;
278 
279  CSMovers[ip]->put(qmcNode);
280  CSMovers[ip]->resetRun(branchEngine.get(), estimatorClones[ip], traceClones[ip], DriftModifier);
281  }
282  }
283 #if !defined(REMOVE_TRACEMANAGER)
284  else
285  {
286 #pragma omp parallel for
287  for (int ip = 0; ip < NumThreads; ++ip)
288  {
289  traceClones[ip]->transfer_state_from(*Traces);
290  }
291  }
292 #endif
293 
294  app_log() << " Total Sample Size =" << nTargetSamples << std::endl;
295  app_log() << " Walker distribution on root = ";
296  copy(wPerRank.begin(), wPerRank.end(), std::ostream_iterator<int>(app_log(), " "));
297  app_log() << std::endl;
298  app_log().flush();
299 
300 #pragma omp parallel for
301  for (int ip = 0; ip < NumThreads; ++ip)
302  {
303  //int ip=omp_get_thread_num();
304  CSMovers[ip]->put(qmcNode);
305  CSMovers[ip]->resetRun(branchEngine.get(), estimatorClones[ip], traceClones[ip], DriftModifier);
307  CSMovers[ip]->initCSWalkersForPbyP(W.begin() + wPerRank[ip], W.begin() + wPerRank[ip + 1], nWarmupSteps > 0);
308  else
309  CSMovers[ip]->initCSWalkers(W.begin() + wPerRank[ip], W.begin() + wPerRank[ip + 1], nWarmupSteps > 0);
310 
311  for (int prestep = 0; prestep < nWarmupSteps; ++prestep)
312  {
313  CSMovers[ip]->advanceWalkers(W.begin() + wPerRank[ip], W.begin() + wPerRank[ip + 1], true);
314  if (prestep == nWarmupSteps - 1)
315  CSMovers[ip]->updateNorms();
316  }
317  }
318 
319  for (int ip = 0; ip < NumThreads; ++ip)
320  wClones[ip]->clearEnsemble();
321  if (nSamplesPerThread)
322  for (int ip = 0; ip < NumThreads; ++ip)
323  wClones[ip]->setNumSamples(nSamplesPerThread);
324  nWarmupSteps = 0;
325 }
std::vector< int > wPerRank
Walkers per MPI rank.
Definition: CloneManager.h:91
std::vector< TrialWaveFunction * > Psi1
a list of TrialWaveFunctions for multiple method
Definition: QMCDriver.h:335
size_t getActiveWalkers() const
return the number of active walkers
static std::vector< std::vector< TrialWaveFunction * > > PsiPoolClones
Definition: CloneManager.h:85
static std::vector< MCWalkerConfiguration * > wClones
Definition: CloneManager.h:61
std::ostream & app_log()
Definition: OutputManager.h:65
RealType nSamplesPerThread
samples per thread
Definition: QMCDriver.h:293
xmlNodePtr qmcNode
pointer to qmc node in xml file
Definition: QMCDriver.h:310
UPtrVector< CSUpdateBase > CSMovers
Definition: CloneManager.h:88
std::vector< QMCUpdateBase * > Movers
update engines
Definition: CloneManager.h:73
std::unique_ptr< TraceManager > Traces
Traces manager.
Definition: QMCDriver.h:195
void FairDivideLow(int ntot, int npart, IV &adist)
partition ntot elements among npart
Definition: FairDivide.h:114
void copy(const Array< T1, 3 > &src, Array< T2, 3 > &dest)
Definition: Blitz.h:639
std::bitset< QMC_MODE_MAX > qmc_driver_mode
bits to classify QMCDriver
Definition: QMCDriver.h:93
std::unique_ptr< BranchEngineType > branchEngine
branch engine
Definition: QMCDriver.h:218
std::vector< EstimatorManagerBase * > estimatorClones
estimator managers
Definition: CloneManager.h:75
const IndexType NumThreads
number of threads
Definition: CloneManager.h:54
DriftModifierBase * DriftModifier
drift modifer
Definition: QMCDriver.h:220
#define APP_ABORT(msg)
Widely used but deprecated fatal error macros from legacy code.
Definition: AppAbort.h:27
void makeClones(MCWalkerConfiguration &w, TrialWaveFunction &psi, QMCHamiltonian &ham)
MCWalkerConfiguration & W
walker ensemble
Definition: QMCDriver.h:323
static UPtrVector< RandomBase< FullPrecRealType > > Children
OHMMS_INDEXTYPE IndexType
define other types
Definition: Configuration.h:65
std::vector< QMCHamiltonian * > H1
a list of QMCHamiltonians for multiple method
Definition: QMCDriver.h:338
IndexType nTargetSamples
the number of saved samples
Definition: QMCDriver.h:289
EstimatorManagerBase * Estimators
Observables manager.
Definition: QMCDriver.h:192
static std::vector< std::vector< QMCHamiltonian * > > HPoolClones
Definition: CloneManager.h:87
std::vector< TraceManager * > traceClones
trace managers
Definition: CloneManager.h:77
IndexType nWarmupSteps
number of warmup steps
Definition: QMCDriver.h:275
UPtrVector< RandomBase< FullPrecRealType > > Rng
Random number generators.
Definition: QMCDriver.h:341
std::string UseDrift
Definition: CSVMC.h:49
iterator begin()
return the first iterator

◆ run()

bool run ( )
overridevirtual

Run the CSVMC algorithm.

Similar to VMC::run

write samples to a file

Implements QMCDriverInterface.

Definition at line 143 of file CSVMC.cpp.

References qmcplusplus::app_log(), WalkerConfigurations::begin(), RandomNumberControl::Children, ParticleSet::Collectables, CloneManager::CSMovers, QMCDriver::CurrentStep, QMCDriver::DumpConfig, MCWalkerConfiguration::dumpEnsemble(), CloneManager::estimatorClones, QMCDriver::Estimators, QMCDriver::finalize(), MPIObjectBase::myComm, QMCDriver::nBlocks, QMCDriver::nSteps, CloneManager::NumThreads, omp_get_thread_num(), QMCDriver::Period4CheckProperties, QMCDriver::Period4WalkerDump, QMCDriver::qmc_driver_mode, QMCDriver::QMC_UPDATE_MODE, QMCDriver::recordBlock(), CSVMC::resetRun(), QMCDriver::Rng, PooledData< T >::size(), Communicate::size(), EstimatorManagerBase::start(), EstimatorManagerBase::stop(), EstimatorManagerBase::stopBlock(), CloneManager::traceClones, QMCDriver::Traces, QMCDriver::W, CloneManager::wClones, QMCDriver::wOut, and CloneManager::wPerRank.

144 {
145  resetRun();
146  //start the main estimator
148  for (int ip = 0; ip < NumThreads; ++ip)
149  CSMovers[ip]->startRun(nBlocks, false);
150 
151 #if !defined(REMOVE_TRACEMANAGER)
152  Traces->startRun(nBlocks, traceClones);
153 #endif
154  const bool has_collectables = W.Collectables.size();
155  for (int block = 0; block < nBlocks; ++block)
156  {
157 #pragma omp parallel
158  {
159  int ip = omp_get_thread_num();
161  //assign the iterators and resuse them
162  MCWalkerConfiguration::iterator wit(W.begin() + wPerRank[ip]), wit_end(W.begin() + wPerRank[ip + 1]);
163  CSMovers[ip]->startBlock(nSteps);
164  int now_loc = CurrentStep;
165  RealType cnorm = 1.0 / static_cast<RealType>(wPerRank[ip + 1] - wPerRank[ip]);
166  for (int step = 0; step < nSteps; ++step)
167  {
168  CSMovers[ip]->set_step(now_loc);
169  //collectables are reset, it is accumulated while advancing walkers
170  wClones[ip]->resetCollectables();
171  CSMovers[ip]->advanceWalkers(wit, wit_end, false);
172  if (has_collectables)
173  wClones[ip]->Collectables *= cnorm;
174  CSMovers[ip]->accumulate(wit, wit_end);
175  ++now_loc;
176  if (Period4WalkerDump && now_loc % Period4WalkerDump == 0)
177  wClones[ip]->saveEnsemble(wit, wit_end);
178  }
179  CSMovers[ip]->stopBlock(false);
180 
181  } //end-of-parallel for
182  CurrentStep += nSteps;
184 #if !defined(REMOVE_TRACEMANAGER)
185  Traces->write_buffers(traceClones, block);
186 #endif
187  recordBlock(block);
188  } //block
190  for (int ip = 0; ip < NumThreads; ++ip)
191  CSMovers[ip]->stopRun2();
192 #if !defined(REMOVE_TRACEMANAGER)
193  Traces->stopRun();
194 #endif
195  //copy back the random states
196  for (int ip = 0; ip < NumThreads; ++ip)
197  RandomNumberControl::Children[ip] = Rng[ip]->makeClone();
198  ///write samples to a file
199  bool wrotesamples = DumpConfig;
200  if (DumpConfig)
201  {
203  if (wrotesamples)
204  app_log() << " samples are written to the config.h5" << std::endl;
205  }
206  //finalize a qmc section
207  return finalize(nBlocks, !wrotesamples);
208 }
size_type size() const
return the size of the data
Definition: PooledData.h:48
std::vector< int > wPerRank
Walkers per MPI rank.
Definition: CloneManager.h:91
void recordBlock(int block) override
record the state of the block
Definition: QMCDriver.cpp:307
bool DumpConfig
flag to turn off dumping configurations
Definition: QMCDriver.h:226
static std::vector< MCWalkerConfiguration * > wClones
Definition: CloneManager.h:61
std::ostream & app_log()
Definition: OutputManager.h:65
IndexType CurrentStep
current step
Definition: QMCDriver.h:263
UPtrVector< CSUpdateBase > CSMovers
Definition: CloneManager.h:88
int size() const
return the number of tasks
Definition: Communicate.h:118
std::unique_ptr< TraceManager > Traces
Traces manager.
Definition: QMCDriver.h:195
omp_int_t omp_get_thread_num()
Definition: OpenMP.h:25
IndexType nSteps
maximum number of steps
Definition: QMCDriver.h:269
std::unique_ptr< HDFWalkerOutput > wOut
record engine for walkers
Definition: QMCDriver.h:332
bool finalize(int block, bool dumpwalkers=true)
finalize a qmc section
Definition: QMCDriver.cpp:318
WalkerList_t::iterator iterator
FIX: a type alias of iterator for an object should not be for just one of many objects it holds...
std::bitset< QMC_MODE_MAX > qmc_driver_mode
bits to classify QMCDriver
Definition: QMCDriver.h:93
Communicate * myComm
pointer to Communicate
Definition: MPIObjectBase.h:62
std::vector< EstimatorManagerBase * > estimatorClones
estimator managers
Definition: CloneManager.h:75
const IndexType NumThreads
number of threads
Definition: CloneManager.h:54
MCWalkerConfiguration & W
walker ensemble
Definition: QMCDriver.h:323
static UPtrVector< RandomBase< FullPrecRealType > > Children
OHMMS_INDEXTYPE IndexType
define other types
Definition: Configuration.h:65
Buffer_t Collectables
observables in addition to those registered in Properties/PropertyList
Definition: ParticleSet.h:126
static bool dumpEnsemble(std::vector< MCWalkerConfiguration *> &others, HDFWalkerOutput &out, int np, int nBlock)
dump Samples to a file
QMCTraits::RealType RealType
EstimatorManagerBase * Estimators
Observables manager.
Definition: QMCDriver.h:192
void stopBlock(RealType accept, bool collectall=true)
stop a block
IndexType nBlocks
maximum number of blocks
Definition: QMCDriver.h:266
int Period4WalkerDump
period of recording walker configurations
Definition: QMCDriver.h:255
std::vector< TraceManager * > traceClones
trace managers
Definition: CloneManager.h:77
int Period4CheckProperties
period of dumping walker positions and IDs for Forward Walking
Definition: QMCDriver.h:249
UPtrVector< RandomBase< FullPrecRealType > > Rng
Random number generators.
Definition: QMCDriver.h:341
void start(int blocks, bool record=true)
start a run
iterator begin()
return the first iterator

Member Data Documentation

◆ equilBlocks

int equilBlocks
private

blocks over which normalization factors are accumulated

Definition at line 53 of file CSVMC.h.

Referenced by CSVMC::CSVMC().

◆ Mover

CSUpdateBase* Mover
private

Definition at line 63 of file CSVMC.h.

◆ multiEstimator

CSEnergyEstimator* multiEstimator
private

Definition at line 62 of file CSVMC.h.

◆ prevSteps

int prevSteps
private

Definition at line 50 of file CSVMC.h.

Referenced by CSVMC::put().

◆ prevStepsBetweenSamples

int prevStepsBetweenSamples
private

Definition at line 51 of file CSVMC.h.

Referenced by CSVMC::put().

◆ UseDrift

std::string UseDrift
private

Definition at line 49 of file CSVMC.h.

Referenced by CSVMC::CSVMC(), and CSVMC::resetRun().

◆ qmcplusplus::CSVMCUpdateAll

class qmcplusplus::CSVMCUpdateAll


Implements the VMC algorithm using umbrella sampling.

Energy difference method with multiple H/Psi. Consult S. Chiesa's note.

Definition at line 32 of file CSVMCUpdateAll.h.

+ Inheritance diagram for CSVMCUpdateAll:
+ Collaboration diagram for CSVMCUpdateAll:

Public Member Functions

 CSVMCUpdateAll (MCWalkerConfiguration &w, std::vector< TrialWaveFunction *> &psi, std::vector< QMCHamiltonian *> &h, RandomBase< FullPrecRealType > &rg)
 Constructor. More...
 
void advanceWalker (Walker_t &thisWalker, bool recompute) override
 move a walker More...
 
- Public Member Functions inherited from CSUpdateBase
 CSUpdateBase (MCWalkerConfiguration &w, std::vector< TrialWaveFunction *> &psi, std::vector< QMCHamiltonian *> &h, RandomBase< FullPrecRealType > &rg)
 
 ~CSUpdateBase () override
 
void computeSumRatio (const std::vector< RealType > &logpsi, const std::vector< RealType > &avgNorm, std::vector< RealType > &sumratio)
 
void computeSumRatio (const Matrix< RealType > &ratioij, std::vector< RealType > &sumratio)
 
void computeSumRatio (const std::vector< RealType > &logpsi, const std::vector< RealType > &avgNorm, Matrix< RealType > &ratioij, std::vector< RealType > &sumratio)
 
void updateRatioMatrix (const std::vector< RealType > &ratio_pbyp, Matrix< RealType > &ratioij)
 
void resizeWorkSpace (int nw, int nptcls)
 
void updateNorms ()
 
void updateAvgWeights ()
 
void initCSWalkers (WalkerIter_t it, WalkerIter_t it_end, bool resetNorms)
 
void initCSWalkersForPbyP (WalkerIter_t it, WalkerIter_t it_end, bool resetNorms)
 
void updateCSWalkers (WalkerIter_t it, WalkerIter_t it_end)
 
- Public Member Functions inherited from QMCUpdateBase
 QMCUpdateBase (MCWalkerConfiguration &w, TrialWaveFunction &psi, QMCHamiltonian &h, RandomBase< FullPrecRealType > &rg)
 Constructor. More...
 
 QMCUpdateBase (MCWalkerConfiguration &w, TrialWaveFunction &psi, TrialWaveFunction &guide, QMCHamiltonian &h, RandomBase< FullPrecRealType > &rg)
 Alt Constructor. More...
 
virtual ~QMCUpdateBase ()
 destructor More...
 
RealType acceptRatio () const
 
void resetRun (BranchEngineType *brancher, EstimatorManagerBase *est, TraceManager *traces, const DriftModifierBase *driftmodifer)
 reset the QMCUpdateBase parameters More...
 
void resetRun2 (BranchEngineType *brancher, EstimatorManagerBase *est, TraceManager *traces, WalkerLogCollector *wlog_collector_, const DriftModifierBase *driftmodifer)
 
RealType getTau ()
 
void setTau (RealType t)
 
RealType getSpinMass ()
 
void setSpinMass (RealType m)
 
void getLogs (std::vector< RealType > &logs)
 
void set_step (int step)
 
void startRun (int blocks, bool record)
 start a run More...
 
void stopRun ()
 stop a run More...
 
void stopRun2 ()
 
void startBlock (int steps)
 prepare to start a block More...
 
void stopBlock (bool collectall=true)
 stop a block More...
 
void setMultiplicity (WalkerIter_t it, WalkerIter_t it_end)
 set the multiplicity of the walkers to branch More...
 
void setMultiplicity (Walker_t &awalker) const
 
virtual void initWalkersForPbyP (WalkerIter_t it, WalkerIter_t it_end)
 initialize Walker buffers for PbyP update More...
 
virtual void initWalkers (WalkerIter_t it, WalkerIter_t it_end)
 initialize Walker for walker update More...
 
virtual bool put (xmlNodePtr cur)
 process options More...
 
void accumulate (WalkerIter_t it, WalkerIter_t it_end)
 
virtual void advanceWalkers (WalkerIter_t it, WalkerIter_t it_end, bool recompute)
 advance walkers executed at each step More...
 
virtual RealType advanceWalkerForEE (Walker_t &w1, std::vector< PosType > &dR, std::vector< int > &iats, std::vector< int > &rs, std::vector< RealType > &ratios)
 
int RMC_checkIndex (int N, int NMax)
 
void RMC_checkWalkerBounds (WalkerIter_t &it, WalkerIter_t first, WalkerIter_t last)
 
RealType logBackwardGF (const ParticleSet::ParticlePos &displ)
 

Additional Inherited Members

- Public Types inherited from QMCUpdateBase
using Walker_t = MCWalkerConfiguration::Walker_t
 
using WalkerIter_t = MCWalkerConfiguration::iterator
 
using BranchEngineType = SimpleFixedNodeBranch
 
using mPosType = PosType
 
using mTensorType = TensorType
 
- Public Types inherited from QMCTraits
enum  { DIM = OHMMS_DIM, DIM_VGL = OHMMS_DIM + 2 }
 
using QTBase = QMCTypes< OHMMS_PRECISION, DIM >
 
using QTFull = QMCTypes< OHMMS_PRECISION_FULL, DIM >
 
using RealType = QTBase::RealType
 
using ComplexType = QTBase::ComplexType
 
using ValueType = QTBase::ValueType
 
using PosType = QTBase::PosType
 
using GradType = QTBase::GradType
 
using TensorType = QTBase::TensorType
 
using IndexType = OHMMS_INDEXTYPE
 define other types More...
 
using FullPrecRealType = QTFull::RealType
 
using FullPrecValueType = QTFull::ValueType
 
using PropertySetType = RecordNamedProperty< FullPrecRealType >
 define PropertyList_t More...
 
using PtclGrpIndexes = std::vector< std::pair< int, int > >
 
- Public Attributes inherited from CSUpdateBase
int nPsi
 
bool useDrift
 
std::vector< RealTypelogpsi
 
std::vector< RealTypesumratio
 
std::vector< RealTypeinvsumratio
 
std::vector< RealTypeavgNorm
 
std::vector< RealTypeavgWeight
 
std::vector< RealTypelogNorm
 
std::vector< RealTypecumNorm
 
std::vector< RealTypeinstRij
 
std::vector< RealTyperatio
 
Matrix< RealTyperatioIJ
 
std::string useDriftOption
 
Matrix< RealTypeRatioIJ
 
CSEnergyEstimatormultiEstimator
 multiple estimator More...
 
std::vector< QMCHamiltonian * > H1
 a list of QMCHamiltonians for multiple method More...
 
std::vector< TrialWaveFunction * > Psi1
 a list of TrialWaveFunctions for multiple method More...
 
std::vector< ParticleSet::ParticleGradient * > G1
 
std::vector< ParticleSet::ParticleLaplacian * > L1
 
std::vector< GradTypeg1_old
 
std::vector< GradTypeg1_new
 
- Public Attributes inherited from QMCUpdateBase
int nSubSteps
 number of steps per measurement More...
 
DriverDebugChecks debug_checks_ = DriverDebugChecks::ALL_OFF
 determine additional checks for debugging purpose More...
 
std::string debug_checks_str_
 
IndexType MaxAge
 MaxAge>0 indicates branch is done. More...
 
IndexType nAccept
 counter for number of moves accepted More...
 
IndexType nReject
 counter for number of moves rejected More...
 
IndexType nAllRejected
 Total number of the steps when all the particle moves are rejected. More...
 
IndexType nNodeCrossing
 Total number of node crossings per block. More...
 
IndexType NonLocalMoveAccepted
 Total numer of non-local moves accepted. More...
 
RealType Tau
 timestep More...
 
RealType spinMass
 spin mass More...
 
bool UseDrift
 use Drift More...
 
RealType csoffset
 normalization offset for cs type runs. More...
 
TraceManagerTraces
 traces More...
 
WalkerLogCollectorwlog_collector
 
- Protected Member Functions inherited from QMCUpdateBase
RealType getNodeCorrection (const ParticleSet::ParticleGradient &g, ParticleSet::ParticlePos &gscaled)
 evaluate the ratio of scaled velocity and velocity More...
 
 QMCUpdateBase (const QMCUpdateBase &)=delete
 copy constructor (disabled) More...
 
- Static Protected Member Functions inherited from QMCUpdateBase
static void checkLogAndGL (ParticleSet &pset, TrialWaveFunction &twf, const std::string_view location)
 check logpsi and grad and lap against values computed from scratch More...
 
- Protected Attributes inherited from QMCUpdateBase
bool UpdatePbyP
 update particle-by-particle More...
 
IndexType NumPtcl
 number of particles More...
 
RealType m_oneover2tau
 Time-step factor $ 1/(2\tau)$. More...
 
RealType m_sqrttau
 Time-step factor $ \sqrt{\tau}$. More...
 
RealType m_tauovermass
 tau/mass More...
 
RealType m_r2max
 maximum displacement^2 More...
 
MCWalkerConfigurationW
 walker ensemble More...
 
TrialWaveFunctionPsi
 trial function More...
 
TrialWaveFunctionGuide
 guide function More...
 
QMCHamiltonianH
 Hamiltonian. More...
 
RandomBase< FullPrecRealType > & RandomGen
 random number generator More...
 
const BranchEngineTypebranchEngine
 branch engine, stateless reference to the one in QMCDriver More...
 
const DriftModifierBaseDriftModifier
 drift modifer, stateless reference to the one in QMCDriver More...
 
EstimatorManagerBaseEstimators
 estimator More...
 
ParameterSet myParams
 parameters More...
 
std::vector< RealTypeMassInvS
 1/Mass per species More...
 
std::vector< RealTypeMassInvP
 1/Mass per particle More...
 
std::vector< RealTypeSqrtTauOverMass
 sqrt(tau/Mass) per particle More...
 
ParticleSet::ParticlePos drift
 temporary storage for drift More...
 
ParticleSet::ParticlePos deltaR
 temporary storage for random displacement More...
 
ParticleSet::ParticleScalar deltaS
 temporart storage for spin displacement More...
 
ParticleSet::ParticleGradient G
 storage for differential gradients for PbyP update More...
 
ParticleSet::ParticleGradient dG
 
ParticleSet::ParticleLaplacian L
 storage for differential laplacians for PbyP update More...
 
ParticleSet::ParticleLaplacian dL
 

Constructor & Destructor Documentation

◆ CSVMCUpdateAll()

CSVMCUpdateAll ( MCWalkerConfiguration w,
std::vector< TrialWaveFunction *> &  psi,
std::vector< QMCHamiltonian *> &  h,
RandomBase< FullPrecRealType > &  rg 
)

Constructor.

Definition at line 33 of file CSVMCUpdateAll.cpp.

References QMCUpdateBase::UpdatePbyP.

37  : CSUpdateBase(w, psi, h, rg)
38 {
39  UpdatePbyP = false;
40 }
CSUpdateBase(MCWalkerConfiguration &w, std::vector< TrialWaveFunction *> &psi, std::vector< QMCHamiltonian *> &h, RandomBase< FullPrecRealType > &rg)
bool UpdatePbyP
update particle-by-particle

Member Function Documentation

◆ advanceWalker()

void advanceWalker ( Walker_t thisWalker,
bool  recompute 
)
overridevirtual

move a walker

Implements QMCUpdateBase.

Definition at line 42 of file CSVMCUpdateAll.cpp.

References Walker< t_traits, p_traits >::Age, CSUpdateBase::avgNorm, CSUpdateBase::cumNorm, QMCUpdateBase::deltaR, qmcplusplus::exp(), ParticleSet::G, CSUpdateBase::G1, Walker< t_traits, p_traits >::getPropertyBase(), CSUpdateBase::H1, CSUpdateBase::invsumratio, ParticleSet::L, CSUpdateBase::L1, CSUpdateBase::logpsi, qmcplusplus::makeGaussRandomWithEngine(), ParticleSet::makeMoveAllParticles(), QMCUpdateBase::MassInvS, Walker< t_traits, p_traits >::Multiplicity, QMCUpdateBase::nAccept, CSUpdateBase::nPsi, QMCUpdateBase::nReject, Walker< t_traits, p_traits >::Properties, CSUpdateBase::Psi1, ParticleSet::R, Walker< t_traits, p_traits >::R, Random, QMCUpdateBase::RandomGen, qmcplusplus::sqrt(), CSUpdateBase::sumratio, QMCUpdateBase::Tau, and QMCUpdateBase::W.

43 {
45  //create a 3N-Dimensional Gaussian with variance=1
47 
48  RealType tau_over_mass = std::sqrt(Tau * MassInvS[0]);
49 
50  if (!W.makeMoveAllParticles(thisWalker, deltaR, tau_over_mass))
51  {
52  for (int ipsi = 0; ipsi < nPsi; ipsi++)
53  H1[ipsi]->rejectedMove(W, thisWalker);
54  return;
55  }
56 
57  //Evaluate Psi and graidients and laplacians
58  //\f$\sum_i \ln(|psi_i|)\f$ and catching the sign separately
59  for (int ipsi = 0; ipsi < nPsi; ipsi++)
60  {
61  logpsi[ipsi] = Psi1[ipsi]->evaluateLog(W);
62  Psi1[ipsi]->L = W.L;
63  Psi1[ipsi]->G = W.G;
64 
65  *G1[ipsi] = W.G;
66  *L1[ipsi] = W.L;
67  sumratio[ipsi] = 1.0;
68  }
69  // Compute the sum over j of Psi^2[j]/Psi^2[i] for each i
70  for (int ipsi = 0; ipsi < nPsi - 1; ipsi++)
71  {
72  for (int jpsi = ipsi + 1; jpsi < nPsi; jpsi++)
73  {
74  RealType ratioij = avgNorm[ipsi] / avgNorm[jpsi] * std::exp(2.0 * (logpsi[jpsi] - logpsi[ipsi]));
75  sumratio[ipsi] += ratioij;
76  sumratio[jpsi] += 1.0 / ratioij;
77  }
78  }
79  for (int ipsi = 0; ipsi < nPsi; ipsi++)
80  {
81  invsumratio[ipsi] = 1.0 / sumratio[ipsi];
82  cumNorm[ipsi] += invsumratio[ipsi];
83  }
84 
85  for (int ipsi = 0; ipsi < nPsi; ipsi++)
86  cumNorm[ipsi] += invsumratio[ipsi];
87 
88  RealType g = sumratio[0] / thisWalker.Multiplicity * std::exp(2.0 * (logpsi[0] - thisWalker.Properties(WP::LOGPSI)));
89 
90  if (Random() > g)
91  {
92  thisWalker.Age++;
93  ++nReject;
94  for (int ipsi = 0; ipsi < nPsi; ipsi++)
95  H1[ipsi]->rejectedMove(W, thisWalker);
96  }
97  else
98  {
99  thisWalker.Age = 0;
100  thisWalker.Multiplicity = sumratio[0];
101  thisWalker.R = W.R;
102  for (int ipsi = 0; ipsi < nPsi; ipsi++)
103  {
104  W.L = *L1[ipsi];
105  W.G = *G1[ipsi];
106 
107  RealType et = H1[ipsi]->evaluate(W);
108  thisWalker.Properties(ipsi, WP::LOGPSI) = logpsi[ipsi];
109  thisWalker.Properties(ipsi, WP::SIGN) = Psi1[ipsi]->getPhase();
110  thisWalker.Properties(ipsi, WP::UMBRELLAWEIGHT) = invsumratio[ipsi];
111  thisWalker.Properties(ipsi, WP::LOCALENERGY) = et;
112  H1[ipsi]->auxHevaluate(W, thisWalker);
113  H1[ipsi]->saveProperty(thisWalker.getPropertyBase(ipsi));
114  }
115  ++nAccept;
116  }
117 }
std::vector< RealType > sumratio
Definition: CSUpdateBase.h:40
std::vector< RealType > cumNorm
Definition: CSUpdateBase.h:45
#define Random
ParticleSet::ParticlePos deltaR
temporary storage for random displacement
ParticleLaplacian L
laplacians of the particles
Definition: ParticleSet.h:85
std::vector< TrialWaveFunction * > Psi1
a list of TrialWaveFunctions for multiple method
Definition: CSUpdateBase.h:57
std::vector< RealType > logpsi
Definition: CSUpdateBase.h:39
WalkerProperties::Indexes WP
Definition: ParticleSet.cpp:34
std::vector< RealType > invsumratio
Definition: CSUpdateBase.h:41
ParticleGradient G
gradients of the particles
Definition: ParticleSet.h:83
RealType Tau
timestep
Definition: QMCUpdateBase.h:73
ParticlePos R
Position.
Definition: ParticleSet.h:79
std::vector< ParticleSet::ParticleGradient * > G1
Definition: CSUpdateBase.h:59
MakeReturn< UnaryNode< FnExp, typename CreateLeaf< Vector< T1, C1 > >::Leaf_t > >::Expression_t exp(const Vector< T1, C1 > &l)
MCWalkerConfiguration & W
walker ensemble
MakeReturn< UnaryNode< FnSqrt, typename CreateLeaf< Vector< T1, C1 > >::Leaf_t > >::Expression_t sqrt(const Vector< T1, C1 > &l)
QMCTraits::RealType RealType
RandomBase< FullPrecRealType > & RandomGen
random number generator
Indexes
an enum denoting index of physical properties
std::vector< RealType > avgNorm
Definition: CSUpdateBase.h:42
std::vector< ParticleSet::ParticleLaplacian * > L1
Definition: CSUpdateBase.h:60
IndexType nAccept
counter for number of moves accepted
Definition: QMCUpdateBase.h:63
IndexType nReject
counter for number of moves rejected
Definition: QMCUpdateBase.h:65
std::vector< RealType > MassInvS
1/Mass per species
bool makeMoveAllParticles(const Walker_t &awalker, const ParticlePos &deltaR, RealType dt)
move all the particles of a walker
std::vector< QMCHamiltonian * > H1
a list of QMCHamiltonians for multiple method
Definition: CSUpdateBase.h:55
void makeGaussRandomWithEngine(ParticleAttrib< TinyVector< T, D >> &a, RG &rng)

◆ qmcplusplus::CSVMCUpdatePbyP

class qmcplusplus::CSVMCUpdatePbyP


Implements the VMC algorithm

Definition at line 24 of file CSVMCUpdatePbyP.h.

+ Inheritance diagram for CSVMCUpdatePbyP:
+ Collaboration diagram for CSVMCUpdatePbyP:

Public Member Functions

 CSVMCUpdatePbyP (MCWalkerConfiguration &w, std::vector< TrialWaveFunction *> &psi, std::vector< QMCHamiltonian *> &h, RandomBase< FullPrecRealType > &rg)
 Constructor. More...
 
 ~CSVMCUpdatePbyP () override
 
void advanceWalker (Walker_t &thisWalker, bool recompute) override
 move a walker More...
 
- Public Member Functions inherited from CSUpdateBase
 CSUpdateBase (MCWalkerConfiguration &w, std::vector< TrialWaveFunction *> &psi, std::vector< QMCHamiltonian *> &h, RandomBase< FullPrecRealType > &rg)
 
 ~CSUpdateBase () override
 
void computeSumRatio (const std::vector< RealType > &logpsi, const std::vector< RealType > &avgNorm, std::vector< RealType > &sumratio)
 
void computeSumRatio (const Matrix< RealType > &ratioij, std::vector< RealType > &sumratio)
 
void computeSumRatio (const std::vector< RealType > &logpsi, const std::vector< RealType > &avgNorm, Matrix< RealType > &ratioij, std::vector< RealType > &sumratio)
 
void updateRatioMatrix (const std::vector< RealType > &ratio_pbyp, Matrix< RealType > &ratioij)
 
void resizeWorkSpace (int nw, int nptcls)
 
void updateNorms ()
 
void updateAvgWeights ()
 
void initCSWalkers (WalkerIter_t it, WalkerIter_t it_end, bool resetNorms)
 
void initCSWalkersForPbyP (WalkerIter_t it, WalkerIter_t it_end, bool resetNorms)
 
void updateCSWalkers (WalkerIter_t it, WalkerIter_t it_end)
 
- Public Member Functions inherited from QMCUpdateBase
 QMCUpdateBase (MCWalkerConfiguration &w, TrialWaveFunction &psi, QMCHamiltonian &h, RandomBase< FullPrecRealType > &rg)
 Constructor. More...
 
 QMCUpdateBase (MCWalkerConfiguration &w, TrialWaveFunction &psi, TrialWaveFunction &guide, QMCHamiltonian &h, RandomBase< FullPrecRealType > &rg)
 Alt Constructor. More...
 
virtual ~QMCUpdateBase ()
 destructor More...
 
RealType acceptRatio () const
 
void resetRun (BranchEngineType *brancher, EstimatorManagerBase *est, TraceManager *traces, const DriftModifierBase *driftmodifer)
 reset the QMCUpdateBase parameters More...
 
void resetRun2 (BranchEngineType *brancher, EstimatorManagerBase *est, TraceManager *traces, WalkerLogCollector *wlog_collector_, const DriftModifierBase *driftmodifer)
 
RealType getTau ()
 
void setTau (RealType t)
 
RealType getSpinMass ()
 
void setSpinMass (RealType m)
 
void getLogs (std::vector< RealType > &logs)
 
void set_step (int step)
 
void startRun (int blocks, bool record)
 start a run More...
 
void stopRun ()
 stop a run More...
 
void stopRun2 ()
 
void startBlock (int steps)
 prepare to start a block More...
 
void stopBlock (bool collectall=true)
 stop a block More...
 
void setMultiplicity (WalkerIter_t it, WalkerIter_t it_end)
 set the multiplicity of the walkers to branch More...
 
void setMultiplicity (Walker_t &awalker) const
 
virtual void initWalkersForPbyP (WalkerIter_t it, WalkerIter_t it_end)
 initialize Walker buffers for PbyP update More...
 
virtual void initWalkers (WalkerIter_t it, WalkerIter_t it_end)
 initialize Walker for walker update More...
 
virtual bool put (xmlNodePtr cur)
 process options More...
 
void accumulate (WalkerIter_t it, WalkerIter_t it_end)
 
virtual void advanceWalkers (WalkerIter_t it, WalkerIter_t it_end, bool recompute)
 advance walkers executed at each step More...
 
virtual RealType advanceWalkerForEE (Walker_t &w1, std::vector< PosType > &dR, std::vector< int > &iats, std::vector< int > &rs, std::vector< RealType > &ratios)
 
int RMC_checkIndex (int N, int NMax)
 
void RMC_checkWalkerBounds (WalkerIter_t &it, WalkerIter_t first, WalkerIter_t last)
 
RealType logBackwardGF (const ParticleSet::ParticlePos &displ)
 

Additional Inherited Members

- Public Types inherited from QMCUpdateBase
using Walker_t = MCWalkerConfiguration::Walker_t
 
using WalkerIter_t = MCWalkerConfiguration::iterator
 
using BranchEngineType = SimpleFixedNodeBranch
 
using mPosType = PosType
 
using mTensorType = TensorType
 
- Public Types inherited from QMCTraits
enum  { DIM = OHMMS_DIM, DIM_VGL = OHMMS_DIM + 2 }
 
using QTBase = QMCTypes< OHMMS_PRECISION, DIM >
 
using QTFull = QMCTypes< OHMMS_PRECISION_FULL, DIM >
 
using RealType = QTBase::RealType
 
using ComplexType = QTBase::ComplexType
 
using ValueType = QTBase::ValueType
 
using PosType = QTBase::PosType
 
using GradType = QTBase::GradType
 
using TensorType = QTBase::TensorType
 
using IndexType = OHMMS_INDEXTYPE
 define other types More...
 
using FullPrecRealType = QTFull::RealType
 
using FullPrecValueType = QTFull::ValueType
 
using PropertySetType = RecordNamedProperty< FullPrecRealType >
 define PropertyList_t More...
 
using PtclGrpIndexes = std::vector< std::pair< int, int > >
 
- Public Attributes inherited from CSUpdateBase
int nPsi
 
bool useDrift
 
std::vector< RealTypelogpsi
 
std::vector< RealTypesumratio
 
std::vector< RealTypeinvsumratio
 
std::vector< RealTypeavgNorm
 
std::vector< RealTypeavgWeight
 
std::vector< RealTypelogNorm
 
std::vector< RealTypecumNorm
 
std::vector< RealTypeinstRij
 
std::vector< RealTyperatio
 
Matrix< RealTyperatioIJ
 
std::string useDriftOption
 
Matrix< RealTypeRatioIJ
 
CSEnergyEstimatormultiEstimator
 multiple estimator More...
 
std::vector< QMCHamiltonian * > H1
 a list of QMCHamiltonians for multiple method More...
 
std::vector< TrialWaveFunction * > Psi1
 a list of TrialWaveFunctions for multiple method More...
 
std::vector< ParticleSet::ParticleGradient * > G1
 
std::vector< ParticleSet::ParticleLaplacian * > L1
 
std::vector< GradTypeg1_old
 
std::vector< GradTypeg1_new
 
- Public Attributes inherited from QMCUpdateBase
int nSubSteps
 number of steps per measurement More...
 
DriverDebugChecks debug_checks_ = DriverDebugChecks::ALL_OFF
 determine additional checks for debugging purpose More...
 
std::string debug_checks_str_
 
IndexType MaxAge
 MaxAge>0 indicates branch is done. More...
 
IndexType nAccept
 counter for number of moves accepted More...
 
IndexType nReject
 counter for number of moves rejected More...
 
IndexType nAllRejected
 Total number of the steps when all the particle moves are rejected. More...
 
IndexType nNodeCrossing
 Total number of node crossings per block. More...
 
IndexType NonLocalMoveAccepted
 Total numer of non-local moves accepted. More...
 
RealType Tau
 timestep More...
 
RealType spinMass
 spin mass More...
 
bool UseDrift
 use Drift More...
 
RealType csoffset
 normalization offset for cs type runs. More...
 
TraceManagerTraces
 traces More...
 
WalkerLogCollectorwlog_collector
 
- Protected Member Functions inherited from QMCUpdateBase
RealType getNodeCorrection (const ParticleSet::ParticleGradient &g, ParticleSet::ParticlePos &gscaled)
 evaluate the ratio of scaled velocity and velocity More...
 
 QMCUpdateBase (const QMCUpdateBase &)=delete
 copy constructor (disabled) More...
 
- Static Protected Member Functions inherited from QMCUpdateBase
static void checkLogAndGL (ParticleSet &pset, TrialWaveFunction &twf, const std::string_view location)
 check logpsi and grad and lap against values computed from scratch More...
 
- Protected Attributes inherited from QMCUpdateBase
bool UpdatePbyP
 update particle-by-particle More...
 
IndexType NumPtcl
 number of particles More...
 
RealType m_oneover2tau
 Time-step factor $ 1/(2\tau)$. More...
 
RealType m_sqrttau
 Time-step factor $ \sqrt{\tau}$. More...
 
RealType m_tauovermass
 tau/mass More...
 
RealType m_r2max
 maximum displacement^2 More...
 
MCWalkerConfigurationW
 walker ensemble More...
 
TrialWaveFunctionPsi
 trial function More...
 
TrialWaveFunctionGuide
 guide function More...
 
QMCHamiltonianH
 Hamiltonian. More...
 
RandomBase< FullPrecRealType > & RandomGen
 random number generator More...
 
const BranchEngineTypebranchEngine
 branch engine, stateless reference to the one in QMCDriver More...
 
const DriftModifierBaseDriftModifier
 drift modifer, stateless reference to the one in QMCDriver More...
 
EstimatorManagerBaseEstimators
 estimator More...
 
ParameterSet myParams
 parameters More...
 
std::vector< RealTypeMassInvS
 1/Mass per species More...
 
std::vector< RealTypeMassInvP
 1/Mass per particle More...
 
std::vector< RealTypeSqrtTauOverMass
 sqrt(tau/Mass) per particle More...
 
ParticleSet::ParticlePos drift
 temporary storage for drift More...
 
ParticleSet::ParticlePos deltaR
 temporary storage for random displacement More...
 
ParticleSet::ParticleScalar deltaS
 temporart storage for spin displacement More...
 
ParticleSet::ParticleGradient G
 storage for differential gradients for PbyP update More...
 
ParticleSet::ParticleGradient dG
 
ParticleSet::ParticleLaplacian L
 storage for differential laplacians for PbyP update More...
 
ParticleSet::ParticleLaplacian dL
 

Constructor & Destructor Documentation

◆ CSVMCUpdatePbyP()

CSVMCUpdatePbyP ( MCWalkerConfiguration w,
std::vector< TrialWaveFunction *> &  psi,
std::vector< QMCHamiltonian *> &  h,
RandomBase< FullPrecRealType > &  rg 
)

Constructor.

Definition at line 30 of file CSVMCUpdatePbyP.cpp.

34  : CSUpdateBase(w, psi, h, rg)
35 {}
CSUpdateBase(MCWalkerConfiguration &w, std::vector< TrialWaveFunction *> &psi, std::vector< QMCHamiltonian *> &h, RandomBase< FullPrecRealType > &rg)

◆ ~CSVMCUpdatePbyP()

~CSVMCUpdatePbyP ( )
override

Definition at line 37 of file CSVMCUpdatePbyP.cpp.

37 {}

Member Function Documentation

◆ advanceWalker()

void advanceWalker ( Walker_t thisWalker,
bool  recompute 
)
overridevirtual

move a walker

Implements QMCUpdateBase.

Definition at line 39 of file CSVMCUpdatePbyP.cpp.

References ParticleSet::accept_rejectMove(), CSUpdateBase::avgNorm, CSUpdateBase::computeSumRatio(), CSUpdateBase::cumNorm, Walker< t_traits, p_traits >::DataSet, QMCUpdateBase::deltaR, ParticleSet::donePbyP(), ParticleSet::first(), ParticleSet::G, CSUpdateBase::G1, Walker< t_traits, p_traits >::getPropertyBase(), ParticleSet::groups(), CSUpdateBase::H1, CSUpdateBase::invsumratio, ParticleSet::L, Walker< t_traits, p_traits >::L, CSUpdateBase::L1, ParticleSet::last(), ParticleSet::loadWalker(), CSUpdateBase::logpsi, qmcplusplus::makeGaussRandomWithEngine(), ParticleSet::makeMoveAndCheck(), QMCUpdateBase::MassInvS, Walker< t_traits, p_traits >::Multiplicity, QMCUpdateBase::nAccept, QMCUpdateBase::nAllRejected, norm(), CSUpdateBase::nPsi, QMCUpdateBase::nReject, QMCUpdateBase::nSubSteps, Walker< t_traits, p_traits >::Properties, CSUpdateBase::Psi1, QMCUpdateBase::RandomGen, CSUpdateBase::ratio, CSUpdateBase::RatioIJ, ParticleSet::saveWalker(), qmcplusplus::sqrt(), CSUpdateBase::sumratio, QMCUpdateBase::Tau, CSUpdateBase::updateRatioMatrix(), and QMCUpdateBase::W.

40 {
41  W.loadWalker(thisWalker, true);
42 
43  //First step, we initialize all Psis, and read up the value of logpsi
44  //from the last run.
45  for (int ipsi = 0; ipsi < nPsi; ipsi++)
46  {
47  Psi1[ipsi]->copyFromBuffer(W, thisWalker.DataSet);
48  logpsi[ipsi] = thisWalker.Properties(ipsi, WP::LOGPSI);
49  }
50 
51  //Now we compute sumratio and more importantly, ratioij.
53  for (int iter = 0; iter < nSubSteps; ++iter)
54  {
56  bool stucked = true;
57  for (int ig = 0; ig < W.groups(); ++ig) //loop over species
58  {
59  RealType sqrttau = std::sqrt(Tau * MassInvS[ig]);
60  for (int iat = W.first(ig); iat < W.last(ig); ++iat)
61  {
62  PosType dr = sqrttau * deltaR[iat];
63  //The move proposal for particle iat.
64  if (W.makeMoveAndCheck(iat, dr))
65  {
66  for (int ipsi = 0; ipsi < nPsi; ipsi++)
67  ratio[ipsi] = std::norm(Psi1[ipsi]->calcRatio(W, iat));
68  //Compute the ratio and acceptance probability.
69  RealType prob = 0;
70  for (int ipsi = 0; ipsi < nPsi; ipsi++)
71  prob += ratio[ipsi] / sumratio[ipsi];
72 
73  bool is_accepted = false;
74  if (RandomGen() < prob)
75  {
76  is_accepted = true;
77  stucked = false;
78  ++nAccept;
79  for (int ipsi = 0; ipsi < nPsi; ipsi++)
80  Psi1[ipsi]->acceptMove(W, iat, true);
81 
82  //Now we update ratioIJ.
85  }
86  else
87  {
88  ++nReject;
89  for (int ipsi = 0; ipsi < nPsi; ipsi++)
90  Psi1[ipsi]->rejectMove(iat);
91  }
92 
93  W.accept_rejectMove(iat, is_accepted);
94  }
95  else //reject illegal moves
96  ++nReject;
97  } //iat
98  } //ig for the species
99  if (stucked)
100  {
101  ++nAllRejected;
102  }
103  for (int ipsi = 0; ipsi < nPsi; ipsi++)
104  Psi1[ipsi]->completeUpdates();
105  }
106 
107  W.donePbyP();
108 
109  for (int ipsi = 0; ipsi < nPsi; ipsi++)
110  {
111  //now recompute logpsi, gradients, and laplacians of the new R. Save them.
112  logpsi[ipsi] = Psi1[ipsi]->updateBuffer(W, thisWalker.DataSet, recompute);
113  W.saveWalker(thisWalker);
114  //Save G and L for this wavefunction in the working G1, L1 arrays.
115  *G1[ipsi] = thisWalker.G;
116  *L1[ipsi] = thisWalker.L;
117  //Set G and L for this wavefunction.
118  Psi1[ipsi]->G = W.G;
119  Psi1[ipsi]->L = W.L;
120  }
121 
123  for (int ipsi = 0; ipsi < nPsi; ipsi++)
124  {
125  invsumratio[ipsi] = sumratio[ipsi];
126  cumNorm[ipsi] += 1.0 / invsumratio[ipsi];
127  }
128 
129  for (int ipsi = 0; ipsi < nPsi; ipsi++)
130  {
131  //Now reload the G and L associated with ipsi into the walker and particle set.
132  //This is required for correct calculation of kinetic energy.
133  thisWalker.G = *G1[ipsi];
134  thisWalker.L = *L1[ipsi];
135  W.L = thisWalker.L;
136  W.G = thisWalker.G;
137  thisWalker.Properties(ipsi, WP::LOCALENERGY) = H1[ipsi]->evaluate(W);
138  thisWalker.Properties(ipsi, WP::LOGPSI) = logpsi[ipsi];
139  thisWalker.Properties(ipsi, WP::SIGN) = Psi1[ipsi]->getPhase();
140  thisWalker.Properties(ipsi, WP::UMBRELLAWEIGHT) = 1.0 / sumratio[ipsi];
141  //Use Multiplicity as a temporary container for sumratio.
142  thisWalker.Multiplicity = sumratio[0];
143  H1[ipsi]->auxHevaluate(W, thisWalker);
144  H1[ipsi]->saveProperty(thisWalker.getPropertyBase(ipsi));
145  }
146 }
std::vector< RealType > sumratio
Definition: CSUpdateBase.h:40
std::vector< RealType > cumNorm
Definition: CSUpdateBase.h:45
void computeSumRatio(const std::vector< RealType > &logpsi, const std::vector< RealType > &avgNorm, std::vector< RealType > &sumratio)
void updateRatioMatrix(const std::vector< RealType > &ratio_pbyp, Matrix< RealType > &ratioij)
int first(int igroup) const
return the first index of a group i
Definition: ParticleSet.h:514
ParticleSet::ParticlePos deltaR
temporary storage for random displacement
ParticleLaplacian L
laplacians of the particles
Definition: ParticleSet.h:85
std::vector< TrialWaveFunction * > Psi1
a list of TrialWaveFunctions for multiple method
Definition: CSUpdateBase.h:57
QMCTraits::PosType PosType
int groups() const
return the number of groups
Definition: ParticleSet.h:511
std::vector< RealType > logpsi
Definition: CSUpdateBase.h:39
double norm(const zVec &c)
Definition: VectorOps.h:118
std::vector< RealType > invsumratio
Definition: CSUpdateBase.h:41
ParticleGradient G
gradients of the particles
Definition: ParticleSet.h:83
void saveWalker(Walker_t &awalker)
save this to awalker
RealType Tau
timestep
Definition: QMCUpdateBase.h:73
void accept_rejectMove(Index_t iat, bool accepted, bool forward_mode=true)
accept or reject a proposed move Two operation modes: The using and updating distance tables via Part...
std::vector< ParticleSet::ParticleGradient * > G1
Definition: CSUpdateBase.h:59
Matrix< RealType > RatioIJ
Definition: CSUpdateBase.h:51
int last(int igroup) const
return the last index of a group i
Definition: ParticleSet.h:517
MCWalkerConfiguration & W
walker ensemble
void loadWalker(Walker_t &awalker, bool pbyp)
load a Walker_t to the current ParticleSet
int nSubSteps
number of steps per measurement
Definition: QMCUpdateBase.h:56
MakeReturn< UnaryNode< FnSqrt, typename CreateLeaf< Vector< T1, C1 > >::Leaf_t > >::Expression_t sqrt(const Vector< T1, C1 > &l)
QMCTraits::RealType RealType
RandomBase< FullPrecRealType > & RandomGen
random number generator
std::vector< RealType > ratio
Definition: CSUpdateBase.h:47
std::vector< RealType > avgNorm
Definition: CSUpdateBase.h:42
bool makeMoveAndCheck(Index_t iat, const SingleParticlePos &displ)
move the iat-th particle to active_pos_
std::vector< ParticleSet::ParticleLaplacian * > L1
Definition: CSUpdateBase.h:60
IndexType nAccept
counter for number of moves accepted
Definition: QMCUpdateBase.h:63
IndexType nReject
counter for number of moves rejected
Definition: QMCUpdateBase.h:65
std::vector< RealType > MassInvS
1/Mass per species
std::vector< QMCHamiltonian * > H1
a list of QMCHamiltonians for multiple method
Definition: CSUpdateBase.h:55
void donePbyP(bool skipSK=false)
update structure factor and unmark active_ptcl_
IndexType nAllRejected
Total number of the steps when all the particle moves are rejected.
Definition: QMCUpdateBase.h:67
void makeGaussRandomWithEngine(ParticleAttrib< TinyVector< T, D >> &a, RG &rng)

◆ qmcplusplus::CSVMCUpdatePbyPWithDriftFast

class qmcplusplus::CSVMCUpdatePbyPWithDriftFast


Implements the VMC algorithm with drift.

Definition at line 43 of file CSVMCUpdatePbyP.h.

+ Inheritance diagram for CSVMCUpdatePbyPWithDriftFast:
+ Collaboration diagram for CSVMCUpdatePbyPWithDriftFast:

Public Member Functions

 CSVMCUpdatePbyPWithDriftFast (MCWalkerConfiguration &w, std::vector< TrialWaveFunction *> &psi, std::vector< QMCHamiltonian *> &h, RandomBase< FullPrecRealType > &rg)
 Constructor. More...
 
 ~CSVMCUpdatePbyPWithDriftFast () override
 
void advanceWalker (Walker_t &thisWalker, bool recompute) override
 move a walker More...
 
- Public Member Functions inherited from CSUpdateBase
 CSUpdateBase (MCWalkerConfiguration &w, std::vector< TrialWaveFunction *> &psi, std::vector< QMCHamiltonian *> &h, RandomBase< FullPrecRealType > &rg)
 
 ~CSUpdateBase () override
 
void computeSumRatio (const std::vector< RealType > &logpsi, const std::vector< RealType > &avgNorm, std::vector< RealType > &sumratio)
 
void computeSumRatio (const Matrix< RealType > &ratioij, std::vector< RealType > &sumratio)
 
void computeSumRatio (const std::vector< RealType > &logpsi, const std::vector< RealType > &avgNorm, Matrix< RealType > &ratioij, std::vector< RealType > &sumratio)
 
void updateRatioMatrix (const std::vector< RealType > &ratio_pbyp, Matrix< RealType > &ratioij)
 
void resizeWorkSpace (int nw, int nptcls)
 
void updateNorms ()
 
void updateAvgWeights ()
 
void initCSWalkers (WalkerIter_t it, WalkerIter_t it_end, bool resetNorms)
 
void initCSWalkersForPbyP (WalkerIter_t it, WalkerIter_t it_end, bool resetNorms)
 
void updateCSWalkers (WalkerIter_t it, WalkerIter_t it_end)
 
- Public Member Functions inherited from QMCUpdateBase
 QMCUpdateBase (MCWalkerConfiguration &w, TrialWaveFunction &psi, QMCHamiltonian &h, RandomBase< FullPrecRealType > &rg)
 Constructor. More...
 
 QMCUpdateBase (MCWalkerConfiguration &w, TrialWaveFunction &psi, TrialWaveFunction &guide, QMCHamiltonian &h, RandomBase< FullPrecRealType > &rg)
 Alt Constructor. More...
 
virtual ~QMCUpdateBase ()
 destructor More...
 
RealType acceptRatio () const
 
void resetRun (BranchEngineType *brancher, EstimatorManagerBase *est, TraceManager *traces, const DriftModifierBase *driftmodifer)
 reset the QMCUpdateBase parameters More...
 
void resetRun2 (BranchEngineType *brancher, EstimatorManagerBase *est, TraceManager *traces, WalkerLogCollector *wlog_collector_, const DriftModifierBase *driftmodifer)
 
RealType getTau ()
 
void setTau (RealType t)
 
RealType getSpinMass ()
 
void setSpinMass (RealType m)
 
void getLogs (std::vector< RealType > &logs)
 
void set_step (int step)
 
void startRun (int blocks, bool record)
 start a run More...
 
void stopRun ()
 stop a run More...
 
void stopRun2 ()
 
void startBlock (int steps)
 prepare to start a block More...
 
void stopBlock (bool collectall=true)
 stop a block More...
 
void setMultiplicity (WalkerIter_t it, WalkerIter_t it_end)
 set the multiplicity of the walkers to branch More...
 
void setMultiplicity (Walker_t &awalker) const
 
virtual void initWalkersForPbyP (WalkerIter_t it, WalkerIter_t it_end)
 initialize Walker buffers for PbyP update More...
 
virtual void initWalkers (WalkerIter_t it, WalkerIter_t it_end)
 initialize Walker for walker update More...
 
virtual bool put (xmlNodePtr cur)
 process options More...
 
void accumulate (WalkerIter_t it, WalkerIter_t it_end)
 
virtual void advanceWalkers (WalkerIter_t it, WalkerIter_t it_end, bool recompute)
 advance walkers executed at each step More...
 
virtual RealType advanceWalkerForEE (Walker_t &w1, std::vector< PosType > &dR, std::vector< int > &iats, std::vector< int > &rs, std::vector< RealType > &ratios)
 
int RMC_checkIndex (int N, int NMax)
 
void RMC_checkWalkerBounds (WalkerIter_t &it, WalkerIter_t first, WalkerIter_t last)
 
RealType logBackwardGF (const ParticleSet::ParticlePos &displ)
 

Additional Inherited Members

- Public Types inherited from QMCUpdateBase
using Walker_t = MCWalkerConfiguration::Walker_t
 
using WalkerIter_t = MCWalkerConfiguration::iterator
 
using BranchEngineType = SimpleFixedNodeBranch
 
using mPosType = PosType
 
using mTensorType = TensorType
 
- Public Types inherited from QMCTraits
enum  { DIM = OHMMS_DIM, DIM_VGL = OHMMS_DIM + 2 }
 
using QTBase = QMCTypes< OHMMS_PRECISION, DIM >
 
using QTFull = QMCTypes< OHMMS_PRECISION_FULL, DIM >
 
using RealType = QTBase::RealType
 
using ComplexType = QTBase::ComplexType
 
using ValueType = QTBase::ValueType
 
using PosType = QTBase::PosType
 
using GradType = QTBase::GradType
 
using TensorType = QTBase::TensorType
 
using IndexType = OHMMS_INDEXTYPE
 define other types More...
 
using FullPrecRealType = QTFull::RealType
 
using FullPrecValueType = QTFull::ValueType
 
using PropertySetType = RecordNamedProperty< FullPrecRealType >
 define PropertyList_t More...
 
using PtclGrpIndexes = std::vector< std::pair< int, int > >
 
- Public Attributes inherited from CSUpdateBase
int nPsi
 
bool useDrift
 
std::vector< RealTypelogpsi
 
std::vector< RealTypesumratio
 
std::vector< RealTypeinvsumratio
 
std::vector< RealTypeavgNorm
 
std::vector< RealTypeavgWeight
 
std::vector< RealTypelogNorm
 
std::vector< RealTypecumNorm
 
std::vector< RealTypeinstRij
 
std::vector< RealTyperatio
 
Matrix< RealTyperatioIJ
 
std::string useDriftOption
 
Matrix< RealTypeRatioIJ
 
CSEnergyEstimatormultiEstimator
 multiple estimator More...
 
std::vector< QMCHamiltonian * > H1
 a list of QMCHamiltonians for multiple method More...
 
std::vector< TrialWaveFunction * > Psi1
 a list of TrialWaveFunctions for multiple method More...
 
std::vector< ParticleSet::ParticleGradient * > G1
 
std::vector< ParticleSet::ParticleLaplacian * > L1
 
std::vector< GradTypeg1_old
 
std::vector< GradTypeg1_new
 
- Public Attributes inherited from QMCUpdateBase
int nSubSteps
 number of steps per measurement More...
 
DriverDebugChecks debug_checks_ = DriverDebugChecks::ALL_OFF
 determine additional checks for debugging purpose More...
 
std::string debug_checks_str_
 
IndexType MaxAge
 MaxAge>0 indicates branch is done. More...
 
IndexType nAccept
 counter for number of moves accepted More...
 
IndexType nReject
 counter for number of moves rejected More...
 
IndexType nAllRejected
 Total number of the steps when all the particle moves are rejected. More...
 
IndexType nNodeCrossing
 Total number of node crossings per block. More...
 
IndexType NonLocalMoveAccepted
 Total numer of non-local moves accepted. More...
 
RealType Tau
 timestep More...
 
RealType spinMass
 spin mass More...
 
bool UseDrift
 use Drift More...
 
RealType csoffset
 normalization offset for cs type runs. More...
 
TraceManagerTraces
 traces More...
 
WalkerLogCollectorwlog_collector
 
- Protected Member Functions inherited from QMCUpdateBase
RealType getNodeCorrection (const ParticleSet::ParticleGradient &g, ParticleSet::ParticlePos &gscaled)
 evaluate the ratio of scaled velocity and velocity More...
 
 QMCUpdateBase (const QMCUpdateBase &)=delete
 copy constructor (disabled) More...
 
- Static Protected Member Functions inherited from QMCUpdateBase
static void checkLogAndGL (ParticleSet &pset, TrialWaveFunction &twf, const std::string_view location)
 check logpsi and grad and lap against values computed from scratch More...
 
- Protected Attributes inherited from QMCUpdateBase
bool UpdatePbyP
 update particle-by-particle More...
 
IndexType NumPtcl
 number of particles More...
 
RealType m_oneover2tau
 Time-step factor $ 1/(2\tau)$. More...
 
RealType m_sqrttau
 Time-step factor $ \sqrt{\tau}$. More...
 
RealType m_tauovermass
 tau/mass More...
 
RealType m_r2max
 maximum displacement^2 More...
 
MCWalkerConfigurationW
 walker ensemble More...
 
TrialWaveFunctionPsi
 trial function More...
 
TrialWaveFunctionGuide
 guide function More...
 
QMCHamiltonianH
 Hamiltonian. More...
 
RandomBase< FullPrecRealType > & RandomGen
 random number generator More...
 
const BranchEngineTypebranchEngine
 branch engine, stateless reference to the one in QMCDriver More...
 
const DriftModifierBaseDriftModifier
 drift modifer, stateless reference to the one in QMCDriver More...
 
EstimatorManagerBaseEstimators
 estimator More...
 
ParameterSet myParams
 parameters More...
 
std::vector< RealTypeMassInvS
 1/Mass per species More...
 
std::vector< RealTypeMassInvP
 1/Mass per particle More...
 
std::vector< RealTypeSqrtTauOverMass
 sqrt(tau/Mass) per particle More...
 
ParticleSet::ParticlePos drift
 temporary storage for drift More...
 
ParticleSet::ParticlePos deltaR
 temporary storage for random displacement More...
 
ParticleSet::ParticleScalar deltaS
 temporart storage for spin displacement More...
 
ParticleSet::ParticleGradient G
 storage for differential gradients for PbyP update More...
 
ParticleSet::ParticleGradient dG
 
ParticleSet::ParticleLaplacian L
 storage for differential laplacians for PbyP update More...
 
ParticleSet::ParticleLaplacian dL
 

Constructor & Destructor Documentation

◆ CSVMCUpdatePbyPWithDriftFast()

CSVMCUpdatePbyPWithDriftFast ( MCWalkerConfiguration w,
std::vector< TrialWaveFunction *> &  psi,
std::vector< QMCHamiltonian *> &  h,
RandomBase< FullPrecRealType > &  rg 
)

Constructor.

UpdatePbyP With Drift Fast.

Definition at line 150 of file CSVMCUpdatePbyP.cpp.

References APP_ABORT.

154  : CSUpdateBase(w, psi, h, rg){APP_ABORT("CSVMCUpdatePbyPWithDriftFast currently not working. Please eliminate \
155  drift option, or choose all electron moves instead.")}
CSUpdateBase(MCWalkerConfiguration &w, std::vector< TrialWaveFunction *> &psi, std::vector< QMCHamiltonian *> &h, RandomBase< FullPrecRealType > &rg)
#define APP_ABORT(msg)
Widely used but deprecated fatal error macros from legacy code.
Definition: AppAbort.h:27

◆ ~CSVMCUpdatePbyPWithDriftFast()

Definition at line 157 of file CSVMCUpdatePbyP.cpp.

158 {}

Member Function Documentation

◆ advanceWalker()

void advanceWalker ( Walker_t thisWalker,
bool  recompute 
)
overridevirtual

move a walker

Implements QMCUpdateBase.

Definition at line 160 of file CSVMCUpdatePbyP.cpp.

160 {}

◆ qmcplusplus::DMC

class qmcplusplus::DMC

DMC driver using OpenMP paragra.

This is the main DMC driver with MPI/OpenMP loops over the walkers.

Definition at line 30 of file DMC.h.

+ Inheritance diagram for DMC:
+ Collaboration diagram for DMC:

Public Member Functions

 DMC (const ProjectData &project_data, MCWalkerConfiguration &w, TrialWaveFunction &psi, QMCHamiltonian &h, UPtrVector< RandomBase< QMCTraits::FullPrecRealType >> &rngs, Communicate *comm, bool enable_profiling)
 Constructor. More...
 
bool run () override
 
bool put (xmlNodePtr cur) override
 
void setTau (RealType i)
 
QMCRunType getRunType () override
 
- Public Member Functions inherited from QMCDriver
 QMCDriver (const ProjectData &project_data, MCWalkerConfiguration &w, TrialWaveFunction &psi, QMCHamiltonian &h, Communicate *comm, const std::string &QMC_driver_type, bool enable_profiling=false)
 Constructor. More...
 
 ~QMCDriver () override
 
int current () const
 return current step More...
 
void setUpdateMode (bool pbyp) override
 set the update mode More...
 
void setStatus (const std::string &aname, const std::string &h5name, bool append) override
 Set the status of the QMCDriver. More...
 
void add_H_and_Psi (QMCHamiltonian *h, TrialWaveFunction *psi) override
 add QMCHamiltonian/TrialWaveFunction pair for multiple More...
 
void process (xmlNodePtr cur) override
 initialize with xmlNode More...
 
xmlNodePtr getQMCNode ()
 return a xmlnode with update More...
 
void putWalkers (std::vector< xmlNodePtr > &wset) override
 Read walker configurations from *.config.h5 files. More...
 
void putTraces (xmlNodePtr txml) override
 
void requestTraces (bool traces) override
 
void putWalkerLogs (xmlNodePtr wlxml) override
 
void requestWalkerLogs (bool allow_walker_logs_) override
 
std::string getEngineName () override
 
template<class PDT >
void setValue (const std::string &aname, PDT x)
 
void setBranchEngine (std::unique_ptr< BranchEngineType > &&be) override
 set the BranchEngineType More...
 
std::unique_ptr< BranchEngineTypegetBranchEngine () override
 return BranchEngineType* More...
 
int addObservable (const std::string &aname)
 
RealType getObservable (int i)
 
void setTau (RealType i)
 
void setWalkerOffsets ()
 set global offsets of the walkers More...
 
RefVector< RandomBase< FullPrecRealType > > getRngRefs () const
 return the random generators More...
 
RandomBase< FullPrecRealType > & getRng (int i) override
 return the i-th random generator More...
 
unsigned long getDriverMode () override
 
- Public Member Functions inherited from QMCDriverInterface
virtual ~QMCDriverInterface ()
 
virtual void setBranchEngine (std::unique_ptr< BranchEngineType > &&be)
 
- Public Member Functions inherited from MPIObjectBase
 MPIObjectBase (Communicate *c)
 constructor with communicator More...
 
int rank () const
 return the rank of the communicator More...
 
int getGroupID () const
 return the group id of the communicator More...
 
CommunicategetCommunicator () const
 return myComm More...
 
CommunicategetCommRef () const
 return a TEMPORARY reference to Communicate More...
 
mpi_comm_type getMPI () const
 return MPI communicator if one wants to use MPI directly More...
 
bool is_manager () const
 return true if the rank == 0 More...
 
const std::string & getName () const
 return the name More...
 
void setName (const std::string &aname)
 
- Public Member Functions inherited from CloneManager
 CloneManager ()
 Constructor. More...
 
virtual ~CloneManager ()
 virtual destructor More...
 
void makeClones (MCWalkerConfiguration &w, TrialWaveFunction &psi, QMCHamiltonian &ham)
 
void makeClones (MCWalkerConfiguration &w, std::vector< TrialWaveFunction *> &psi, std::vector< QMCHamiltonian *> &ham)
 
void makeClones (MCWalkerConfiguration &wg, TrialWaveFunction &guide)
 
void makeClones (TrialWaveFunction &guide)
 
RealType acceptRatio () const
 

Private Member Functions

void resetUpdateEngines ()
 
 DMC (const DMC &)=delete
 Copy Constructor (disabled) More...
 
DMCoperator= (const DMC &)=delete
 Copy operator (disabled). More...
 

Private Attributes

UPtrVector< RandomBase< QMCTraits::FullPrecRealType > > & rngs_
 
IndexType KillNodeCrossing
 Index to determine what to do when node crossing is detected. More...
 
IndexType BranchInterval
 Interval between branching. More...
 
std::string BranchInfo
 hdf5 file name for Branch conditions More...
 
std::string KillWalker
 input std::string to determine kill walkers or not More...
 
std::string SwapWalkers
 input std::string to determine swap walkers among mpi processors More...
 
std::string L2
 input to control diffusion with L2 operator More...
 
std::string Reconfiguration
 input std::string to determine to use reconfiguration More...
 
std::string NonLocalMove
 input std::string to determine to use nonlocal move More...
 
IndexType mover_MaxAge
 input to control maximum age allowed for walkers. More...
 

Additional Inherited Members

- Public Types inherited from QMCDriver
enum  { QMC_UPDATE_MODE, QMC_MULTIPLE, QMC_OPTIMIZE, QMC_WARMUP }
 enumeration coupled with QMCMode More...
 
using Walker_t = MCWalkerConfiguration::Walker_t
 
using Buffer_t = Walker_t::Buffer_t
 
using FullPrecRealType = QMCTraits::FullPrecRealType
 
- Public Types inherited from QMCDriverInterface
using BranchEngineType = SimpleFixedNodeBranch
 
using FullPrecRealType = QMCTraits::FullPrecRealType
 
- Public Types inherited from QMCTraits
enum  { DIM = OHMMS_DIM, DIM_VGL = OHMMS_DIM + 2 }
 
using QTBase = QMCTypes< OHMMS_PRECISION, DIM >
 
using QTFull = QMCTypes< OHMMS_PRECISION_FULL, DIM >
 
using RealType = QTBase::RealType
 
using ComplexType = QTBase::ComplexType
 
using ValueType = QTBase::ValueType
 
using PosType = QTBase::PosType
 
using GradType = QTBase::GradType
 
using TensorType = QTBase::TensorType
 
using IndexType = OHMMS_INDEXTYPE
 define other types More...
 
using FullPrecRealType = QTFull::RealType
 
using FullPrecValueType = QTFull::ValueType
 
using PropertySetType = RecordNamedProperty< FullPrecRealType >
 define PropertyList_t More...
 
using PtclGrpIndexes = std::vector< std::pair< int, int > >
 
- Public Types inherited from MPIObjectBase
using mpi_comm_type = Communicate::mpi_comm_type
 
- Static Public Member Functions inherited from CloneManager
static void clearClones ()
 
- Public Attributes inherited from QMCDriver
std::bitset< QMC_MODE_MAXqmc_driver_mode
 bits to classify QMCDriver More...
 
bool allow_traces
 whether to allow traces More...
 
xmlNodePtr traces_xml
 traces xml More...
 
bool allow_walker_logs
 whether to allow traces More...
 
xmlNodePtr walker_logs_xml
 traces xml More...
 
EstimatorManagerBaseEstimators
 Observables manager. More...
 
std::unique_ptr< TraceManagerTraces
 Traces manager. More...
 
std::unique_ptr< WalkerLogManagerwlog_manager_
 Traces manager. More...
 
- Protected Member Functions inherited from QMCDriver
bool putQMCInfo (xmlNodePtr cur)
 Parses the xml input file for parameter definitions for a single qmc simulation. More...
 
void addWalkers (int nwalkers)
 Add walkers to the end of the ensemble of walkers. More...
 
void recordBlock (int block) override
 record the state of the block More...
 
bool finalize (int block, bool dumpwalkers=true)
 finalize a qmc section More...
 
std::string getRotationName (std::string RootName)
 
std::string getLastRotationName (std::string RootName)
 
const std::string & get_root_name () const override
 
- Protected Member Functions inherited from CloneManager
RefVector< WalkerLogCollectorgetWalkerLogCollectorRefs ()
 
- Protected Attributes inherited from QMCDriver
const ProjectDataproject_data_
 top-level project data information More...
 
std::unique_ptr< BranchEngineTypebranchEngine
 branch engine More...
 
DriftModifierBaseDriftModifier
 drift modifer More...
 
bool ResetRandom
 randomize it More...
 
bool AppendRun
 flag to append or restart the run More...
 
bool DumpConfig
 flag to turn off dumping configurations More...
 
bool IsQMCDriver
 true, if it is a real QMC engine More...
 
int MyCounter
 the number of times this QMCDriver is executed More...
 
int kDelay
 the number to delay updates by More...
 
int Period4CheckPoint
 period of dumping walker configurations and everything else for restart More...
 
int Period4CheckProperties
 period of dumping walker positions and IDs for Forward Walking More...
 
int Period4WalkerDump
 period of recording walker configurations More...
 
int Period4ConfigDump
 period of recording walker positions and IDs for forward walking afterwards More...
 
IndexType CurrentStep
 current step More...
 
IndexType nBlocks
 maximum number of blocks More...
 
IndexType nSteps
 maximum number of steps More...
 
IndexType nSubSteps
 number of steps between a step: VMCs do not evaluate energies More...
 
IndexType nWarmupSteps
 number of warmup steps More...
 
IndexType nAccept
 counter for number of moves accepted More...
 
IndexType nReject
 counter for number of moves /rejected More...
 
IndexType nBlocksBetweenRecompute
 the number of blocks between recomptePsi More...
 
IndexType nTargetWalkers
 the number of walkers More...
 
IndexType nTargetSamples
 the number of saved samples More...
 
IndexType nStepsBetweenSamples
 alternate method of setting QMC run parameters More...
 
RealType nSamplesPerThread
 samples per thread More...
 
RealType nTargetPopulation
 target population More...
 
RealType Tau
 timestep More...
 
int MaxCPUSecs
 maximum cpu in secs More...
 
RealType m_oneover2tau
 Time-step factor $ 1/(2\tau)$. More...
 
RealType m_sqrttau
 Time-step factor $ \sqrt{\tau}$. More...
 
xmlNodePtr qmcNode
 pointer to qmc node in xml file More...
 
const std::string QMCType
 type of QMC driver More...
 
std::string h5FileRoot
 the root of h5File More...
 
std::string RootName
 root of all the output files More...
 
ParameterSet m_param
 store any parameter that has to be read from a file More...
 
MCWalkerConfigurationW
 walker ensemble More...
 
TrialWaveFunctionPsi
 trial function More...
 
QMCHamiltonianH
 Hamiltonian. More...
 
std::unique_ptr< HDFWalkerOutputwOut
 record engine for walkers More...
 
std::vector< TrialWaveFunction * > Psi1
 a list of TrialWaveFunctions for multiple method More...
 
std::vector< QMCHamiltonian * > H1
 a list of QMCHamiltonians for multiple method More...
 
UPtrVector< RandomBase< FullPrecRealType > > Rng
 Random number generators. More...
 
std::vector< xmlNodePtr > mcwalkerNodePtr
 a list of mcwalkerset element More...
 
ParticleSet::ParticlePos drift
 temporary storage for drift More...
 
ParticleSet::ParticlePos deltaR
 temporary storage for random displacement More...
 
RealType SpinMass
 spin mass for spinor calcs More...
 
int rotation
 
- Protected Attributes inherited from MPIObjectBase
CommunicatemyComm
 pointer to Communicate More...
 
std::string ClassName
 class Name More...
 
std::string myName
 name of the object More...
 
- Protected Attributes inherited from CloneManager
const IndexType NumThreads
 number of threads More...
 
std::vector< QMCUpdateBase * > Movers
 update engines More...
 
std::vector< EstimatorManagerBase * > estimatorClones
 estimator managers More...
 
std::vector< TraceManager * > traceClones
 trace managers More...
 
UPtrVector< WalkerLogCollectorwlog_collectors
 trace collectors More...
 
UPtrVector< CSUpdateBaseCSMovers
 
std::vector< int > wPerRank
 Walkers per MPI rank. More...
 
- Static Protected Attributes inherited from CloneManager
static UPtrVector< MCWalkerConfigurationwClones_uptr
 walkers More...
 
static std::vector< MCWalkerConfiguration * > wClones
 
static UPtrVector< MCWalkerConfigurationwgClones
 
static UPtrVector< TrialWaveFunctionpsiClones_uptr
 trial wavefunctions More...
 
static std::vector< TrialWaveFunction * > psiClones
 
static UPtrVector< TrialWaveFunctionguideClones_uptr
 guide wavefunctions More...
 
static std::vector< TrialWaveFunction * > guideClones
 
static UPtrVector< QMCHamiltonianhClones_uptr
 Hamiltonians. More...
 
static std::vector< QMCHamiltonian * > hClones
 
static std::vector< UPtrVector< MCWalkerConfiguration > > WPoolClones_uptr
 
static std::vector< std::vector< MCWalkerConfiguration * > > WPoolClones
 
static std::vector< UPtrVector< TrialWaveFunction > > PsiPoolClones_uptr
 
static std::vector< std::vector< TrialWaveFunction * > > PsiPoolClones
 
static std::vector< UPtrVector< QMCHamiltonian > > HPoolClones_uptr
 
static std::vector< std::vector< QMCHamiltonian * > > HPoolClones
 

Constructor & Destructor Documentation

◆ DMC() [1/2]

DMC ( const ProjectData project_data,
MCWalkerConfiguration w,
TrialWaveFunction psi,
QMCHamiltonian h,
UPtrVector< RandomBase< QMCTraits::FullPrecRealType >> &  rngs,
Communicate comm,
bool  enable_profiling 
)

Constructor.

Definition at line 44 of file DMC.cpp.

References ParameterSet::add(), DMC::KillWalker, DMC::L2, QMCDriver::m_param, DMC::mover_MaxAge, DMC::NonLocalMove, QMCDriver::qmc_driver_mode, QMCDriver::QMC_UPDATE_MODE, DMC::Reconfiguration, and QMCDriver::RootName.

51  : QMCDriver(project_data, w, psi, h, comm, "DMC", enable_profiling),
52  rngs_(rngs),
54  BranchInterval(-1),
55  L2("no"),
56  Reconfiguration("no"),
57  mover_MaxAge(-1)
58 {
59  RootName = "dmc";
61  m_param.add(KillWalker, "killnode");
62  m_param.add(Reconfiguration, "reconfiguration");
63  //m_param.add(BranchInterval,"branchInterval");
64  m_param.add(NonLocalMove, "nonlocalmove");
65  m_param.add(NonLocalMove, "nonlocalmoves");
66  m_param.add(mover_MaxAge, "MaxAge");
67  m_param.add(L2, "L2_diffusion");
68 }
QMCDriver(const ProjectData &project_data, MCWalkerConfiguration &w, TrialWaveFunction &psi, QMCHamiltonian &h, Communicate *comm, const std::string &QMC_driver_type, bool enable_profiling=false)
Constructor.
Definition: QMCDriver.cpp:44
std::string RootName
root of all the output files
Definition: QMCDriver.h:317
IndexType mover_MaxAge
input to control maximum age allowed for walkers.
Definition: DMC.h:68
UPtrVector< RandomBase< QMCTraits::FullPrecRealType > > & rngs_
Definition: DMC.h:49
ParameterSet m_param
store any parameter that has to be read from a file
Definition: QMCDriver.h:320
std::bitset< QMC_MODE_MAX > qmc_driver_mode
bits to classify QMCDriver
Definition: QMCDriver.h:93
std::string Reconfiguration
input std::string to determine to use reconfiguration
Definition: DMC.h:64
void add(PDT &aparam, const std::string &aname_in, std::vector< PDT > candidate_values={}, TagStatus status=TagStatus::OPTIONAL)
add a new parameter corresponding to an xmlNode <parameter>
IndexType BranchInterval
Interval between branching.
Definition: DMC.h:54
std::string KillWalker
input std::string to determine kill walkers or not
Definition: DMC.h:58
std::string L2
input to control diffusion with L2 operator
Definition: DMC.h:62
IndexType KillNodeCrossing
Index to determine what to do when node crossing is detected.
Definition: DMC.h:52
std::string NonLocalMove
input std::string to determine to use nonlocal move
Definition: DMC.h:66

◆ DMC() [2/2]

DMC ( const DMC )
privatedelete

Copy Constructor (disabled)

Member Function Documentation

◆ getRunType()

QMCRunType getRunType ( )
inlineoverridevirtual

Implements QMCDriverInterface.

Definition at line 45 of file DMC.h.

References qmcplusplus::DMC.

45 { return QMCRunType::DMC; }
DMC type: dmc, dmc-ptcl.

◆ operator=()

DMC& operator= ( const DMC )
privatedelete

Copy operator (disabled).

◆ put()

bool put ( xmlNodePtr  cur)
overridevirtual

Implements QMCDriverInterface.

Definition at line 339 of file DMC.cpp.

References ParameterSet::add(), DMC::BranchInterval, and ParameterSet::put().

340 {
341  BranchInterval = -1;
342  ParameterSet p;
343  p.add(BranchInterval, "branchInterval");
344  p.add(BranchInterval, "branchinterval");
345  p.add(BranchInterval, "substeps");
346  p.add(BranchInterval, "subSteps");
347  p.add(BranchInterval, "sub_steps");
348  p.put(q);
349 
350  //app_log() << "\n DMC::put qmc_counter=" << qmc_common.qmc_counter << " my_counter=" << MyCounter<< std::endl;
351  //app_log() << " timestep = " << Tau << std::endl;
352  //app_log() << " blocks = " << nBlocks << std::endl;
353  //app_log() << " steps = " << nSteps << std::endl;
354  //app_log() << " current = " << CurrentStep << std::endl;
355  //app_log() << " walkers/mpi = " << W.getActiveWalkers() << std::endl << std::endl;
356  //app_log().flush();
357  return true;
358 }
bool put(std::istream &is) override
read from std::istream
Definition: ParameterSet.h:42
class to handle a set of parameters
Definition: ParameterSet.h:27
void add(PDT &aparam, const std::string &aname_in, std::vector< PDT > candidate_values={}, TagStatus status=TagStatus::OPTIONAL)
add a new parameter corresponding to an xmlNode <parameter>
IndexType BranchInterval
Interval between branching.
Definition: DMC.h:54

◆ resetUpdateEngines()

void resetUpdateEngines ( )
private

Definition at line 70 of file DMC.cpp.

References APP_ABORT, qmcplusplus::app_log(), WalkerConfigurations::begin(), QMCDriver::branchEngine, DMC::BranchInterval, copy(), MCWalkerConfiguration::createWalkers(), QMCDriver::DriftModifier, Timer::elapsed(), CloneManager::estimatorClones, QMCDriver::Estimators, FairDivideLow(), WalkerConfigurations::getActiveWalkers(), QMCDriver::H, CloneManager::hClones, ParticleSet::isSpinor(), DMC::KillNodeCrossing, DMC::L2, MCWalkerConfiguration::loadEnsemble(), CloneManager::makeClones(), DMC::mover_MaxAge, CloneManager::Movers, QMCDriver::nBlocks, QMCDriver::nSteps, CloneManager::NumThreads, QMCDriver::Psi, CloneManager::psiClones, QMCDriver::qmc_driver_mode, QMCDriver::QMC_UPDATE_MODE, QMCDriver::qmcNode, DMC::Reconfiguration, QMCDriver::Rng, DMC::rngs_, QMCDriver::setWalkerOffsets(), QMCDriver::SpinMass, CloneManager::traceClones, QMCDriver::Traces, QMCDriver::W, CloneManager::wClones, CloneManager::wlog_collectors, QMCDriver::wlog_manager_, and CloneManager::wPerRank.

Referenced by DMC::run().

71 {
72  ReportEngine PRE("DMC", "resetUpdateEngines");
73  bool fixW = (Reconfiguration == "runwhileincorrect");
74  if (Reconfiguration != "no" && Reconfiguration != "runwhileincorrect")
75  throw std::runtime_error("Reconfiguration is currently broken and gives incorrect results. Use dynamic "
76  "population control by setting reconfiguration=\"no\" or removing the reconfiguration "
77  "option from the DMC input section. If accessing the broken reconfiguration code path "
78  "is still desired, set reconfiguration to \"runwhileincorrect\" instead of \"yes\".");
79  makeClones(W, Psi, H);
80  Timer init_timer;
81  bool spinor = false;
82  if (Movers.empty())
83  {
86  int nw_multi = branchEngine->initWalkerController(W, fixW, false);
87  if (nw_multi > 1)
88  {
89  W.createWalkers((nw_multi - 1) * W.getActiveWalkers());
91  }
92  //if(qmc_driver_mode[QMC_UPDATE_MODE]) W.clearAuxDataSet();
93  Movers.resize(NumThreads, nullptr);
94  Rng.resize(NumThreads);
95  estimatorClones.resize(NumThreads, nullptr);
96  traceClones.resize(NumThreads, nullptr);
99 
100  {
101  //log file
102  std::ostringstream o;
103  o << " Initial partition of walkers on a node: ";
104  copy(wPerRank.begin(), wPerRank.end(), std::ostream_iterator<int>(o, " "));
105  o << "\n";
107  {
108  o << " Updates by particle-by-particle moves";
109  if (L2 == "yes")
110  app_log() << "Using DMCUpdatePbyPL2" << std::endl;
111  else
112  app_log() << "Using DMCUpdatePbyPWithRejectionFast" << std::endl;
113  }
114  else
115  o << " Updates by walker moves";
116  // Appears to be set in constructor reported here and used nowhere
117  if (KillNodeCrossing)
118  o << "\n Walkers are killed when a node crossing is detected";
119  else
120  o << "\n DMC moves are rejected when a node crossing is detected";
121  app_log() << o.str() << std::endl;
122  }
123 
124  // hdf_archive::hdf_archive() is not thread-safe
125  for (int ip = 0; ip < NumThreads; ++ip)
126  estimatorClones[ip] = new EstimatorManagerBase(*Estimators);
127 
128 #pragma omp parallel for
129  for (int ip = 0; ip < NumThreads; ++ip)
130  {
131  estimatorClones[ip]->setCollectionMode(false);
132 #if !defined(REMOVE_TRACEMANAGER)
133  traceClones[ip] = Traces->makeClone();
134 #endif
135  wlog_collectors[ip] = wlog_manager_->makeCollector();
136  Rng[ip] = rngs_[ip]->makeClone();
137  hClones[ip]->setRandomGenerator(Rng[ip].get());
138  if (W.isSpinor())
139  {
140  spinor = true;
142  {
143  Movers[ip] = new SODMCUpdatePbyPWithRejectionFast(*wClones[ip], *psiClones[ip], *hClones[ip], *Rng[ip]);
144  Movers[ip]->setSpinMass(SpinMass);
145  Movers[ip]->put(qmcNode);
146  //Movers[ip]->resetRun(branchEngine.get(), estimatorClones[ip], traceClones[ip], DriftModifier);
147  Movers[ip]->resetRun2(branchEngine.get(), estimatorClones[ip], traceClones[ip], wlog_collectors[ip].get(), DriftModifier);
148  Movers[ip]->initWalkersForPbyP(W.begin() + wPerRank[ip], W.begin() + wPerRank[ip + 1]);
149  }
150  else
151  {
152  APP_ABORT("SODMC Driver Mode must be PbyP\n");
153  }
154  }
155  else
156  {
158  {
159  if (L2 == "yes")
160  Movers[ip] = new DMCUpdatePbyPL2(*wClones[ip], *psiClones[ip], *hClones[ip], *Rng[ip]);
161  else
162  Movers[ip] = new DMCUpdatePbyPWithRejectionFast(*wClones[ip], *psiClones[ip], *hClones[ip], *Rng[ip]);
163 
164  Movers[ip]->put(qmcNode);
165  //Movers[ip]->resetRun(branchEngine.get(), estimatorClones[ip], traceClones[ip], DriftModifier);
166  Movers[ip]->resetRun2(branchEngine.get(), estimatorClones[ip], traceClones[ip], wlog_collectors[ip].get(), DriftModifier);
167  Movers[ip]->initWalkersForPbyP(W.begin() + wPerRank[ip], W.begin() + wPerRank[ip + 1]);
168  }
169  else
170  {
171  if (KillNodeCrossing)
172  Movers[ip] = new DMCUpdateAllWithKill(*wClones[ip], *psiClones[ip], *hClones[ip], *Rng[ip]);
173  else
174  Movers[ip] = new DMCUpdateAllWithRejection(*wClones[ip], *psiClones[ip], *hClones[ip], *Rng[ip]);
175  Movers[ip]->put(qmcNode);
176  //Movers[ip]->resetRun(branchEngine.get(), estimatorClones[ip], traceClones[ip], DriftModifier);
177  Movers[ip]->resetRun2(branchEngine.get(), estimatorClones[ip], traceClones[ip], wlog_collectors[ip].get(), DriftModifier);
178  Movers[ip]->initWalkers(W.begin() + wPerRank[ip], W.begin() + wPerRank[ip + 1]);
179  }
180  }
181  }
182  }
183 #if !defined(REMOVE_TRACEMANAGER)
184  else
185  {
186 #pragma omp parallel for
187  for (int ip = 0; ip < NumThreads; ++ip)
188  traceClones[ip]->transfer_state_from(*Traces);
189  }
190 #endif
191  if (spinor)
192  app_log() << " Spins treated as dynamic variable with SpinMass: " << SpinMass << std::endl;
193 
194  branchEngine->checkParameters(W);
195  int mxage = mover_MaxAge;
196  if (fixW)
197  {
198  if (BranchInterval < 0)
199  BranchInterval = 1;
200  mxage = (mover_MaxAge < 0) ? 0 : mover_MaxAge;
201  for (int ip = 0; ip < Movers.size(); ++ip)
202  Movers[ip]->MaxAge = mxage;
203  }
204  else
205  {
206  if (BranchInterval < 0)
207  BranchInterval = 1;
208  int miage = (qmc_driver_mode[QMC_UPDATE_MODE]) ? 1 : 5;
209  mxage = (mover_MaxAge < 0) ? miage : mover_MaxAge;
210  for (int i = 0; i < NumThreads; ++i)
211  Movers[i]->MaxAge = mxage;
212  }
213  {
214  std::ostringstream o;
215  if (fixW)
216  o << " Fixed population using reconfiguration method\n";
217  else
218  o << " Fluctuating population\n";
219  o << " Persistent walkers are killed after " << mxage << " MC sweeps\n";
220  o << " BranchInterval = " << BranchInterval << "\n";
221  o << " Steps per block = " << nSteps << "\n";
222  o << " Number of blocks = " << nBlocks << "\n";
223  app_log() << o.str() << std::endl;
224  }
225  app_log() << " DMC Engine Initialization = " << init_timer.elapsed() << " secs" << std::endl;
226 }
UPtrVector< WalkerLogCollector > wlog_collectors
trace collectors
Definition: CloneManager.h:79
static std::vector< TrialWaveFunction * > psiClones
Definition: CloneManager.h:65
std::vector< int > wPerRank
Walkers per MPI rank.
Definition: CloneManager.h:91
size_t getActiveWalkers() const
return the number of active walkers
static std::vector< MCWalkerConfiguration * > wClones
Definition: CloneManager.h:61
std::ostream & app_log()
Definition: OutputManager.h:65
xmlNodePtr qmcNode
pointer to qmc node in xml file
Definition: QMCDriver.h:310
std::vector< QMCUpdateBase * > Movers
update engines
Definition: CloneManager.h:73
IndexType mover_MaxAge
input to control maximum age allowed for walkers.
Definition: DMC.h:68
RealType SpinMass
spin mass for spinor calcs
Definition: QMCDriver.h:353
UPtrVector< RandomBase< QMCTraits::FullPrecRealType > > & rngs_
Definition: DMC.h:49
void loadEnsemble()
load SampleStack data to the current list of walker configurations
std::unique_ptr< TraceManager > Traces
Traces manager.
Definition: QMCDriver.h:195
void FairDivideLow(int ntot, int npart, IV &adist)
partition ntot elements among npart
Definition: FairDivide.h:114
void copy(const Array< T1, 3 > &src, Array< T2, 3 > &dest)
Definition: Blitz.h:639
IndexType nSteps
maximum number of steps
Definition: QMCDriver.h:269
std::bitset< QMC_MODE_MAX > qmc_driver_mode
bits to classify QMCDriver
Definition: QMCDriver.h:93
std::unique_ptr< BranchEngineType > branchEngine
branch engine
Definition: QMCDriver.h:218
std::vector< EstimatorManagerBase * > estimatorClones
estimator managers
Definition: CloneManager.h:75
std::string Reconfiguration
input std::string to determine to use reconfiguration
Definition: DMC.h:64
const IndexType NumThreads
number of threads
Definition: CloneManager.h:54
QMCHamiltonian & H
Hamiltonian.
Definition: QMCDriver.h:329
DriftModifierBase * DriftModifier
drift modifer
Definition: QMCDriver.h:220
#define APP_ABORT(msg)
Widely used but deprecated fatal error macros from legacy code.
Definition: AppAbort.h:27
void makeClones(MCWalkerConfiguration &w, TrialWaveFunction &psi, QMCHamiltonian &ham)
MCWalkerConfiguration & W
walker ensemble
Definition: QMCDriver.h:323
static std::vector< QMCHamiltonian * > hClones
Definition: CloneManager.h:71
EstimatorManagerBase * Estimators
Observables manager.
Definition: QMCDriver.h:192
TrialWaveFunction & Psi
trial function
Definition: QMCDriver.h:326
IndexType nBlocks
maximum number of blocks
Definition: QMCDriver.h:266
void createWalkers(int numWalkers)
create numWalkers Walkers
std::vector< TraceManager * > traceClones
trace managers
Definition: CloneManager.h:77
void setWalkerOffsets()
set global offsets of the walkers
Definition: QMCDriver.cpp:370
IndexType BranchInterval
Interval between branching.
Definition: DMC.h:54
UPtrVector< RandomBase< FullPrecRealType > > Rng
Random number generators.
Definition: QMCDriver.h:341
std::unique_ptr< WalkerLogManager > wlog_manager_
Traces manager.
Definition: QMCDriver.h:198
std::string L2
input to control diffusion with L2 operator
Definition: DMC.h:62
IndexType KillNodeCrossing
Index to determine what to do when node crossing is detected.
Definition: DMC.h:52
iterator begin()
return the first iterator

◆ run()

bool run ( )
overridevirtual

Implements QMCDriverInterface.

Definition at line 228 of file DMC.cpp.

References CloneManager::acceptRatio(), qmcplusplus::app_log(), Communicate::bcast(), QMCDriver::branchEngine, DMC::BranchInterval, ParticleSet::Collectables, QMCDriver::CurrentStep, QMCDriver::DumpConfig, QMCDriver::Estimators, FairDivideLow(), QMCDriver::finalize(), WalkerConfigurations::getActiveWalkers(), Communicate::getName(), CloneManager::getWalkerLogCollectorRefs(), QMCDriver::MaxCPUSecs, CloneManager::Movers, MPIObjectBase::myComm, QMCDriver::nBlocks, QMCDriver::nBlocksBetweenRecompute, QMCDriver::nSteps, CloneManager::NumThreads, omp_get_thread_num(), QMCDriver::Period4CheckPoint, QMCDriver::Period4CheckProperties, QMCDriver::qmc_driver_mode, QMCDriver::QMC_UPDATE_MODE, Communicate::rank(), DMC::Reconfiguration, QMCDriver::recordBlock(), DMC::resetUpdateEngines(), QMCDriver::Rng, DMC::rngs_, qmcplusplus::run_time_manager, EstimatorManagerBase::setCollectionMode(), PooledData< T >::size(), LoopTimer< CLOCK >::start(), EstimatorManagerBase::start(), EstimatorManagerBase::startBlock(), LoopTimer< CLOCK >::stop(), EstimatorManagerBase::stop(), EstimatorManagerBase::stopBlock(), CloneManager::traceClones, QMCDriver::Traces, QMCDriver::W, CloneManager::wClones, QMCDriver::wlog_manager_, and CloneManager::wPerRank.

Referenced by qmcplusplus::TEST_CASE().

229 {
230  LoopTimer<> dmc_loop;
231 
232  bool variablePop = (Reconfiguration == "no");
234  //estimator does not need to collect data
237  for (int ip = 0; ip < NumThreads; ip++)
238  Movers[ip]->startRun(nBlocks, false);
239 #if !defined(REMOVE_TRACEMANAGER)
240  Traces->startRun(nBlocks, traceClones);
241 #endif
243  IndexType block = 0;
245  int sample = 0;
246 
247  RunTimeControl<> runtimeControl(run_time_manager, MaxCPUSecs, myComm->getName(), myComm->rank() == 0);
248 
249  do // block
250  {
251  dmc_loop.start();
253  for (int ip = 0; ip < NumThreads; ip++)
254  Movers[ip]->startBlock(nSteps);
255 
256  for (IndexType step = 0; step < nSteps; ++step, CurrentStep += BranchInterval)
257  {
258  // if(storeConfigs && (CurrentStep%storeConfigs == 0)) {
259  // ForwardWalkingHistory.storeConfigsForForwardWalking(W);
260  // W.resetWalkerParents();
261  // }
262 
263 #pragma omp parallel
264  {
265  int ip = omp_get_thread_num();
266  Movers[ip]->set_step(sample);
267  bool recompute = (step + 1 == nSteps && nBlocksBetweenRecompute && (1 + block) % nBlocksBetweenRecompute == 0 &&
269  wClones[ip]->resetCollectables();
270  const size_t nw = W.getActiveWalkers();
271 #pragma omp for nowait
272  for (size_t iw = 0; iw < nw; ++iw)
273  {
274  Walker_t& thisWalker(*W[iw]);
275  Movers[ip]->advanceWalker(thisWalker, recompute);
276  }
277  }
278 
279  //Collectables are weighted but not yet normalized
280  if (W.Collectables.size())
281  {
282  // only when collectable is not empty, need to generalize for W != wClones[0]
283  for (int ip = 1; ip < NumThreads; ++ip)
284  W.Collectables += wClones[ip]->Collectables;
285  }
286  branchEngine->branch(CurrentStep, W);
287  // if(storeConfigs && (CurrentStep%storeConfigs == 0)) {
288  // ForwardWalkingHistory.storeConfigsForForwardWalking(W);
289  // W.resetWalkerParents();
290  // }
291  if (variablePop)
293  sample++;
294  }
295  // branchEngine->debugFWconfig();
297 #if !defined(REMOVE_TRACEMANAGER)
298  Traces->write_buffers(traceClones, block);
299 #endif
300  wlog_manager_->writeBuffers();
301  block++;
302  if (DumpConfig && block % Period4CheckPoint == 0)
303  {
304  for (int ip = 0; ip < NumThreads; ip++)
305  rngs_[ip] = Rng[ip]->makeClone();
306  }
307  recordBlock(block);
308  dmc_loop.stop();
309 
310  bool stop_requested = false;
311  // Rank 0 decides whether the time limit was reached
312  if (!myComm->rank())
313  stop_requested = runtimeControl.checkStop(dmc_loop);
314  myComm->bcast(stop_requested);
315 
316  if (stop_requested)
317  {
318  if (!myComm->rank())
319  app_log() << runtimeControl.generateStopMessage("DMC", block - 1);
320  run_time_manager.markStop();
321  break;
322  }
323 
324  } while (block < nBlocks);
325 
326  for (int ip = 0; ip < NumThreads; ip++)
327  rngs_[ip] = Rng[ip]->makeClone();
328  Estimators->stop();
329  for (int ip = 0; ip < NumThreads; ++ip)
330  Movers[ip]->stopRun2();
331 #if !defined(REMOVE_TRACEMANAGER)
332  Traces->stopRun();
333 #endif
334  wlog_manager_->stopRun();
335  return finalize(nBlocks);
336 }
size_type size() const
return the size of the data
Definition: PooledData.h:48
int MaxCPUSecs
maximum cpu in secs
Definition: QMCDriver.h:302
std::vector< int > wPerRank
Walkers per MPI rank.
Definition: CloneManager.h:91
int rank() const
return the rank
Definition: Communicate.h:116
size_t getActiveWalkers() const
return the number of active walkers
void recordBlock(int block) override
record the state of the block
Definition: QMCDriver.cpp:307
bool DumpConfig
flag to turn off dumping configurations
Definition: QMCDriver.h:226
static std::vector< MCWalkerConfiguration * > wClones
Definition: CloneManager.h:61
std::ostream & app_log()
Definition: OutputManager.h:65
void resetUpdateEngines()
Definition: DMC.cpp:70
RunTimeManager< ChronoClock > run_time_manager
IndexType CurrentStep
current step
Definition: QMCDriver.h:263
MCWalkerConfiguration::Walker_t Walker_t
Definition: QMCDriver.h:83
std::vector< QMCUpdateBase * > Movers
update engines
Definition: CloneManager.h:73
UPtrVector< RandomBase< QMCTraits::FullPrecRealType > > & rngs_
Definition: DMC.h:49
std::unique_ptr< TraceManager > Traces
Traces manager.
Definition: QMCDriver.h:195
void FairDivideLow(int ntot, int npart, IV &adist)
partition ntot elements among npart
Definition: FairDivide.h:114
omp_int_t omp_get_thread_num()
Definition: OpenMP.h:25
IndexType nSteps
maximum number of steps
Definition: QMCDriver.h:269
void startBlock(int steps)
start a block
bool finalize(int block, bool dumpwalkers=true)
finalize a qmc section
Definition: QMCDriver.cpp:318
const std::string & getName() const
Definition: Communicate.h:131
void setCollectionMode(bool collect)
set CollectSum
std::bitset< QMC_MODE_MAX > qmc_driver_mode
bits to classify QMCDriver
Definition: QMCDriver.h:93
Communicate * myComm
pointer to Communicate
Definition: MPIObjectBase.h:62
std::unique_ptr< BranchEngineType > branchEngine
branch engine
Definition: QMCDriver.h:218
std::string Reconfiguration
input std::string to determine to use reconfiguration
Definition: DMC.h:64
const IndexType NumThreads
number of threads
Definition: CloneManager.h:54
MCWalkerConfiguration & W
walker ensemble
Definition: QMCDriver.h:323
OHMMS_INDEXTYPE IndexType
define other types
Definition: Configuration.h:65
Buffer_t Collectables
observables in addition to those registered in Properties/PropertyList
Definition: ParticleSet.h:126
EstimatorManagerBase * Estimators
Observables manager.
Definition: QMCDriver.h:192
int Period4CheckPoint
period of dumping walker configurations and everything else for restart
Definition: QMCDriver.h:242
void stopBlock(RealType accept, bool collectall=true)
stop a block
RealType acceptRatio() const
void bcast(T &)
IndexType nBlocks
maximum number of blocks
Definition: QMCDriver.h:266
std::vector< TraceManager * > traceClones
trace managers
Definition: CloneManager.h:77
int Period4CheckProperties
period of dumping walker positions and IDs for Forward Walking
Definition: QMCDriver.h:249
RefVector< WalkerLogCollector > getWalkerLogCollectorRefs()
IndexType BranchInterval
Interval between branching.
Definition: DMC.h:54
UPtrVector< RandomBase< FullPrecRealType > > Rng
Random number generators.
Definition: QMCDriver.h:341
std::unique_ptr< WalkerLogManager > wlog_manager_
Traces manager.
Definition: QMCDriver.h:198
IndexType nBlocksBetweenRecompute
the number of blocks between recomptePsi
Definition: QMCDriver.h:284
void start(int blocks, bool record=true)
start a run

◆ setTau()

void setTau ( RealType  i)

Member Data Documentation

◆ BranchInfo

std::string BranchInfo
private

hdf5 file name for Branch conditions

Definition at line 56 of file DMC.h.

◆ BranchInterval

IndexType BranchInterval
private

Interval between branching.

Definition at line 54 of file DMC.h.

Referenced by DMC::put(), DMC::resetUpdateEngines(), and DMC::run().

◆ KillNodeCrossing

IndexType KillNodeCrossing
private

Index to determine what to do when node crossing is detected.

Definition at line 52 of file DMC.h.

Referenced by DMC::resetUpdateEngines().

◆ KillWalker

std::string KillWalker
private

input std::string to determine kill walkers or not

Definition at line 58 of file DMC.h.

Referenced by DMC::DMC().

◆ L2

std::string L2
private

input to control diffusion with L2 operator

Definition at line 62 of file DMC.h.

Referenced by DMC::DMC(), and DMC::resetUpdateEngines().

◆ mover_MaxAge

IndexType mover_MaxAge
private

input to control maximum age allowed for walkers.

Definition at line 68 of file DMC.h.

Referenced by DMC::DMC(), and DMC::resetUpdateEngines().

◆ NonLocalMove

std::string NonLocalMove
private

input std::string to determine to use nonlocal move

Definition at line 66 of file DMC.h.

Referenced by DMC::DMC().

◆ Reconfiguration

std::string Reconfiguration
private

input std::string to determine to use reconfiguration

Definition at line 64 of file DMC.h.

Referenced by DMC::DMC(), DMC::resetUpdateEngines(), and DMC::run().

◆ rngs_

Definition at line 49 of file DMC.h.

Referenced by DMC::resetUpdateEngines(), and DMC::run().

◆ SwapWalkers

std::string SwapWalkers
private

input std::string to determine swap walkers among mpi processors

Definition at line 60 of file DMC.h.

◆ qmcplusplus::DMCBatched

class qmcplusplus::DMCBatched


Implements a DMC using particle-by-particle threaded and batched moves.

Definition at line 35 of file DMCBatched.h.

+ Inheritance diagram for DMCBatched:
+ Collaboration diagram for DMCBatched:

Public Types

using Base = QMCDriverNew
 
using FullPrecRealType = QMCTraits::FullPrecRealType
 
using PosType = QMCTraits::PosType
 
using ParticlePositions = PtclOnLatticeTraits::ParticlePos
 
- Public Types inherited from QMCDriverNew
enum  { QMC_UPDATE_MODE, QMC_MULTIPLE, QMC_OPTIMIZE, QMC_WARMUP }
 separate but similar to QMCModeEnum More...
 
using RealType = QMCTraits::RealType
 
using IndexType = QMCTraits::IndexType
 
using FullPrecRealType = QMCTraits::FullPrecRealType
 
using MCPWalker = MCPopulation::MCPWalker
 
using WFBuffer = MCPopulation::WFBuffer
 
using SetNonLocalMoveHandler = std::function< void(QMCHamiltonian &)>
 
- Public Types inherited from QMCDriverInterface
using BranchEngineType = SimpleFixedNodeBranch
 
using FullPrecRealType = QMCTraits::FullPrecRealType
 
- Public Types inherited from MPIObjectBase
using mpi_comm_type = Communicate::mpi_comm_type
 

Public Member Functions

 DMCBatched (const ProjectData &project_data, QMCDriverInput &&qmcdriver_input, const std::optional< EstimatorManagerInput > &global_emi, DMCDriverInput &&input, WalkerConfigurations &wc, MCPopulation &&pop, Communicate *comm)
 Constructor. More...
 
 DMCBatched (const DMCBatched &)=delete
 Copy Constructor (disabled) More...
 
DMCBatchedoperator= (const DMCBatched &)=delete
 Copy operator (disabled). More...
 
 DMCBatched (DMCBatched &&)=default
 
 ~DMCBatched () override
 
void process (xmlNodePtr cur) override
 DMCBatched driver will eventually ignore cur. More...
 
bool run () override
 
QMCRunType getRunType () override
 
void setNonLocalMoveHandler (QMCHamiltonian &hamiltonian)
 
- Public Member Functions inherited from QMCDriverNew
 QMCDriverNew (const ProjectData &project_data, QMCDriverInput &&input, const std::optional< EstimatorManagerInput > &global_emi, WalkerConfigurations &wc, MCPopulation &&population, const std::string timer_prefix, Communicate *comm, const std::string &QMC_driver_type)
 Constructor. More...
 
 QMCDriverNew (QMCDriverNew &&)=default
 Move Constructor. More...
 
 QMCDriverNew (const QMCDriverNew &)=delete
 Copy Constructor (disabled). More...
 
QMCDriverNewoperator= (const QMCDriverNew &)=delete
 Copy operator (disabled). More...
 
 ~QMCDriverNew () override
 
bool putQMCInfo (xmlNodePtr cur)
 
void makeLocalWalkers (int nwalkers, RealType reserve)
 Adjust populations local walkers to this number. More...
 
DriftModifierBaseget_drift_modifier () const
 
void recordBlock (int block) override
 record the state of the block More...
 
bool finalize (int block, bool dumpwalkers=true)
 finalize a qmc section More...
 
IndexType current () const
 return current step More...
 
void setStatus (const std::string &aname, const std::string &h5name, bool append) override
 Set the status of the QMCDriver. More...
 
void add_H_and_Psi (QMCHamiltonian *h, TrialWaveFunction *psi) override
 
void createRngsStepContexts (int num_crowds)
 Creates Random Number generators for crowds and step contexts. More...
 
void putWalkers (std::vector< xmlNodePtr > &wset) override
 Read walker configurations from *.config.h5 files. More...
 
RefVector< RandomBase< FullPrecRealType > > getRngRefs () const
 
RandomBase< FullPrecRealType > & getRng (int i) override
 return the i-th random generator More...
 
std::string getEngineName () override
 intended for logging output and debugging you should base behavior on type preferably at compile time or if necessary at runtime using and protected by dynamic cast. More...
 
unsigned long getDriverMode () override
 
IndexType get_num_living_walkers () const
 
IndexType get_num_dead_walkers () const
 
const QMCDriverInputgetQMCDriverInput () const
 
bool put (xmlNodePtr cur) override
 
More...
 
void setUpdateMode (bool pbyp) override
 should be set in input don't see a reason to set individually More...
 
void putTraces (xmlNodePtr txml) override
 
void requestTraces (bool allow_traces) override
 
void putWalkerLogs (xmlNodePtr wlxml) override
 
void requestWalkerLogs (bool allow_walker_logs_) override
 
- Public Member Functions inherited from QMCDriverInterface
virtual ~QMCDriverInterface ()
 
virtual void setBranchEngine (std::unique_ptr< BranchEngineType > &&be)
 
virtual std::unique_ptr< BranchEngineTypegetBranchEngine ()
 
- Public Member Functions inherited from MPIObjectBase
 MPIObjectBase (Communicate *c)
 constructor with communicator More...
 
int rank () const
 return the rank of the communicator More...
 
int getGroupID () const
 return the group id of the communicator More...
 
CommunicategetCommunicator () const
 return myComm More...
 
CommunicategetCommRef () const
 return a TEMPORARY reference to Communicate More...
 
mpi_comm_type getMPI () const
 return MPI communicator if one wants to use MPI directly More...
 
bool is_manager () const
 return true if the rank == 0 More...
 
const std::string & getName () const
 return the name More...
 
void setName (const std::string &aname)
 

Static Public Member Functions

static void runDMCStep (int crowd_id, const StateForThread &sft, DriverTimers &timers, DMCTimers &dmc_timers, UPtrVector< ContextForSteps > &move_context, UPtrVector< Crowd > &crowds)
 
- Static Public Member Functions inherited from QMCDriverNew
static void initialLogEvaluation (int crowd_id, UPtrVector< Crowd > &crowds, UPtrVector< ContextForSteps > &step_context)
 
template<typename RT , CoordsType CT>
static void scaleBySqrtTau (const TauParams< RT, CT > &taus, MCCoords< CT > &coords)
 
template<typename RT , CoordsType CT>
static void computeLogGreensFunction (const MCCoords< CT > &coords, const TauParams< RT, CT > &taus, std::vector< QMCTraits::RealType > &log_gb)
 calculates Green Function from displacements stored in MCCoords [param, out] log_g More...
 

Static Private Member Functions

template<CoordsType CT>
static void advanceWalkers (const StateForThread &sft, Crowd &crowd, DriverTimers &timers, DMCTimers &dmc_timers, ContextForSteps &move_context, bool recompute, bool accumulate_this_step)
 

Private Attributes

const DMCDriverInput dmcdriver_input_
 
DMCTimers dmc_timers_
 I think its better if these have there own type and variable name. More...
 
IndexType branch_interval_
 Interval between branching. More...
 
std::unique_ptr< SFNBranchbranch_engine_
 branch engine More...
 
std::unique_ptr< WalkerControlwalker_controller_
 walker controller for load-balance More...
 

Friends

class qmcplusplus::testing::DMCBatchedTest
 

Additional Inherited Members

- Public Attributes inherited from QMCDriverNew
std::bitset< QMC_MODE_MAXqmc_driver_mode_
 bits to classify QMCDriver More...
 
bool allow_walker_logs
 whether to allow walker logs More...
 
WalkerLogInput walker_logs_input
 walker logs input More...
 
- Protected Member Functions inherited from QMCDriverNew
void initializeQMC (const AdjustedWalkerCounts &awc)
 Do common section starting tasks for VMC and DMC. More...
 
void measureImbalance (const std::string &tag) const
 inject additional barrier and measure load imbalance. More...
 
void endBlock ()
 end of a block operations. Aggregates statistics across all MPI ranks and write to disk. More...
 
const std::string & get_root_name () const override
 
- Static Protected Member Functions inherited from QMCDriverNew
static QMCDriverNew::AdjustedWalkerCounts adjustGlobalWalkerCount (Communicate &comm, const IndexType current_configs, const IndexType requested_total_walkers, const IndexType requested_walkers_per_rank, const RealType reserve_walkers, int num_crowds)
 }@ More...
 
static size_t determineStepsPerBlock (IndexType global_walkers, IndexType requested_samples, IndexType requested_steps, IndexType blocks)
 pure function calculating the actual number of steps per block More...
 
static void checkNumCrowdsLTNumThreads (const int num_crowds)
 
static void checkLogAndGL (Crowd &crowd, const std::string_view location)
 check logpsi and grad and lap against values computed from scratch More...
 
static void setWalkerOffsets (WalkerConfigurations &, Communicate *comm)
 update the global offsets of walker configurations after active walkers being touched. More...
 
- Protected Attributes inherited from QMCDriverNew
QMCDriverInput qmcdriver_input_
 
RealType max_disp_sq_
 
they should be limited to values that can be changed from input or are live state. More...
 
IndexType target_samples_
 the number of saved samples More...
 
IndexType nBlocksBetweenRecompute
 the number of blocks between recomptePsi More...
 
UPtrVector< Crowdcrowds_
 }@ More...
 
std::string h5_file_root_
 
std::unique_ptr< DriftModifierBasedrift_modifier_
 drift modifer More...
 
int k_delay
 the number to delay updates by More...
 
int walker_dump_period
 period of recording walker configurations More...
 
IndexType current_step_
 
size_t steps_per_block_ = 0
 actual number of steps per block More...
 
IndexType nAccept
 counter for number of moves accepted More...
 
IndexType nReject
 counter for number of moves /rejected More...
 
RealType m_oneover2tau
 Time-step factor $ 1/(2\tau)$. More...
 
RealType m_sqrttau
 Time-step factor $ \sqrt{\tau}$. More...
 
const std::string QMCType
 type of qmc: assigned by subclasses More...
 
MCPopulation population_
 the entire (on node) walker population it serves VMCBatch and DMCBatch right now but will be polymorphic More...
 
struct DriverWalkerResourceCollection golden_resource_
 the golden multi walker shared resource serves ParticleSet TrialWaveFunction right now but actually should be based on MCPopulation. More...
 
const MultiWalkerDispatchers dispatchers_
 multi walker dispatchers More...
 
std::unique_ptr< EstimatorManagerNewestimator_manager_
 Observables manager Has very problematic owner ship and life cycle. More...
 
std::unique_ptr< HDFWalkerOutputwOut
 record engine for walkers More...
 
UPtrVector< ContextForStepsstep_contexts_
 Per crowd move contexts, this is where the DistanceTables etc. More...
 
UPtrVector< RandomBase< FullPrecRealType > > Rng
 Random number generators. More...
 
std::vector< xmlNodePtr > mcwalkerNodePtr
 a list of mcwalkerset element More...
 
DriverTimers timers_
 period of dumping walker configurations and everything else for restart More...
 
ScopedProfiler driver_scope_profiler_
 profile the driver lifetime More...
 
const ProjectDataproject_data_
 project info for accessing global fileroot and series id More...
 
WalkerConfigurationswalker_configs_ref_
 
- Protected Attributes inherited from MPIObjectBase
CommunicatemyComm
 pointer to Communicate More...
 
std::string ClassName
 class Name More...
 
std::string myName
 name of the object More...
 

Member Typedef Documentation

◆ Base

using Base = QMCDriverNew

Definition at line 38 of file DMCBatched.h.

◆ FullPrecRealType

Definition at line 39 of file DMCBatched.h.

◆ ParticlePositions

◆ PosType

Definition at line 40 of file DMCBatched.h.

Constructor & Destructor Documentation

◆ DMCBatched() [1/3]

DMCBatched ( const ProjectData project_data,
QMCDriverInput &&  qmcdriver_input,
const std::optional< EstimatorManagerInput > &  global_emi,
DMCDriverInput &&  input,
WalkerConfigurations wc,
MCPopulation &&  pop,
Communicate comm 
)

Constructor.

Constructor maintains proper ownership of input parameters.

Note you must call the Base constructor before the derived class sets QMCType

Definition at line 44 of file DMCBatched.cpp.

51  : QMCDriverNew(project_data,
52  std::move(qmcdriver_input),
53  global_emi,
54  wc,
55  std::move(pop),
56  "DMCBatched::",
57  comm,
58  "DMCBatched"),
60  dmc_timers_("DMCBatched::")
61 {}
QMCDriverNew(const ProjectData &project_data, QMCDriverInput &&input, const std::optional< EstimatorManagerInput > &global_emi, WalkerConfigurations &wc, MCPopulation &&population, const std::string timer_prefix, Communicate *comm, const std::string &QMC_driver_type)
Constructor.
DMCTimers dmc_timers_
I think its better if these have there own type and variable name.
Definition: DMCBatched.h:136
const DMCDriverInput dmcdriver_input_
Definition: DMCBatched.h:132
testing::ValidSpinDensityInput input

◆ DMCBatched() [2/3]

DMCBatched ( const DMCBatched )
delete

Copy Constructor (disabled)

◆ DMCBatched() [3/3]

DMCBatched ( DMCBatched &&  )
default

◆ ~DMCBatched()

~DMCBatched ( )
overridedefault

Member Function Documentation

◆ advanceWalkers()

void advanceWalkers ( const StateForThread sft,
Crowd crowd,
DriverTimers timers,
DMCTimers dmc_timers,
ContextForSteps move_context,
bool  recompute,
bool  accumulate_this_step 
)
staticprivate

Definition at line 72 of file DMCBatched.cpp.

References DMCBatched::StateForThread::branch_engine, SFNBranch::branchWeight(), QMCDriverNew::DriverTimers::buffer_timer, qmcplusplus::CHECKGL_AFTER_MOVES, qmcplusplus::CHECKGL_AFTER_TMOVE, QMCDriverNew::checkLogAndGL(), QMCDriverNew::DriverTimers::collectables_timer, QMCDriverNew::computeLogGreensFunction(), qmcplusplus::crowd, qmcplusplus::dot(), DMCBatched::StateForThread::drift_modifier, QMCDriverNew::DriverTimers::estimators_timer, qmcplusplus::exp(), QMCDriverInput::get_debug_checks(), MCPopulation::get_ptclgrp_inv_mass(), ContextForSteps::get_random_gen(), QMCDriverInput::get_spin_mass(), QMCDriverInput::get_tau(), DriftModifierBase::getDrifts(), DMCBatched::StateForThread::global_step, QMCDriverNew::DriverTimers::hamiltonian_timer, qmcplusplus::isfinite(), qmcplusplus::makeGaussRandomWithEngine(), QMCDriverNew::DriverTimers::movepbyp_timer, norm(), qmcplusplus::hdf::num_walkers, SFNBranch::phaseChanged(), DMCBatched::StateForThread::population, DMCBatched::StateForThread::qmcdrv_input, QMCDriverNew::DriverTimers::resource_timer, QMCDriverNew::scaleBySqrtTau(), TimerType< CLOCK >::start(), DMCBatched::DMCTimers::step_begin_recompute_timer, TimerType< CLOCK >::stop(), DMCBatched::DMCTimers::tmove_timer, qmcplusplus::twf, qmcplusplus::walker, and qmcplusplus::hdf::walkers.

79 {
80  auto& ps_dispatcher = crowd.dispatchers_.ps_dispatcher_;
81  auto& twf_dispatcher = crowd.dispatchers_.twf_dispatcher_;
82  auto& ham_dispatcher = crowd.dispatchers_.ham_dispatcher_;
83 
84  auto& walkers = crowd.get_walkers();
85  const RefVectorWithLeader<ParticleSet> walker_elecs(crowd.get_walker_elecs()[0], crowd.get_walker_elecs());
86  const RefVectorWithLeader<TrialWaveFunction> walker_twfs(crowd.get_walker_twfs()[0], crowd.get_walker_twfs());
87  const RefVectorWithLeader<QMCHamiltonian> walker_hamiltonians(crowd.get_walker_hamiltonians()[0],
88  crowd.get_walker_hamiltonians());
89 
90  timers.resource_timer.start();
91  ResourceCollectionTeamLock<ParticleSet> pset_res_lock(crowd.getSharedResource().pset_res, walker_elecs);
92  ResourceCollectionTeamLock<TrialWaveFunction> twfs_res_lock(crowd.getSharedResource().twf_res, walker_twfs);
93  ResourceCollectionTeamLock<QMCHamiltonian> hams_res_lock(crowd.getSharedResource().ham_res, walker_hamiltonians);
94  timers.resource_timer.stop();
95 
96  {
97  ScopedTimer recompute_timer(dmc_timers.step_begin_recompute_timer);
98  std::vector<bool> recompute_mask;
99  recompute_mask.reserve(walkers.size());
100  for (MCPWalker& awalker : walkers)
101  if (awalker.wasTouched)
102  {
103  recompute_mask.push_back(true);
104  awalker.wasTouched = false;
105  }
106  else
107  recompute_mask.push_back(false);
108  ps_dispatcher.flex_loadWalker(walker_elecs, walkers, recompute_mask, true);
109  twf_dispatcher.flex_recompute(walker_twfs, walker_elecs, recompute_mask);
110  }
111 
112  const int num_walkers = crowd.size();
113  auto& pset_leader = walker_elecs.getLeader();
114  const int num_particles = pset_leader.getTotalNum();
115 
116  MCCoords<CT> drifts(num_walkers), drifts_reverse(num_walkers);
117  MCCoords<CT> walker_deltas(num_walkers * num_particles), deltas(num_walkers);
118  TWFGrads<CT> grads_now(num_walkers), grads_new(num_walkers);
119 
120  //This generates an entire steps worth of deltas.
121  makeGaussRandomWithEngine(walker_deltas, step_context.get_random_gen());
122 
123  std::vector<PsiValue> ratios(num_walkers, PsiValue(0.0));
124  std::vector<RealType> log_gf(num_walkers, 0.0);
125  std::vector<RealType> log_gb(num_walkers, 0.0);
126  std::vector<RealType> prob(num_walkers, 0.0);
127 
128  // local list to handle accept/reject
129  std::vector<bool> isAccepted;
130  isAccepted.reserve(num_walkers);
131 
132  //save the old energies for branching needs.
133  std::vector<FullPrecRealType> old_energies(num_walkers);
134  for (int iw = 0; iw < num_walkers; ++iw)
135  old_energies[iw] = walkers[iw].get().Properties(WP::LOCALENERGY);
136 
137  std::vector<RealType> rr_proposed(num_walkers, 0.0);
138  std::vector<RealType> rr_accepted(num_walkers, 0.0);
139 
140  {
141  ScopedTimer pbyp_local_timer(timers.movepbyp_timer);
142  for (int ig = 0; ig < pset_leader.groups(); ++ig)
143  {
144  TauParams<RealType, CT> taus(sft.qmcdrv_input.get_tau(), sft.population.get_ptclgrp_inv_mass()[ig],
145  sft.qmcdrv_input.get_spin_mass());
146 
147  twf_dispatcher.flex_prepareGroup(walker_twfs, walker_elecs, ig);
148 
149  for (int iat = pset_leader.first(ig); iat < pset_leader.last(ig); ++iat)
150  {
151  //This is very useful thing to be able to look at in the debugger
152 #ifndef NDEBUG
153  std::vector<int> walkers_who_have_been_on_wire(num_walkers, 0);
154  for (int iw = 0; iw < walkers.size(); ++iw)
155  {
156  walkers[iw].get().get_has_been_on_wire() ? walkers_who_have_been_on_wire[iw] = 1
157  : walkers_who_have_been_on_wire[iw] = 0;
158  }
159 #endif
160  //get deltas for this particle for all walkers
161  walker_deltas.getSubset(iat * num_walkers, num_walkers, deltas);
162 
163  // only DMC does this
164  // TODO: rr needs a real name
165  std::vector<RealType> rr(num_walkers, 0.0);
166  assert(rr.size() == deltas.positions.size());
167  std::transform(deltas.positions.begin(), deltas.positions.end(), rr.begin(),
168  [t = taus.tauovermass](auto& delta_r) { return t * dot(delta_r, delta_r); });
169 
170  twf_dispatcher.flex_evalGrad(walker_twfs, walker_elecs, iat, grads_now);
171  sft.drift_modifier.getDrifts(taus, grads_now, drifts);
172 
173  scaleBySqrtTau(taus, deltas);
174  drifts += deltas;
175 
176 // in DMC this was done here, changed to match VMCBatched pending factoring to common source
177 // if (rr > m_r2max)
178 // {
179 // ++nRejectTemp;
180 // continue;
181 // }
182 #ifndef NDEBUG
183  for (int i = 0; i < rr.size(); ++i)
184  assert(qmcplusplus::isfinite(rr[i]));
185 #endif
186 
187  ps_dispatcher.flex_makeMove(walker_elecs, iat, drifts);
188 
189  twf_dispatcher.flex_calcRatioGrad(walker_twfs, walker_elecs, iat, ratios, grads_new);
190 
191  computeLogGreensFunction(deltas, taus, log_gf);
192 
193  sft.drift_modifier.getDrifts(taus, grads_new, drifts_reverse);
194 
195  drifts_reverse += drifts;
196 
197  computeLogGreensFunction(drifts_reverse, taus, log_gb);
198 
199  auto checkPhaseChanged = [&sft](const PsiValue& ratio, int& is_reject) {
200  if (ratio == PsiValue(0) || sft.branch_engine.phaseChanged(std::arg(ratio)))
201  is_reject = 1;
202  else
203  is_reject = 0;
204  };
205 
206  // Hopefully a phase change doesn't make any of these transformations fail.
207  std::vector<int> rejects(num_walkers); // instead of std::vector<bool>
208  for (int iw = 0; iw < num_walkers; ++iw)
209  {
210  checkPhaseChanged(ratios[iw], rejects[iw]);
211  //This is just convenient to do here
212  rr_proposed[iw] += rr[iw];
213  }
214 
215  for (int iw = 0; iw < num_walkers; ++iw)
216  prob[iw] = std::norm(ratios[iw]) * std::exp(log_gb[iw] - log_gf[iw]);
217 
218  isAccepted.clear();
219 
220  for (int iw = 0; iw < num_walkers; ++iw)
221  if ((!rejects[iw]) && prob[iw] >= std::numeric_limits<RealType>::epsilon() &&
222  step_context.get_random_gen()() < prob[iw])
223  {
224  crowd.incAccept();
225  isAccepted.push_back(true);
226  rr_accepted[iw] += rr[iw];
227  }
228  else
229  {
230  crowd.incReject();
231  isAccepted.push_back(false);
232  }
233 
234  twf_dispatcher.flex_accept_rejectMove(walker_twfs, walker_elecs, iat, isAccepted, true);
235 
236  ps_dispatcher.flex_accept_rejectMove<CT>(walker_elecs, iat, isAccepted);
237  }
238  }
239 
240  twf_dispatcher.flex_completeUpdates(walker_twfs);
241  ps_dispatcher.flex_donePbyP(walker_elecs);
242  }
243 
244  { // collect GL for KE.
245  ScopedTimer buffer_local(timers.buffer_timer);
246  twf_dispatcher.flex_evaluateGL(walker_twfs, walker_elecs, recompute);
247  if (sft.qmcdrv_input.get_debug_checks() & DriverDebugChecks::CHECKGL_AFTER_MOVES)
248  checkLogAndGL(crowd, "checkGL_after_moves");
249  ps_dispatcher.flex_saveWalker(walker_elecs, walkers);
250  }
251 
252  { // hamiltonian
253  ScopedTimer ham_local(timers.hamiltonian_timer);
254 
255  std::vector<QMCHamiltonian::FullPrecRealType> new_energies(
256  ham_dispatcher.flex_evaluateWithToperator(walker_hamiltonians, walker_twfs, walker_elecs));
257 
258  auto resetSigNLocalEnergy = [](MCPWalker& walker, TrialWaveFunction& twf, auto local_energy, auto rr_acc,
259  auto rr_prop) {
260  walker.resetProperty(twf.getLogPsi(), twf.getPhase(), local_energy, rr_acc, rr_prop, 1.0);
261  };
262 
263  for (int iw = 0; iw < walkers.size(); ++iw)
264  {
265  resetSigNLocalEnergy(walkers[iw], walker_twfs[iw], new_energies[iw], rr_accepted[iw], rr_proposed[iw]);
266  FullPrecRealType branch_weight = sft.branch_engine.branchWeight(new_energies[iw], old_energies[iw]);
267  walkers[iw].get().Weight *= branch_weight;
268  if (rr_proposed[iw] > 0)
269  walkers[iw].get().Age = 0;
270  else
271  walkers[iw].get().Age++;
272  }
273  }
274 
275  { // estimator collectables
276  ScopedTimer collectable_local(timers.collectables_timer);
277 
278  // evaluate non-physical hamiltonian elements
279  for (int iw = 0; iw < walkers.size(); ++iw)
280  walker_hamiltonians[iw].auxHevaluate(walker_elecs[iw], walkers[iw]);
281 
282  // save properties into walker
283  for (int iw = 0; iw < walkers.size(); ++iw)
284  walker_hamiltonians[iw].saveProperty(walkers[iw].get().getPropertyBase());
285  }
286 
287  if (accumulate_this_step)
288  {
289  ScopedTimer est_timer(timers.estimators_timer);
290  crowd.accumulate(step_context.get_random_gen());
291  }
292 
293  // collect walker logs
294  crowd.collectStepWalkerLog(sft.global_step);
295 
296  { // T-moves
297  ScopedTimer tmove_timer(dmc_timers.tmove_timer);
298 
299  const auto num_walkers = walkers.size();
300  std::vector<int> walker_non_local_moves_accepted(num_walkers, 0);
301  RefVector<MCPWalker> moved_nonlocal_walkers;
302  RefVectorWithLeader<ParticleSet> moved_nonlocal_walker_elecs(crowd.get_walker_elecs()[0]);
303  RefVectorWithLeader<TrialWaveFunction> moved_nonlocal_walker_twfs(crowd.get_walker_twfs()[0]);
304  moved_nonlocal_walkers.reserve(num_walkers);
305  moved_nonlocal_walker_elecs.reserve(num_walkers);
306  moved_nonlocal_walker_twfs.reserve(num_walkers);
307 
308  for (int iw = 0; iw < walkers.size(); ++iw)
309  {
310  walker_non_local_moves_accepted[iw] = walker_hamiltonians[iw].makeNonLocalMoves(walker_elecs[iw]);
311 
312  if (walker_non_local_moves_accepted[iw] > 0)
313  {
314  crowd.incNonlocalAccept(walker_non_local_moves_accepted[iw]);
315  moved_nonlocal_walkers.push_back(walkers[iw]);
316  moved_nonlocal_walker_elecs.push_back(walker_elecs[iw]);
317  moved_nonlocal_walker_twfs.push_back(walker_twfs[iw]);
318  }
319  }
320 
321  if (moved_nonlocal_walkers.size())
322  {
323  twf_dispatcher.flex_evaluateGL(moved_nonlocal_walker_twfs, moved_nonlocal_walker_elecs, false);
324  if (sft.qmcdrv_input.get_debug_checks() & DriverDebugChecks::CHECKGL_AFTER_TMOVE)
325  checkLogAndGL(crowd, "checkGL_after_tmove");
326  ps_dispatcher.flex_saveWalker(moved_nonlocal_walker_elecs, moved_nonlocal_walkers);
327  }
328  }
329 }
WaveFunctionComponent::PsiValue PsiValue
Definition: SlaterDet.cpp:25
const char num_walkers[]
Definition: HDFVersion.h:37
static void scaleBySqrtTau(const TauParams< RT, CT > &taus, MCCoords< CT > &coords)
Definition: QMCDriverNew.h:257
ScopeGuard< NewTimer > ScopedTimer
Definition: NewTimer.h:257
MCPopulation::MCPWalker MCPWalker
Definition: QMCDriverNew.h:93
const char walkers[]
Definition: HDFVersion.h:36
bool isfinite(float a)
return true if the value is finite.
Definition: math.cpp:21
double norm(const zVec &c)
Definition: VectorOps.h:118
QMCTraits::FullPrecRealType FullPrecRealType
Definition: DMCBatched.h:39
static void computeLogGreensFunction(const MCCoords< CT > &coords, const TauParams< RT, CT > &taus, std::vector< QMCTraits::RealType > &log_gb)
calculates Green Function from displacements stored in MCCoords [param, out] log_g ...
Definition: QMCDriverNew.h:270
MakeReturn< UnaryNode< FnExp, typename CreateLeaf< Vector< T1, C1 > >::Leaf_t > >::Expression_t exp(const Vector< T1, C1 > &l)
static void checkLogAndGL(Crowd &crowd, const std::string_view location)
check logpsi and grad and lap against values computed from scratch
Tensor< typename BinaryReturn< T1, T2, OpMultiply >::Type_t, D > dot(const AntiSymTensor< T1, D > &lhs, const AntiSymTensor< T2, D > &rhs)
void makeGaussRandomWithEngine(ParticleAttrib< TinyVector< T, D >> &a, RG &rng)

◆ getRunType()

QMCRunType getRunType ( )
inlineoverridevirtual

Implements QMCDriverInterface.

Definition at line 127 of file DMCBatched.h.

References qmcplusplus::DMC_BATCH.

◆ operator=()

DMCBatched& operator= ( const DMCBatched )
delete

Copy operator (disabled).

◆ process()

void process ( xmlNodePtr  cur)
overridevirtual

DMCBatched driver will eventually ignore cur.

This is the shared entry point from QMCMain so cannot be updated yet

Contains logic that sets walkers_per_rank_ TargetWalkers trump walkers, if it is not set walkers which is by default per rank for the batched drivers from this or the previous section wins.

walkers is still badly named.

Implements QMCDriverNew.

Definition at line 375 of file DMCBatched.cpp.

References QMCDriverNew::adjustGlobalWalkerCount(), qmcplusplus::app_log(), Communicate::barrier_and_abort(), DMCBatched::branch_engine_, QMCDriverNew::determineStepsPerBlock(), DMCBatched::dmcdriver_input_, Timer::elapsed(), DMCDriverInput::get_branch_interval(), DMCDriverInput::get_feedback(), DMCDriverInput::get_max_age(), QMCDriverInput::get_max_blocks(), QMCDriverInput::get_num_crowds(), MCPopulation::get_num_global_walkers(), DMCDriverInput::get_reconfiguration(), DMCDriverInput::get_refenergy_update_scheme(), QMCDriverInput::get_requested_samples(), QMCDriverInput::get_requested_steps(), DMCDriverInput::get_reserve(), QMCDriverInput::get_tau(), QMCDriverInput::get_total_walkers(), QMCDriverInput::get_walkers_per_rank(), WalkerConfigurations::getActiveWalkers(), QMCDriverNew::AdjustedWalkerCounts::global_walkers, QMCDriverNew::initializeQMC(), MPIObjectBase::myComm, qmcplusplus::node, QMCDriverNew::population_, qmcplusplus::print_mem(), QMCDriverNew::qmcdriver_input_, Random, QMCDriverNew::steps_per_block_, qmcplusplus::UNLIMITED_HISTORY, QMCDriverNew::walker_configs_ref_, and DMCBatched::walker_controller_.

376 {
377  print_mem("DMCBatched before initialization", app_log());
378  try
379  {
380  QMCDriverNew::AdjustedWalkerCounts awc =
384 
388 
389  Base::initializeQMC(awc);
390  }
391  catch (const UniformCommunicateError& ue)
392  {
393  myComm->barrier_and_abort(ue.what());
394  }
395 
396  {
397  ReportEngine PRE("DMC", "resetUpdateEngines");
398  Timer init_timer;
399  // Here DMC loads "Ensemble of cloned MCWalkerConfigurations"
400  // I'd like to do away with this method in DMCBatched.
401 
402  app_log() << " Creating the branching engine and walker controler" << std::endl;
403  const auto refE_update_scheme = dmcdriver_input_.get_refenergy_update_scheme();
404  app_log() << " Reference energy is updated using the "
405  << (refE_update_scheme == DMCRefEnergyScheme::UNLIMITED_HISTORY ? "unlimited_history" : "limited_history")
406  << " scheme" << std::endl;
408  std::make_unique<SFNBranch>(qmcdriver_input_.get_tau(), dmcdriver_input_.get_feedback(), refE_update_scheme);
409  branch_engine_->put(node);
410 
411  walker_controller_ = std::make_unique<WalkerControl>(myComm, Random, dmcdriver_input_.get_reconfiguration());
413  walker_controller_->start();
414  walker_controller_->put(node);
415 
416  std::ostringstream o;
418  o << " Fixed population using reconfiguration method\n";
419  else
420  o << " Fluctuating population\n";
421 
422  o << " Persistent walkers are killed after " << dmcdriver_input_.get_max_age() << " MC sweeps\n";
423  o << " BranchInterval = " << dmcdriver_input_.get_branch_interval() << "\n";
424  o << " Steps per block = " << steps_per_block_ << "\n";
425  o << " Number of blocks = " << qmcdriver_input_.get_max_blocks() << "\n";
426  app_log() << o.str() << std::endl;
427 
428  app_log() << " DMC Engine Initialization = " << init_timer.elapsed() << " secs" << std::endl;
429  }
430 }
size_t steps_per_block_
actual number of steps per block
Definition: QMCDriverNew.h:407
MCPopulation population_
the entire (on node) walker population it serves VMCBatch and DMCBatch right now but will be polymorp...
Definition: QMCDriverNew.h:426
size_t getActiveWalkers() const
return the number of active walkers
if(!okay) throw std xmlNodePtr node
std::unique_ptr< WalkerControl > walker_controller_
walker controller for load-balance
Definition: DMCBatched.h:142
IndexType get_requested_steps() const
std::ostream & app_log()
Definition: OutputManager.h:65
DMCRefEnergyScheme get_refenergy_update_scheme() const
RealType get_reserve() const
#define Random
void print_mem(const std::string &title, std::ostream &log)
Definition: MemoryUsage.cpp:30
IndexType get_max_age() const
IndexType get_num_crowds() const
static size_t determineStepsPerBlock(IndexType global_walkers, IndexType requested_samples, IndexType requested_steps, IndexType blocks)
pure function calculating the actual number of steps per block
IndexType get_total_walkers() const
IndexType get_walkers_per_rank() const
WalkerConfigurations & walker_configs_ref_
Definition: QMCDriverNew.h:481
Communicate * myComm
pointer to Communicate
Definition: MPIObjectBase.h:62
static QMCDriverNew::AdjustedWalkerCounts adjustGlobalWalkerCount(Communicate &comm, const IndexType current_configs, const IndexType requested_total_walkers, const IndexType requested_walkers_per_rank, const RealType reserve_walkers, int num_crowds)
}@
const DMCDriverInput dmcdriver_input_
Definition: DMCBatched.h:132
IndexType get_branch_interval() const
IndexType get_num_global_walkers() const
Definition: MCPopulation.h:168
std::unique_ptr< SFNBranch > branch_engine_
branch engine
Definition: DMCBatched.h:140
IndexType get_max_blocks() const
void barrier_and_abort(const std::string &msg) const
QMCDriverInput qmcdriver_input_
Definition: QMCDriverNew.h:372
IndexType get_requested_samples() const
void initializeQMC(const AdjustedWalkerCounts &awc)
Do common section starting tasks for VMC and DMC.

◆ run()

bool run ( )
overridevirtual

Implements QMCDriverInterface.

Definition at line 432 of file DMCBatched.cpp.

References QMCDriverNew::allow_walker_logs, qmcplusplus::app_debug_stream(), qmcplusplus::app_log(), qmcplusplus::app_summary(), Communicate::barrier(), Communicate::bcast(), DMCBatched::branch_engine_, qmcplusplus::crowd, QMCDriverNew::crowds_, DMCBatched::dmc_timers_, DMCBatched::dmcdriver_input_, QMCDriverNew::drift_modifier_, QMCDriverNew::endBlock(), QMCDriverNew::estimator_manager_, QMCDriverNew::finalize(), QMCDriverInput::get_blocks_between_recompute(), MCPopulation::get_golden_electrons(), MCPopulation::get_hamiltonians(), QMCDriverInput::get_max_blocks(), QMCDriverInput::get_measure_imbalance(), QMCDriverInput::get_recalculate_properties_period(), DMCDriverInput::get_reconfiguration(), QMCDriverNew::get_root_name(), ProjectData::getMaxCPUSeconds(), ProjectData::getTitle(), ParticleSet::getTotalNum(), Crowd::getWalkerLogCollectorRefs(), DMCBatched::StateForThread::global_step, qmcplusplus::ham, QMCDriverNew::DriverTimers::init_walkers_timer, QMCDriverNew::initialLogEvaluation(), DMCBatched::StateForThread::is_recomputing_block, WalkerLogManager::makeCollector(), MCPopulation::measureGlobalEnergyVariance(), QMCDriverNew::measureImbalance(), MPIObjectBase::myComm, qmcplusplus::hdf::num_blocks, QMCDriverNew::population_, qmcplusplus::print_mem(), QMCDriverNew::DriverTimers::production_timer, QMCDriverNew::project_data_, QMCDriverNew::qmc_driver_mode_, QMCDriverNew::QMC_UPDATE_MODE, QMCDriverNew::qmcdriver_input_, Communicate::rank(), DMCBatched::StateForThread::recalculate_properties_period, QMCDriverNew::recordBlock(), MCPopulation::redistributeWalkers(), QMCDriverNew::DriverTimers::run_steps_timer, qmcplusplus::run_time_manager, DMCBatched::runDMCStep(), DMCBatched::setNonLocalMoveHandler(), WalkerLogManager::startRun(), DMCBatched::StateForThread::step, QMCDriverNew::step_contexts_, QMCDriverNew::steps_per_block_, WalkerLogManager::stopRun(), QMCDriverNew::timers_, DMCBatched::walker_controller_, QMCDriverNew::walker_logs_input, and WalkerLogManager::writeBuffers().

433 {
435 
436  estimator_manager_->startDriverRun();
437 
438  //initialize WalkerLogManager and collectors
439  WalkerLogManager wlog_manager(walker_logs_input, allow_walker_logs, get_root_name(), myComm);
440  for (auto& crowd : crowds_)
441  crowd->setWalkerLogCollector(wlog_manager.makeCollector());
442  //register walker log collectors into the manager
443  wlog_manager.startRun(Crowd::getWalkerLogCollectorRefs(crowds_));
444 
446 
447  LoopTimer<> dmc_loop;
448  RunTimeControl<> runtimeControl(run_time_manager, project_data_.getMaxCPUSeconds(), project_data_.getTitle(),
449  myComm->rank() == 0);
450 
451  { // walker initialization
453  ParallelExecutor<> section_start_task;
454  section_start_task(crowds_.size(), initialLogEvaluation, std::ref(crowds_), std::ref(step_contexts_));
455 
456  FullPrecRealType energy, variance;
457  population_.measureGlobalEnergyVariance(*myComm, energy, variance);
458  // false indicates we do not support kill at node crossings.
459  branch_engine_->initParam(population_, energy, variance, dmcdriver_input_.get_reconfiguration(), false);
460  walker_controller_->setTrialEnergy(branch_engine_->getEtrial());
461 
462  print_mem("DMCBatched after initialLogEvaluation", app_summary());
464  measureImbalance("InitialLogEvaluation");
465  }
466 
467  // this barrier fences all previous load imbalance. Avoid block 0 timing pollution.
468  myComm->barrier();
469 
470  ScopedTimer local_timer(timers_.production_timer);
471  ParallelExecutor<> crowd_task;
472 
473  int global_step = 0;
474  for (int block = 0; block < num_blocks; ++block)
475  {
476  {
477  ScopeGuard<LoopTimer<>> dmc_local_timer(dmc_loop);
479 
480  dmc_state.recalculate_properties_period = (qmc_driver_mode_[QMC_UPDATE_MODE])
483  dmc_state.is_recomputing_block = qmcdriver_input_.get_blocks_between_recompute()
484  ? (1 + block) % qmcdriver_input_.get_blocks_between_recompute() == 0
485  : false;
486 
487  for (UPtr<Crowd>& crowd : crowds_)
488  crowd->startBlock(steps_per_block_);
489 
490  for (int step = 0; step < steps_per_block_; ++step, ++global_step)
491  {
492  ScopedTimer local_timer(timers_.run_steps_timer);
493 
494  // ensure all the live walkers carry the up-to-date T-move settings.
495  // Such info should be removed from each NLPP eventually and be kept in the driver.
496  for (UPtr<QMCHamiltonian>& ham : population_.get_hamiltonians())
498 
499  dmc_state.step = step;
500  dmc_state.global_step = global_step;
501  crowd_task(crowds_.size(), runDMCStep, dmc_state, timers_, dmc_timers_, std::ref(step_contexts_),
502  std::ref(crowds_));
503 
504  {
505  const int iter = block * steps_per_block_ + step;
506  walker_controller_->branch(iter, population_, iter == 0);
507  branch_engine_->updateParamAfterPopControl(walker_controller_->get_ensemble_property(),
509  walker_controller_->setTrialEnergy(branch_engine_->getEtrial());
510  }
511 
513  }
514  print_mem("DMCBatched after a block", app_debug_stream());
516  measureImbalance("Block " + std::to_string(block));
517  endBlock();
518  wlog_manager.writeBuffers();
519  recordBlock(block);
520  }
521 
522  bool stop_requested = false;
523  // Rank 0 decides whether the time limit was reached
524  if (!myComm->rank())
525  stop_requested = runtimeControl.checkStop(dmc_loop);
526  myComm->bcast(stop_requested);
527  // Progress messages before possibly stopping
528  if (!myComm->rank())
529  app_log() << runtimeControl.generateProgressMessage("DMCBatched", block, num_blocks);
530  if (stop_requested)
531  {
532  if (!myComm->rank())
533  app_log() << runtimeControl.generateStopMessage("DMCBatched", block);
534  run_time_manager.markStop();
535  break;
536  }
537  }
538 
539  branch_engine_->printStatus();
540 
541  print_mem("DMCBatched ends", app_log());
542 
543  wlog_manager.stopRun();
544  estimator_manager_->stopDriverRun();
545 
546  return finalize(num_blocks, true);
547 }
const std::string & getTitle() const noexcept
returns the title of the project <project id="det_qmc_short_sdbatch_vmcbatch_mwalkers" series="0"> tr...
size_t steps_per_block_
actual number of steps per block
Definition: QMCDriverNew.h:407
const ParticleSet & get_golden_electrons() const
Definition: MCPopulation.h:176
void barrier() const
MCPopulation population_
the entire (on node) walker population it serves VMCBatch and DMCBatch right now but will be polymorp...
Definition: QMCDriverNew.h:426
int rank() const
return the rank
Definition: Communicate.h:116
void recordBlock(int block) override
record the state of the block
std::unique_ptr< WalkerControl > walker_controller_
walker controller for load-balance
Definition: DMCBatched.h:142
WalkerLogInput walker_logs_input
walker logs input
Definition: QMCDriverNew.h:108
size_t getTotalNum() const
Definition: ParticleSet.h:493
std::ostream & app_log()
Definition: OutputManager.h:65
std::ostream & app_summary()
Definition: OutputManager.h:63
RunTimeManager< ChronoClock > run_time_manager
const char num_blocks[]
Definition: HDFVersion.h:44
ScopeGuard< NewTimer > ScopedTimer
Definition: NewTimer.h:257
UPtrVector< QMCHamiltonian > & get_hamiltonians()
Definition: MCPopulation.h:203
std::unique_ptr< EstimatorManagerNew > estimator_manager_
Observables manager Has very problematic owner ship and life cycle.
Definition: QMCDriverNew.h:443
void print_mem(const std::string &title, std::ostream &log)
Definition: MemoryUsage.cpp:30
DMCTimers dmc_timers_
I think its better if these have there own type and variable name.
Definition: DMCBatched.h:136
std::bitset< QMC_MODE_MAX > qmc_driver_mode_
bits to classify QMCDriver
Definition: QMCDriverNew.h:103
void measureGlobalEnergyVariance(Communicate &comm, FullPrecRealType &ener, FullPrecRealType &variance) const
bool finalize(int block, bool dumpwalkers=true)
finalize a qmc section
int getMaxCPUSeconds() const noexcept
const std::string & get_root_name() const override
Definition: QMCDriverNew.h:331
static RefVector< WalkerLogCollector > getWalkerLogCollectorRefs(const UPtrVector< Crowd > &crowds)
get refereces of active walker log collectors. If walker logging is disabled, the RefVector size can ...
Definition: Crowd.cpp:106
static void initialLogEvaluation(int crowd_id, UPtrVector< Crowd > &crowds, UPtrVector< ContextForSteps > &step_context)
Communicate * myComm
pointer to Communicate
Definition: MPIObjectBase.h:62
void setNonLocalMoveHandler(QMCHamiltonian &hamiltonian)
Definition: DMCBatched.cpp:65
QMCTraits::FullPrecRealType FullPrecRealType
Definition: DMCBatched.h:39
QMCTraits::IndexType IndexType
Definition: QMCDriverNew.h:79
UPtrVector< ContextForSteps > step_contexts_
Per crowd move contexts, this is where the DistanceTables etc.
Definition: QMCDriverNew.h:450
const DMCDriverInput dmcdriver_input_
Definition: DMCBatched.h:132
std::unique_ptr< DriftModifierBase > drift_modifier_
drift modifer
Definition: QMCDriverNew.h:394
bool allow_walker_logs
whether to allow walker logs
Definition: QMCDriverNew.h:106
std::unique_ptr< SFNBranch > branch_engine_
branch engine
Definition: DMCBatched.h:140
IndexType get_max_blocks() const
const ProjectData & project_data_
project info for accessing global fileroot and series id
Definition: QMCDriverNew.h:478
void bcast(T &)
static void runDMCStep(int crowd_id, const StateForThread &sft, DriverTimers &timers, DMCTimers &dmc_timers, UPtrVector< ContextForSteps > &move_context, UPtrVector< Crowd > &crowds)
Definition: DMCBatched.cpp:347
IndexType get_blocks_between_recompute() const
UPtrVector< Crowd > crowds_
}@
Definition: QMCDriverNew.h:389
QMCDriverInput qmcdriver_input_
Definition: QMCDriverNew.h:372
void measureImbalance(const std::string &tag) const
inject additional barrier and measure load imbalance.
DriverTimers timers_
period of dumping walker configurations and everything else for restart
Definition: QMCDriverNew.h:472
std::ostream & app_debug_stream()
Definition: OutputManager.h:71
void redistributeWalkers(WTTV &walker_consumers)
distributes walkers and their "cloned" elements to the elements of a vector of unique_ptr to "walker_...
Definition: MCPopulation.h:131
void endBlock()
end of a block operations. Aggregates statistics across all MPI ranks and write to disk...
int get_recalculate_properties_period() const

◆ runDMCStep()

void runDMCStep ( int  crowd_id,
const StateForThread sft,
DriverTimers timers,
DMCTimers dmc_timers,
UPtrVector< ContextForSteps > &  move_context,
UPtrVector< Crowd > &  crowds 
)
static

Definition at line 347 of file DMCBatched.cpp.

References qmcplusplus::crowd, MCPopulation::get_golden_electrons(), DMCBatched::StateForThread::is_recomputing_block, ParticleSet::isSpinor(), DMCBatched::StateForThread::population, DMCBatched::StateForThread::step, and DMCBatched::StateForThread::steps_per_block.

Referenced by DMCBatched::run().

353 {
354  Crowd& crowd = *(crowds[crowd_id]);
355 
356  if (crowd.size() == 0)
357  return;
358 
359  auto& rng = context_for_steps[crowd_id]->get_random_gen();
360  crowd.setRNGForHamiltonian(rng);
361 
362  const IndexType step = sft.step;
363  // Are we entering the the last step of a block to recompute at?
364  const bool recompute_this_step = (sft.is_recomputing_block && (step + 1) == sft.steps_per_block);
365  const bool accumulate_this_step = true;
366  const bool spin_move = sft.population.get_golden_electrons().isSpinor();
367  if (spin_move)
368  advanceWalkers<CoordsType::POS_SPIN>(sft, crowd, timers, dmc_timers, *context_for_steps[crowd_id],
369  recompute_this_step, accumulate_this_step);
370  else
371  advanceWalkers<CoordsType::POS>(sft, crowd, timers, dmc_timers, *context_for_steps[crowd_id], recompute_this_step,
372  accumulate_this_step);
373 }
QMCTraits::IndexType IndexType
Definition: QMCDriverNew.h:79

◆ setNonLocalMoveHandler()

Friends And Related Function Documentation

◆ qmcplusplus::testing::DMCBatchedTest

Definition at line 153 of file DMCBatched.h.

Member Data Documentation

◆ branch_engine_

std::unique_ptr<SFNBranch> branch_engine_
private

branch engine

Definition at line 140 of file DMCBatched.h.

Referenced by DMCBatched::process(), and DMCBatched::run().

◆ branch_interval_

IndexType branch_interval_
private

Interval between branching.

Definition at line 138 of file DMCBatched.h.

◆ dmc_timers_

DMCTimers dmc_timers_
private

I think its better if these have there own type and variable name.

Definition at line 136 of file DMCBatched.h.

Referenced by DMCBatched::run().

◆ dmcdriver_input_

const DMCDriverInput dmcdriver_input_
private

◆ walker_controller_

std::unique_ptr<WalkerControl> walker_controller_
private

walker controller for load-balance

Definition at line 142 of file DMCBatched.h.

Referenced by DMCBatched::process(), and DMCBatched::run().

◆ qmcplusplus::QMCDriver

class qmcplusplus::QMCDriver

abstract base class for QMC engines

Definition at line 71 of file QMCDriver.h.

+ Inheritance diagram for QMCDriver:
+ Collaboration diagram for QMCDriver:

Public Types

enum  { QMC_UPDATE_MODE, QMC_MULTIPLE, QMC_OPTIMIZE, QMC_WARMUP }
 enumeration coupled with QMCMode More...
 
using Walker_t = MCWalkerConfiguration::Walker_t
 
using Buffer_t = Walker_t::Buffer_t
 
using FullPrecRealType = QMCTraits::FullPrecRealType
 
- Public Types inherited from QMCDriverInterface
using BranchEngineType = SimpleFixedNodeBranch
 
using FullPrecRealType = QMCTraits::FullPrecRealType
 
- Public Types inherited from QMCTraits
enum  { DIM = OHMMS_DIM, DIM_VGL = OHMMS_DIM + 2 }
 
using QTBase = QMCTypes< OHMMS_PRECISION, DIM >
 
using QTFull = QMCTypes< OHMMS_PRECISION_FULL, DIM >
 
using RealType = QTBase::RealType
 
using ComplexType = QTBase::ComplexType
 
using ValueType = QTBase::ValueType
 
using PosType = QTBase::PosType
 
using GradType = QTBase::GradType
 
using TensorType = QTBase::TensorType
 
using IndexType = OHMMS_INDEXTYPE
 define other types More...
 
using FullPrecRealType = QTFull::RealType
 
using FullPrecValueType = QTFull::ValueType
 
using PropertySetType = RecordNamedProperty< FullPrecRealType >
 define PropertyList_t More...
 
using PtclGrpIndexes = std::vector< std::pair< int, int > >
 
- Public Types inherited from MPIObjectBase
using mpi_comm_type = Communicate::mpi_comm_type
 

Public Member Functions

 QMCDriver (const ProjectData &project_data, MCWalkerConfiguration &w, TrialWaveFunction &psi, QMCHamiltonian &h, Communicate *comm, const std::string &QMC_driver_type, bool enable_profiling=false)
 Constructor. More...
 
 ~QMCDriver () override
 
int current () const
 return current step More...
 
void setUpdateMode (bool pbyp) override
 set the update mode More...
 
void setStatus (const std::string &aname, const std::string &h5name, bool append) override
 Set the status of the QMCDriver. More...
 
void add_H_and_Psi (QMCHamiltonian *h, TrialWaveFunction *psi) override
 add QMCHamiltonian/TrialWaveFunction pair for multiple More...
 
void process (xmlNodePtr cur) override
 initialize with xmlNode More...
 
xmlNodePtr getQMCNode ()
 return a xmlnode with update More...
 
void putWalkers (std::vector< xmlNodePtr > &wset) override
 Read walker configurations from *.config.h5 files. More...
 
void putTraces (xmlNodePtr txml) override
 
void requestTraces (bool traces) override
 
void putWalkerLogs (xmlNodePtr wlxml) override
 
void requestWalkerLogs (bool allow_walker_logs_) override
 
std::string getEngineName () override
 
template<class PDT >
void setValue (const std::string &aname, PDT x)
 
void setBranchEngine (std::unique_ptr< BranchEngineType > &&be) override
 set the BranchEngineType More...
 
std::unique_ptr< BranchEngineTypegetBranchEngine () override
 return BranchEngineType* More...
 
int addObservable (const std::string &aname)
 
RealType getObservable (int i)
 
void setTau (RealType i)
 
void setWalkerOffsets ()
 set global offsets of the walkers More...
 
RefVector< RandomBase< FullPrecRealType > > getRngRefs () const
 return the random generators More...
 
RandomBase< FullPrecRealType > & getRng (int i) override
 return the i-th random generator More...
 
unsigned long getDriverMode () override
 
- Public Member Functions inherited from QMCDriverInterface
virtual bool run ()=0
 
virtual bool put (xmlNodePtr cur)=0
 
virtual QMCRunType getRunType ()=0
 
virtual ~QMCDriverInterface ()
 
virtual void setBranchEngine (std::unique_ptr< BranchEngineType > &&be)
 
- Public Member Functions inherited from MPIObjectBase
 MPIObjectBase (Communicate *c)
 constructor with communicator More...
 
int rank () const
 return the rank of the communicator More...
 
int getGroupID () const
 return the group id of the communicator More...
 
CommunicategetCommunicator () const
 return myComm More...
 
CommunicategetCommRef () const
 return a TEMPORARY reference to Communicate More...
 
mpi_comm_type getMPI () const
 return MPI communicator if one wants to use MPI directly More...
 
bool is_manager () const
 return true if the rank == 0 More...
 
const std::string & getName () const
 return the name More...
 
void setName (const std::string &aname)
 

Public Attributes

std::bitset< QMC_MODE_MAXqmc_driver_mode
 bits to classify QMCDriver More...
 
bool allow_traces
 whether to allow traces More...
 
xmlNodePtr traces_xml
 traces xml More...
 
bool allow_walker_logs
 whether to allow traces More...
 
xmlNodePtr walker_logs_xml
 traces xml More...
 
EstimatorManagerBaseEstimators
 Observables manager. More...
 
std::unique_ptr< TraceManagerTraces
 Traces manager. More...
 
std::unique_ptr< WalkerLogManagerwlog_manager_
 Traces manager. More...
 

Protected Member Functions

bool putQMCInfo (xmlNodePtr cur)
 Parses the xml input file for parameter definitions for a single qmc simulation. More...
 
void addWalkers (int nwalkers)
 Add walkers to the end of the ensemble of walkers. More...
 
void recordBlock (int block) override
 record the state of the block More...
 
bool finalize (int block, bool dumpwalkers=true)
 finalize a qmc section More...
 
std::string getRotationName (std::string RootName)
 
std::string getLastRotationName (std::string RootName)
 
const std::string & get_root_name () const override
 

Protected Attributes

const ProjectDataproject_data_
 top-level project data information More...
 
std::unique_ptr< BranchEngineTypebranchEngine
 branch engine More...
 
DriftModifierBaseDriftModifier
 drift modifer More...
 
bool ResetRandom
 randomize it More...
 
bool AppendRun
 flag to append or restart the run More...
 
bool DumpConfig
 flag to turn off dumping configurations More...
 
bool IsQMCDriver
 true, if it is a real QMC engine More...
 
int MyCounter
 the number of times this QMCDriver is executed More...
 
int kDelay
 the number to delay updates by More...
 
int Period4CheckPoint
 period of dumping walker configurations and everything else for restart More...
 
int Period4CheckProperties
 period of dumping walker positions and IDs for Forward Walking More...
 
int Period4WalkerDump
 period of recording walker configurations More...
 
int Period4ConfigDump
 period of recording walker positions and IDs for forward walking afterwards More...
 
IndexType CurrentStep
 current step More...
 
IndexType nBlocks
 maximum number of blocks More...
 
IndexType nSteps
 maximum number of steps More...
 
IndexType nSubSteps
 number of steps between a step: VMCs do not evaluate energies More...
 
IndexType nWarmupSteps
 number of warmup steps More...
 
IndexType nAccept
 counter for number of moves accepted More...
 
IndexType nReject
 counter for number of moves /rejected More...
 
IndexType nBlocksBetweenRecompute
 the number of blocks between recomptePsi More...
 
IndexType nTargetWalkers
 the number of walkers More...
 
IndexType nTargetSamples
 the number of saved samples More...
 
IndexType nStepsBetweenSamples
 alternate method of setting QMC run parameters More...
 
RealType nSamplesPerThread
 samples per thread More...
 
RealType nTargetPopulation
 target population More...
 
RealType Tau
 timestep More...
 
int MaxCPUSecs
 maximum cpu in secs More...
 
RealType m_oneover2tau
 Time-step factor $ 1/(2\tau)$. More...
 
RealType m_sqrttau
 Time-step factor $ \sqrt{\tau}$. More...
 
xmlNodePtr qmcNode
 pointer to qmc node in xml file More...
 
const std::string QMCType
 type of QMC driver More...
 
std::string h5FileRoot
 the root of h5File More...
 
std::string RootName
 root of all the output files More...
 
ParameterSet m_param
 store any parameter that has to be read from a file More...
 
MCWalkerConfigurationW
 walker ensemble More...
 
TrialWaveFunctionPsi
 trial function More...
 
QMCHamiltonianH
 Hamiltonian. More...
 
std::unique_ptr< HDFWalkerOutputwOut
 record engine for walkers More...
 
std::vector< TrialWaveFunction * > Psi1
 a list of TrialWaveFunctions for multiple method More...
 
std::vector< QMCHamiltonian * > H1
 a list of QMCHamiltonians for multiple method More...
 
UPtrVector< RandomBase< FullPrecRealType > > Rng
 Random number generators. More...
 
std::vector< xmlNodePtr > mcwalkerNodePtr
 a list of mcwalkerset element More...
 
ParticleSet::ParticlePos drift
 temporary storage for drift More...
 
ParticleSet::ParticlePos deltaR
 temporary storage for random displacement More...
 
RealType SpinMass
 spin mass for spinor calcs More...
 
int rotation
 
- Protected Attributes inherited from MPIObjectBase
CommunicatemyComm
 pointer to Communicate More...
 
std::string ClassName
 class Name More...
 
std::string myName
 name of the object More...
 

Private Attributes

NewTimercheckpoint_timer_
 
ScopedProfiler driver_scope_profiler_
 profile the driver lifetime More...
 

Member Typedef Documentation

◆ Buffer_t

Definition at line 84 of file QMCDriver.h.

◆ FullPrecRealType

Definition at line 85 of file QMCDriver.h.

◆ Walker_t

Definition at line 83 of file QMCDriver.h.

Member Enumeration Documentation

◆ anonymous enum

anonymous enum

enumeration coupled with QMCMode

Enumerator
QMC_UPDATE_MODE 
QMC_MULTIPLE 
QMC_OPTIMIZE 
QMC_WARMUP 

Definition at line 75 of file QMCDriver.h.

Constructor & Destructor Documentation

◆ QMCDriver()

QMCDriver ( const ProjectData project_data,
MCWalkerConfiguration w,
TrialWaveFunction psi,
QMCHamiltonian h,
Communicate comm,
const std::string &  QMC_driver_type,
bool  enable_profiling = false 
)

Constructor.

Definition at line 44 of file QMCDriver.cpp.

References ParameterSet::add(), QMCDriver::allow_traces, QMCDriver::allow_walker_logs, QMCDriver::AppendRun, QMCDriver::CurrentStep, DEPRECATED, QMCDriver::DumpConfig, WalkerConfigurations::getActiveWalkers(), QMCDriver::IsQMCDriver, QMCDriver::m_param, QMCDriver::MaxCPUSecs, QMCDriver::MyCounter, QMCDriver::nAccept, QMCDriver::nBlocks, QMCDriver::nBlocksBetweenRecompute, QMCDriver::nReject, QMCDriver::nSamplesPerThread, QMCDriver::nSteps, QMCDriver::nStepsBetweenSamples, QMCDriver::nSubSteps, QMCDriver::nTargetPopulation, QMCDriver::nTargetSamples, QMCDriver::nTargetWalkers, QMCDriver::nWarmupSteps, QMCDriver::Period4CheckPoint, QMCDriver::Period4CheckProperties, QMCDriver::Period4ConfigDump, QMCDriver::Period4WalkerDump, QMCDriver::ResetRandom, QMCDriver::rotation, QMCDriver::SpinMass, QMCDriver::Tau, QMCDriver::W, and QMCDriver::walker_logs_xml.

52  project_data_(project_data),
53  DriftModifier(0),
54  qmcNode(NULL),
55  QMCType(QMC_driver_type),
56  W(w),
57  Psi(psi),
58  H(h),
59  checkpoint_timer_(createGlobalTimer("checkpoint::recordBlock", timer_level_medium)),
60  driver_scope_profiler_(enable_profiling)
61 {
62  ResetRandom = false;
63  AppendRun = false;
64  DumpConfig = false;
65  IsQMCDriver = true;
66  allow_traces = false;
67  allow_walker_logs = false;
68  walker_logs_xml = NULL;
69  MyCounter = 0;
70  //<parameter name=" "> value </parameter>
71  //accept multiple names for the same value
72  //recommend using all lower cases for a new parameter
75  m_param.add(Period4CheckProperties, "checkProperties");
76  m_param.add(Period4CheckProperties, "checkproperties");
77  m_param.add(Period4CheckProperties, "check_properties");
79  //m_param.add(Period4WalkerDump,"recordWalkers");
80  m_param.add(Period4WalkerDump, "record_walkers");
81  m_param.add(Period4WalkerDump, "recordwalkers");
83  //m_param.add(Period4ConfigDump,"recordConfigs");
84  m_param.add(Period4ConfigDump, "recordconfigs");
85  m_param.add(Period4ConfigDump, "record_configs");
86  CurrentStep = 0;
87  m_param.add(CurrentStep, "current");
88  nBlocks = 1;
89  m_param.add(nBlocks, "blocks");
90  nSteps = 1;
91  m_param.add(nSteps, "steps");
92  nSubSteps = 1;
93  m_param.add(nSubSteps, "substeps");
94  //m_param.add(nSubSteps,"subSteps");
95  m_param.add(nSubSteps, "sub_steps");
96  nWarmupSteps = 0;
97  m_param.add(nWarmupSteps, "warmupsteps");
98  //m_param.add(nWarmupSteps,"warmupSteps");
99  m_param.add(nWarmupSteps, "warmup_steps");
100  nAccept = 0;
101  nReject = 0;
103  m_param.add(nTargetWalkers, "walkers");
104  //sample-related parameters
105  //samples will set nTargetPopulation
106  nTargetSamples = 0;
108  m_param.add(nStepsBetweenSamples, "stepsbetweensamples");
109  nSamplesPerThread = 0;
110  m_param.add(nSamplesPerThread, "samplesperthread");
111  m_param.add(nSamplesPerThread, "dmcwalkersperthread");
112 
113  nTargetPopulation = 0;
114 
115  m_param.add(nTargetPopulation, "samples");
116 
117  SpinMass = 1.0;
118  m_param.add(SpinMass, "SpinMass");
119  m_param.add(SpinMass, "spin_mass");
120 
121  Tau = 0.1;
122  //m_param.add(Tau,"timeStep");
123  m_param.add(Tau, "timestep");
124  m_param.add(Tau, "time_step");
125  //m_param.add(Tau,"Tau");
126  m_param.add(Tau, "tau");
127  MaxCPUSecs = 360000; //100 hours
128  m_param.add(MaxCPUSecs, "maxcpusecs", {}, TagStatus::DEPRECATED);
129  m_param.add(MaxCPUSecs, "max_seconds");
130  // by default call recompute at the end of each block in the mixed precision case.
131 #ifdef MIXED_PRECISION
132  // cpu mixed precision
134 #else
135  // cpu double precision
137 #endif
138  m_param.add(nBlocksBetweenRecompute, "blocks_between_recompute");
139  ////add each OperatorBase to W.PropertyList so that averages can be taken
140  //H.add2WalkerProperty(W);
141  //if (storeConfigs) ForwardWalkingHistory.storeConfigsForForwardWalking(w);
142  rotation = 0;
143 }
NewTimer & checkpoint_timer_
Definition: QMCDriver.h:381
int MaxCPUSecs
maximum cpu in secs
Definition: QMCDriver.h:302
size_t getActiveWalkers() const
return the number of active walkers
bool DumpConfig
flag to turn off dumping configurations
Definition: QMCDriver.h:226
RealType nSamplesPerThread
samples per thread
Definition: QMCDriver.h:293
xmlNodePtr qmcNode
pointer to qmc node in xml file
Definition: QMCDriver.h:310
IndexType CurrentStep
current step
Definition: QMCDriver.h:263
bool AppendRun
flag to append or restart the run
Definition: QMCDriver.h:224
RealType SpinMass
spin mass for spinor calcs
Definition: QMCDriver.h:353
IndexType nReject
counter for number of moves /rejected
Definition: QMCDriver.h:281
IndexType nTargetWalkers
the number of walkers
Definition: QMCDriver.h:287
int Period4ConfigDump
period of recording walker positions and IDs for forward walking afterwards
Definition: QMCDriver.h:260
ParameterSet m_param
store any parameter that has to be read from a file
Definition: QMCDriver.h:320
IndexType nSubSteps
number of steps between a step: VMCs do not evaluate energies
Definition: QMCDriver.h:272
IndexType nSteps
maximum number of steps
Definition: QMCDriver.h:269
const std::string QMCType
type of QMC driver
Definition: QMCDriver.h:313
NewTimer & createGlobalTimer(const std::string &myname, timer_levels mylevel)
QMCHamiltonian & H
Hamiltonian.
Definition: QMCDriver.h:329
DriftModifierBase * DriftModifier
drift modifer
Definition: QMCDriver.h:220
MCWalkerConfiguration & W
walker ensemble
Definition: QMCDriver.h:323
bool allow_walker_logs
whether to allow traces
Definition: QMCDriver.h:101
xmlNodePtr walker_logs_xml
traces xml
Definition: QMCDriver.h:103
bool IsQMCDriver
true, if it is a real QMC engine
Definition: QMCDriver.h:228
void add(PDT &aparam, const std::string &aname_in, std::vector< PDT > candidate_values={}, TagStatus status=TagStatus::OPTIONAL)
add a new parameter corresponding to an xmlNode <parameter>
IndexType nTargetSamples
the number of saved samples
Definition: QMCDriver.h:289
int Period4CheckPoint
period of dumping walker configurations and everything else for restart
Definition: QMCDriver.h:242
RealType nTargetPopulation
target population
Definition: QMCDriver.h:295
TrialWaveFunction & Psi
trial function
Definition: QMCDriver.h:326
IndexType nAccept
counter for number of moves accepted
Definition: QMCDriver.h:278
RealType Tau
timestep
Definition: QMCDriver.h:299
const ProjectData & project_data_
top-level project data information
Definition: QMCDriver.h:216
IndexType nStepsBetweenSamples
alternate method of setting QMC run parameters
Definition: QMCDriver.h:291
IndexType nBlocks
maximum number of blocks
Definition: QMCDriver.h:266
ScopedProfiler driver_scope_profiler_
profile the driver lifetime
Definition: QMCDriver.h:383
int Period4WalkerDump
period of recording walker configurations
Definition: QMCDriver.h:255
int Period4CheckProperties
period of dumping walker positions and IDs for Forward Walking
Definition: QMCDriver.h:249
MPIObjectBase(Communicate *c)
constructor with communicator
IndexType nWarmupSteps
number of warmup steps
Definition: QMCDriver.h:275
IndexType nBlocksBetweenRecompute
the number of blocks between recomptePsi
Definition: QMCDriver.h:284
int MyCounter
the number of times this QMCDriver is executed
Definition: QMCDriver.h:235
bool allow_traces
whether to allow traces
Definition: QMCDriver.h:96
bool ResetRandom
randomize it
Definition: QMCDriver.h:222

◆ ~QMCDriver()

~QMCDriver ( )
override

Definition at line 145 of file QMCDriver.cpp.

References QMCDriver::DriftModifier.

146 {
147  if (DriftModifier)
148  delete DriftModifier;
149 }
DriftModifierBase * DriftModifier
drift modifer
Definition: QMCDriver.h:220

Member Function Documentation

◆ add_H_and_Psi()

void add_H_and_Psi ( QMCHamiltonian h,
TrialWaveFunction psi 
)
overridevirtual

add QMCHamiltonian/TrialWaveFunction pair for multiple

Parameters
hQMCHamiltonian
psiTrialWaveFunction

Multiple drivers use multiple H/Psi pairs to perform correlated sampling for energy difference evaluations.

Implements QMCDriverInterface.

Definition at line 151 of file QMCDriver.cpp.

References QMCDriver::H1, and QMCDriver::Psi1.

152 {
153  H1.push_back(h);
154  Psi1.push_back(psi);
155 }
std::vector< TrialWaveFunction * > Psi1
a list of TrialWaveFunctions for multiple method
Definition: QMCDriver.h:335
std::vector< QMCHamiltonian * > H1
a list of QMCHamiltonians for multiple method
Definition: QMCDriver.h:338

◆ addObservable()

int addObservable ( const std::string &  aname)
inline

Definition at line 176 of file QMCDriver.h.

References EstimatorManagerBase::addObservable(), and QMCDriver::Estimators.

177  {
178  if (Estimators)
179  return Estimators->addObservable(aname.c_str());
180  else
181  return -1;
182  }
EstimatorManagerBase * Estimators
Observables manager.
Definition: QMCDriver.h:192

◆ addWalkers()

void addWalkers ( int  nwalkers)
protected

Add walkers to the end of the ensemble of walkers.

Parameters
nwalkersnumber of walkers to add

Definition at line 338 of file QMCDriver.cpp.

References qmcplusplus::app_log(), WalkerConfigurations::begin(), MCWalkerConfiguration::createWalkers(), WalkerConfigurations::destroyWalkers(), WalkerConfigurations::end(), WalkerConfigurations::getActiveWalkers(), ParticleSet::R, QMCDriver::setWalkerOffsets(), and QMCDriver::W.

Referenced by QMCFixedSampleLinearOptimize::processOptXML(), QMCDriver::putQMCInfo(), and RMC::resetReptiles().

339 {
340  if (nwalkers > 0)
341  {
342  //add nwalkers walkers to the end of the ensemble
343  int nold = W.getActiveWalkers();
344  app_log() << " Adding " << nwalkers << " walkers to " << nold << " existing sets" << std::endl;
345  W.createWalkers(nwalkers);
346  if (nold)
347  {
348  int iw = nold;
349  for (MCWalkerConfiguration::iterator it = W.begin() + nold; it != W.end(); ++it, ++iw)
350  (*it)->R = W[iw % nold]->R; //assign existing walker configurations when the number of walkers change
351  }
352  }
353  else if (nwalkers < 0)
354  {
355  W.destroyWalkers(-nwalkers);
356  app_log() << " Removed " << -nwalkers << " walkers. Current number of walkers =" << W.getActiveWalkers()
357  << std::endl;
358  }
359  else
360  {
361  app_log() << " Using the current " << W.getActiveWalkers() << " walkers." << std::endl;
362  }
364 
365  ////update the global number of walkers
366  ////int nw=W.getActiveWalkers();
367  ////myComm->allreduce(nw);
368 }
size_t getActiveWalkers() const
return the number of active walkers
std::ostream & app_log()
Definition: OutputManager.h:65
iterator destroyWalkers(iterator first, iterator last)
destroy Walkers from itstart to itend
WalkerList_t::iterator iterator
FIX: a type alias of iterator for an object should not be for just one of many objects it holds...
ParticlePos R
Position.
Definition: ParticleSet.h:79
MCWalkerConfiguration & W
walker ensemble
Definition: QMCDriver.h:323
void createWalkers(int numWalkers)
create numWalkers Walkers
void setWalkerOffsets()
set global offsets of the walkers
Definition: QMCDriver.cpp:370
iterator end()
return the last iterator, [begin(), end())
iterator begin()
return the first iterator

◆ current()

int current ( ) const
inline

return current step

Definition at line 117 of file QMCDriver.h.

References QMCDriver::CurrentStep.

117 { return CurrentStep; }
IndexType CurrentStep
current step
Definition: QMCDriver.h:263

◆ finalize()

bool finalize ( int  block,
bool  dumpwalkers = true 
)
protected

finalize a qmc section

Parameters
blockcurrent block
dumpwalkersif true, dump walkers

Accumulate energy and weight is written to a hdf5 file. Finialize the estimators

Definition at line 318 of file QMCDriver.cpp.

References QMCDriver::branchEngine, QMCDriver::DumpConfig, InfoStream::flush(), WalkerConfigurations::getActiveWalkers(), infoLog, infoSummary, MPIObjectBase::myComm, QMCDriver::MyCounter, QMCDriver::nTargetWalkers, QMCDriver::RootName, QMCDriver::W, QMCDriver::wOut, and RandomNumberControl::write().

Referenced by VMC::run(), RMC::run(), DMC::run(), and CSVMC::run().

319 {
320  if (DumpConfig && dumpwalkers)
321  wOut->dump(W, block);
323  MyCounter++;
324  infoSummary.flush();
325  infoLog.flush();
326 
327  branchEngine->finalize(W);
328 
329  if (DumpConfig)
331 
332  return true;
333 }
size_t getActiveWalkers() const
return the number of active walkers
bool DumpConfig
flag to turn off dumping configurations
Definition: QMCDriver.h:226
std::string RootName
root of all the output files
Definition: QMCDriver.h:317
InfoStream infoSummary
static void write(const std::string &fname, Communicate *comm)
write in parallel or serial
IndexType nTargetWalkers
the number of walkers
Definition: QMCDriver.h:287
InfoStream infoLog
std::unique_ptr< HDFWalkerOutput > wOut
record engine for walkers
Definition: QMCDriver.h:332
Communicate * myComm
pointer to Communicate
Definition: MPIObjectBase.h:62
std::unique_ptr< BranchEngineType > branchEngine
branch engine
Definition: QMCDriver.h:218
MCWalkerConfiguration & W
walker ensemble
Definition: QMCDriver.h:323
void flush()
flush stream buffer
Definition: InfoStream.cpp:39
int MyCounter
the number of times this QMCDriver is executed
Definition: QMCDriver.h:235

◆ get_root_name()

const std::string& get_root_name ( ) const
inlineoverrideprotectedvirtual

Implements QMCDriverInterface.

Definition at line 378 of file QMCDriver.h.

References QMCDriver::RootName.

Referenced by QMCFixedSampleLinearOptimize::run(), and QMCFixedSampleLinearOptimize::test_run().

378 { return RootName; }
std::string RootName
root of all the output files
Definition: QMCDriver.h:317

◆ getBranchEngine()

std::unique_ptr<BranchEngineType> getBranchEngine ( )
inlineoverridevirtual

return BranchEngineType*

Reimplemented from QMCDriverInterface.

Definition at line 174 of file QMCDriver.h.

References QMCDriver::branchEngine.

174 { return std::move(branchEngine); }
std::unique_ptr< BranchEngineType > branchEngine
branch engine
Definition: QMCDriver.h:218

◆ getDriverMode()

unsigned long getDriverMode ( )
inlineoverridevirtual

Implements QMCDriverInterface.

Definition at line 212 of file QMCDriver.h.

References QMCDriver::qmc_driver_mode.

212 { return qmc_driver_mode.to_ulong(); }
std::bitset< QMC_MODE_MAX > qmc_driver_mode
bits to classify QMCDriver
Definition: QMCDriver.h:93

◆ getEngineName()

std::string getEngineName ( )
inlineoverridevirtual

Implements QMCDriverInterface.

Definition at line 162 of file QMCDriver.h.

References QMCDriver::QMCType.

162 { return QMCType; }
const std::string QMCType
type of QMC driver
Definition: QMCDriver.h:313

◆ getLastRotationName()

std::string getLastRotationName ( std::string  RootName)
protected

Definition at line 293 of file QMCDriver.cpp.

References QMCDriver::RootName, and QMCDriver::rotation.

294 {
295  std::string r_RootName;
296  if ((rotation - 1) % 2 == 0)
297  {
298  r_RootName = RootName;
299  }
300  else
301  {
302  r_RootName = RootName + ".bk";
303  }
304  return r_RootName;
305 }
std::string RootName
root of all the output files
Definition: QMCDriver.h:317

◆ getObservable()

RealType getObservable ( int  i)
inline

Definition at line 184 of file QMCDriver.h.

References QMCDriver::Estimators, and EstimatorManagerBase::getObservable().

184 { return Estimators->getObservable(i); }
EstimatorManagerBase * Estimators
Observables manager.
Definition: QMCDriver.h:192

◆ getQMCNode()

xmlNodePtr getQMCNode ( )

return a xmlnode with update

Definition at line 516 of file QMCDriver.cpp.

References QMCDriver::CurrentStep, getContent(), getXMLAttributeValue(), and QMCDriver::qmcNode.

517 {
518  xmlNodePtr newqmc = xmlCopyNode(qmcNode, 1);
519  xmlNodePtr current_ptr = NULL;
520  xmlNodePtr cur = newqmc->children;
521  while (cur != NULL && current_ptr == NULL)
522  {
523  std::string cname((const char*)(cur->name));
524  if (cname == "parameter")
525  {
526  const std::string name(getXMLAttributeValue(cur, "name"));
527  if (name == "current")
528  current_ptr = cur;
529  }
530  cur = cur->next;
531  }
532  if (current_ptr == NULL)
533  {
534  current_ptr = xmlNewTextChild(newqmc, NULL, (const xmlChar*)"parameter", (const xmlChar*)"0");
535  xmlNewProp(current_ptr, (const xmlChar*)"name", (const xmlChar*)"current");
536  }
537  getContent(CurrentStep, current_ptr);
538  return newqmc;
539 }
xmlNodePtr qmcNode
pointer to qmc node in xml file
Definition: QMCDriver.h:310
IndexType CurrentStep
current step
Definition: QMCDriver.h:263
std::string getXMLAttributeValue(const xmlNodePtr cur, const std::string_view name)
get the value string for attribute name if name is unfound in cur you get an empty string back this i...
bool getContent(const T &a, xmlNodePtr cur)
write a value to a node.
Definition: libxmldefs.h:119

◆ getRng()

RandomBase<FullPrecRealType>& getRng ( int  i)
inlineoverridevirtual

return the i-th random generator

Implements QMCDriverInterface.

Definition at line 210 of file QMCDriver.h.

References QMCDriver::Rng.

210 { return (*Rng[i]); }
UPtrVector< RandomBase< FullPrecRealType > > Rng
Random number generators.
Definition: QMCDriver.h:341

◆ getRngRefs()

RefVector<RandomBase<FullPrecRealType> > getRngRefs ( ) const
inline

return the random generators

Definition at line 201 of file QMCDriver.h.

References QMCDriver::Rng.

202  {
203  RefVector<RandomBase<FullPrecRealType>> RngRefs;
204  for (int i = 0; i < Rng.size(); ++i)
205  RngRefs.push_back(*Rng[i]);
206  return RngRefs;
207  }
UPtrVector< RandomBase< FullPrecRealType > > Rng
Random number generators.
Definition: QMCDriver.h:341

◆ getRotationName()

std::string getRotationName ( std::string  RootName)
protected

Definition at line 278 of file QMCDriver.cpp.

References QMCDriver::RootName, and QMCDriver::rotation.

279 {
280  std::string r_RootName;
281  if (rotation % 2 == 0)
282  {
283  r_RootName = RootName;
284  }
285  else
286  {
287  r_RootName = RootName + ".bk";
288  }
289  rotation++;
290  return r_RootName;
291 }
std::string RootName
root of all the output files
Definition: QMCDriver.h:317

◆ process()

void process ( xmlNodePtr  cur)
overridevirtual

initialize with xmlNode

process a <qmc> element

Parameters
curxmlNode with qmc tag

This function is called before QMCDriver::run and following actions are taken:

  • Initialize basic data to execute run function. – distance tables – resize deltaR and drift with the number of particles – assign cur to qmcNode
  • process input file – putQMCInfo: <parameter> s for generic QMC – put : extra data by derived classes
  • initialize branchEngine to accumulate energies
  • initialize Estimators
  • initialize Walkers

Implements QMCDriverInterface.

Definition at line 172 of file QMCDriver.cpp.

References QMCDriver::allow_traces, QMCDriver::allow_walker_logs, qmcplusplus::app_log(), QMCDriver::branchEngine, qmcplusplus::createDriftModifier(), QMCDriver::deltaR, QMCDriver::drift, QMCDriver::DriftModifier, QMCDriver::Estimators, InfoStream::flush(), WalkerConfigurations::getGlobalNumWalkers(), ParticleSet::getTotalNum(), QMCDriver::H, QMCDriver::H1, QMCDriver::h5FileRoot, infoLog, infoSummary, RandomNumberControl::make_seeds(), MPIObjectBase::myComm, DriftModifierBase::parseXML(), QMCDriverInterface::put(), EstimatorManagerBase::put(), QMCDriver::putQMCInfo(), QMCDriver::qmcNode, QMCDriver::ResetRandom, MCWalkerConfiguration::resetWalkerProperty(), QMCDriver::RootName, QMCDriver::Tau, QMCDriver::Traces, QMCDriver::traces_xml, QMCDriver::W, QMCDriver::walker_logs_xml, QMCDriver::wlog_manager_, and QMCDriver::wOut.

Referenced by qmcplusplus::TEST_CASE().

173 {
174  deltaR.resize(W.getTotalNum());
175  drift.resize(W.getTotalNum());
176  qmcNode = cur;
177  //process common parameters
178  putQMCInfo(cur);
179  ////set the Tau parameter inside the Hamiltonian
180  //H.setTau(Tau);
181  //need to initialize properties
182  int numCopies = (H1.empty()) ? 1 : H1.size();
183  W.resetWalkerProperty(numCopies);
184  //create branchEngine first
185  if (!branchEngine)
186  {
187  branchEngine = std::make_unique<BranchEngineType>(Tau, W.getGlobalNumWalkers());
188  }
189  //execute the put function implemented by the derived classes
190  put(cur);
191  //create and initialize estimator
192  Estimators = branchEngine->getEstimatorManager();
193  if (Estimators == nullptr)
194  {
195  branchEngine->setEstimatorManager(std::make_unique<EstimatorManagerBase>(myComm));
196  Estimators = branchEngine->getEstimatorManager();
197  branchEngine->read(h5FileRoot);
198  }
199  if (DriftModifier == 0)
201  DriftModifier->parseXML(cur);
202 #if !defined(REMOVE_TRACEMANAGER)
203  //create and initialize traces
204  if (!Traces)
205  Traces = std::make_unique<TraceManager>(myComm);
207 #endif
208  //create and initialize traces
209  if (!wlog_manager_)
210  {
211  WalkerLogInput walker_logs_input(walker_logs_xml);
212  wlog_manager_ = std::make_unique<WalkerLogManager>(walker_logs_input, allow_walker_logs, RootName, myComm);
213  }
214  branchEngine->put(cur);
215  Estimators->put(H, cur);
216  if (!wOut)
217  wOut = std::make_unique<HDFWalkerOutput>(W.getTotalNum(), RootName, myComm);
218  branchEngine->start(RootName);
219  branchEngine->write(RootName);
220  //use new random seeds
221  if (ResetRandom)
222  {
223  app_log() << " Regenerate random seeds." << std::endl;
225  ResetRandom = false;
226  }
227  //flush the std::ostreams
228  infoSummary.flush();
229  infoLog.flush();
230  //increment QMCCounter of the branch engine
231  branchEngine->advanceQMCCounter();
232 }
std::string h5FileRoot
the root of h5File
Definition: QMCDriver.h:315
std::string RootName
root of all the output files
Definition: QMCDriver.h:317
InfoStream infoSummary
size_t getTotalNum() const
Definition: ParticleSet.h:493
std::ostream & app_log()
Definition: OutputManager.h:65
xmlNodePtr qmcNode
pointer to qmc node in xml file
Definition: QMCDriver.h:310
ParticleSet::ParticlePos drift
temporary storage for drift
Definition: QMCDriver.h:347
std::unique_ptr< TraceManager > Traces
Traces manager.
Definition: QMCDriver.h:195
size_t getGlobalNumWalkers() const
return the total number of active walkers among a MPI group
virtual bool put(xmlNodePtr cur)=0
InfoStream infoLog
std::unique_ptr< HDFWalkerOutput > wOut
record engine for walkers
Definition: QMCDriver.h:332
virtual bool parseXML(xmlNodePtr cur)
Communicate * myComm
pointer to Communicate
Definition: MPIObjectBase.h:62
std::unique_ptr< BranchEngineType > branchEngine
branch engine
Definition: QMCDriver.h:218
bool putQMCInfo(xmlNodePtr cur)
Parses the xml input file for parameter definitions for a single qmc simulation.
Definition: QMCDriver.cpp:399
QMCHamiltonian & H
Hamiltonian.
Definition: QMCDriver.h:329
DriftModifierBase * DriftModifier
drift modifer
Definition: QMCDriver.h:220
MCWalkerConfiguration & W
walker ensemble
Definition: QMCDriver.h:323
bool put(QMCHamiltonian &H, xmlNodePtr cur)
process xml tag associated with estimators
bool allow_walker_logs
whether to allow traces
Definition: QMCDriver.h:101
xmlNodePtr walker_logs_xml
traces xml
Definition: QMCDriver.h:103
void flush()
flush stream buffer
Definition: InfoStream.cpp:39
std::vector< QMCHamiltonian * > H1
a list of QMCHamiltonians for multiple method
Definition: QMCDriver.h:338
EstimatorManagerBase * Estimators
Observables manager.
Definition: QMCDriver.h:192
RealType Tau
timestep
Definition: QMCDriver.h:299
std::unique_ptr< WalkerLogManager > wlog_manager_
Traces manager.
Definition: QMCDriver.h:198
xmlNodePtr traces_xml
traces xml
Definition: QMCDriver.h:98
static void make_seeds()
reset the generator
ParticleSet::ParticlePos deltaR
temporary storage for random displacement
Definition: QMCDriver.h:350
bool allow_traces
whether to allow traces
Definition: QMCDriver.h:96
void resetWalkerProperty(int ncopy=1)
reset the Property container of all the walkers
DriftModifierBase * createDriftModifier(xmlNodePtr cur, const Communicate *myComm)
create DriftModifier
bool ResetRandom
randomize it
Definition: QMCDriver.h:222

◆ putQMCInfo()

bool putQMCInfo ( xmlNodePtr  cur)
protected

Parses the xml input file for parameter definitions for a single qmc simulation.

Basic parameters are handled here and each driver will perform its own initialization with the input attribute list

  • checkpoint="-1|0|n" default=-1 – 1 = do not write anything – 0 = dump after the completion of a qmc section – n = dump after n blocks
  • kdelay = "0|1|n" default=0

Definition at line 399 of file QMCDriver.cpp.

References OhmmsAttributeSet::add(), QMCDriver::addWalkers(), qmcplusplus::app_log(), qmcplusplus::app_warning(), QMCDriver::AppendRun, QMCDriver::CurrentStep, QMCDriver::DumpConfig, WalkerConfigurations::getActiveWalkers(), MPIObjectBase::getName(), QMCDriver::IsQMCDriver, QMCDriver::kDelay, QMCDriver::m_param, QMCDriver::nBlocks, QMCDriver::nSteps, QMCDriver::nSubSteps, QMCDriver::nTargetWalkers, omp_get_max_threads(), QMCDriver::Period4CheckPoint, QMCDriver::Period4ConfigDump, QMCDriver::Period4WalkerDump, ParameterSet::put(), OhmmsAttributeSet::put(), qmcplusplus::qmc_common, QMCState::qmc_counter, QMCDriver::ResetRandom, and QMCDriver::W.

Referenced by QMCDriver::process(), and WaveFunctionTester::put().

400 {
401  if (!IsQMCDriver)
402  {
403  app_log() << getName() << " Skip QMCDriver::putQMCInfo " << std::endl;
404  return true;
405  }
406 
407  ////store the current nSteps and nStepsBetweenSamples
408  //int oldStepsBetweenSamples=nStepsBetweenSamples;
409  //int oldSteps=nSteps;
410 
411  //set the default walker to the number of threads times 10
412  Period4CheckPoint = 0;
413  int defaultw = omp_get_max_threads();
414  OhmmsAttributeSet aAttrib;
415  aAttrib.add(Period4CheckPoint, "checkpoint");
416  aAttrib.add(kDelay, "kdelay");
417  aAttrib.put(cur);
418  if (cur != NULL)
419  {
420  //initialize the parameter set
421  m_param.put(cur);
422 
423  xmlNodePtr tcur = cur->children;
424  //determine how often to print walkers to hdf5 file
425  while (tcur != NULL)
426  {
427  std::string cname((const char*)(tcur->name));
428  if (cname == "record")
429  {
430  //dump walkers for optimization
431  OhmmsAttributeSet rAttrib;
432  rAttrib.add(Period4WalkerDump, "stride");
433  rAttrib.add(Period4WalkerDump, "period");
434  rAttrib.put(tcur);
435  }
436  else if (cname == "checkpoint")
437  {
438  OhmmsAttributeSet rAttrib;
439  rAttrib.add(Period4CheckPoint, "stride");
440  rAttrib.add(Period4CheckPoint, "period");
441  rAttrib.put(tcur);
442  //DumpConfig=(Period4CheckPoint>0);
443  }
444  else if (cname == "dumpconfig")
445  {
446  OhmmsAttributeSet rAttrib;
447  rAttrib.add(Period4ConfigDump, "stride");
448  rAttrib.add(Period4ConfigDump, "period");
449  rAttrib.put(tcur);
450  }
451  else if (cname == "random")
452  {
453  ResetRandom = true;
454  }
455  tcur = tcur->next;
456  }
457  }
458 
459  // check input parameters collected by m_param
460  //set the minimum blocks
461  if (nBlocks < 1)
462  {
463  app_warning() << "Input parameter \"blocks\" must be positive! Set to 1. User input value " << nBlocks << std::endl;
464  nBlocks = 1;
465  }
466 
467  //set the minimum nSteps
468  if (nSteps < 1)
469  {
470  app_warning() << "Input parameter \"steps\" must be positive! Set to 1. User input value " << nSteps << std::endl;
471  nSteps = 1;
472  }
473 
474  //set the minimum nSubSteps
475  if (nSubSteps < 1)
476  {
477  app_warning() << "Input parameter \"substeps\" must be positive! Set to 1. User input value " << nSubSteps
478  << std::endl;
479  nSubSteps = 1;
480  }
481 
482  DumpConfig = (Period4CheckPoint >= 0);
483  if (Period4CheckPoint < 1)
485  //reset CurrentStep to zero if qmc/@continue='no'
486  if (!AppendRun)
487  CurrentStep = 0;
488 
489  //if walkers are initialized via <mcwalkerset/>, use the existing one
491  {
492  app_log() << "Using existing walkers " << std::endl;
493  }
494  else
495  {
496  app_log() << "Resetting walkers" << std::endl;
497  int nths(omp_get_max_threads());
498  nTargetWalkers = (std::max(nths, (nTargetWalkers / nths) * nths));
499  int nw = W.getActiveWalkers();
500  int ndiff = 0;
501  if (nw)
502  {
503  // nTargetWalkers == 0, if it is not set by the input file
504  ndiff = (nTargetWalkers) ? nTargetWalkers - nw : 0;
505  }
506  else
507  {
508  ndiff = (nTargetWalkers) ? nTargetWalkers : defaultw;
509  }
510  addWalkers(ndiff);
511  }
512 
513  return (W.getActiveWalkers() > 0);
514 }
std::ostream & app_warning()
Definition: OutputManager.h:69
size_t getActiveWalkers() const
return the number of active walkers
bool DumpConfig
flag to turn off dumping configurations
Definition: QMCDriver.h:226
std::ostream & app_log()
Definition: OutputManager.h:65
bool put(xmlNodePtr cur)
assign attributes to the set
Definition: AttributeSet.h:55
IndexType CurrentStep
current step
Definition: QMCDriver.h:263
bool AppendRun
flag to append or restart the run
Definition: QMCDriver.h:224
IndexType nTargetWalkers
the number of walkers
Definition: QMCDriver.h:287
bool put(std::istream &is) override
read from std::istream
Definition: ParameterSet.h:42
int Period4ConfigDump
period of recording walker positions and IDs for forward walking afterwards
Definition: QMCDriver.h:260
ParameterSet m_param
store any parameter that has to be read from a file
Definition: QMCDriver.h:320
IndexType nSubSteps
number of steps between a step: VMCs do not evaluate energies
Definition: QMCDriver.h:272
IndexType nSteps
maximum number of steps
Definition: QMCDriver.h:269
int kDelay
the number to delay updates by
Definition: QMCDriver.h:237
omp_int_t omp_get_max_threads()
Definition: OpenMP.h:26
class to handle a set of attributes of an xmlNode
Definition: AttributeSet.h:24
int qmc_counter
init for <qmc> section
Definition: qmc_common.h:31
MCWalkerConfiguration & W
walker ensemble
Definition: QMCDriver.h:323
bool IsQMCDriver
true, if it is a real QMC engine
Definition: QMCDriver.h:228
int Period4CheckPoint
period of dumping walker configurations and everything else for restart
Definition: QMCDriver.h:242
const std::string & getName() const
return the name
Definition: MPIObjectBase.h:54
IndexType nBlocks
maximum number of blocks
Definition: QMCDriver.h:266
int Period4WalkerDump
period of recording walker configurations
Definition: QMCDriver.h:255
void addWalkers(int nwalkers)
Add walkers to the end of the ensemble of walkers.
Definition: QMCDriver.cpp:338
QMCState qmc_common
a unique QMCState during a run
Definition: qmc_common.cpp:111
void add(PDT &aparam, const std::string &aname, std::vector< PDT > candidate_values={}, TagStatus status=TagStatus::OPTIONAL)
add a new attribute
Definition: AttributeSet.h:42
bool ResetRandom
randomize it
Definition: QMCDriver.h:222

◆ putTraces()

void putTraces ( xmlNodePtr  txml)
inlineoverridevirtual

Implements QMCDriverInterface.

Definition at line 154 of file QMCDriver.h.

References QMCDriver::traces_xml.

154 { traces_xml = txml; }
xmlNodePtr traces_xml
traces xml
Definition: QMCDriver.h:98

◆ putWalkerLogs()

void putWalkerLogs ( xmlNodePtr  wlxml)
inlineoverridevirtual

Implements QMCDriverInterface.

Definition at line 158 of file QMCDriver.h.

References QMCDriver::walker_logs_xml.

158 { walker_logs_xml = wlxml; }
xmlNodePtr walker_logs_xml
traces xml
Definition: QMCDriver.h:103

◆ putWalkers()

void putWalkers ( std::vector< xmlNodePtr > &  wset)
overridevirtual

Read walker configurations from *.config.h5 files.

Parameters
wsetlist of xml elements containing mcwalkerset

Implements QMCDriverInterface.

Definition at line 253 of file QMCDriver.cpp.

References Communicate::allreduce(), Communicate::bcast(), WalkerConfigurations::getActiveWalkers(), ParticleSet::getTotalNum(), QMCDriver::h5FileRoot, MPIObjectBase::myComm, Communicate::rank(), WalkerConfigurations::setWalkerOffsets(), Communicate::size(), and QMCDriver::W.

254 {
255  if (wset.empty())
256  return;
257  int nfile = wset.size();
258  HDFWalkerInputManager W_in(W, W.getTotalNum(), myComm);
259  for (int i = 0; i < wset.size(); i++)
260  if (W_in.put(wset[i]))
261  h5FileRoot = W_in.getFileRoot();
262  //clear the walker set
263  wset.clear();
264  int nwtot = W.getActiveWalkers();
265  myComm->bcast(nwtot);
266  if (nwtot)
267  {
268  int np = myComm->size();
269  std::vector<int> nw(np, 0), nwoff(np + 1, 0);
270  nw[myComm->rank()] = W.getActiveWalkers();
271  myComm->allreduce(nw);
272  for (int ip = 0; ip < np; ++ip)
273  nwoff[ip + 1] = nwoff[ip] + nw[ip];
274  W.setWalkerOffsets(nwoff);
275  }
276 }
std::string h5FileRoot
the root of h5File
Definition: QMCDriver.h:315
int rank() const
return the rank
Definition: Communicate.h:116
size_t getActiveWalkers() const
return the number of active walkers
size_t getTotalNum() const
Definition: ParticleSet.h:493
void setWalkerOffsets(const std::vector< int > &o)
return the total number of active walkers among a MPI group
int size() const
return the number of tasks
Definition: Communicate.h:118
void allreduce(T &)
Communicate * myComm
pointer to Communicate
Definition: MPIObjectBase.h:62
MCWalkerConfiguration & W
walker ensemble
Definition: QMCDriver.h:323
void bcast(T &)

◆ recordBlock()

void recordBlock ( int  block)
overrideprotectedvirtual

record the state of the block

Parameters
blockcurrent block

virtual function with a default implementation

Implements QMCDriverInterface.

Definition at line 307 of file QMCDriver.cpp.

References QMCDriver::branchEngine, QMCDriver::checkpoint_timer_, QMCDriver::DumpConfig, MPIObjectBase::myComm, QMCDriver::Period4CheckPoint, QMCDriver::RootName, QMCDriver::W, QMCDriver::wOut, and RandomNumberControl::write().

Referenced by VMC::run(), RMC::run(), DMC::run(), and CSVMC::run().

308 {
309  if (DumpConfig && block % Period4CheckPoint == 0)
310  {
312  wOut->dump(W, block);
313  branchEngine->write(RootName, true); //save energy_history
315  }
316 }
NewTimer & checkpoint_timer_
Definition: QMCDriver.h:381
bool DumpConfig
flag to turn off dumping configurations
Definition: QMCDriver.h:226
std::string RootName
root of all the output files
Definition: QMCDriver.h:317
ScopeGuard< NewTimer > ScopedTimer
Definition: NewTimer.h:257
static void write(const std::string &fname, Communicate *comm)
write in parallel or serial
std::unique_ptr< HDFWalkerOutput > wOut
record engine for walkers
Definition: QMCDriver.h:332
Communicate * myComm
pointer to Communicate
Definition: MPIObjectBase.h:62
std::unique_ptr< BranchEngineType > branchEngine
branch engine
Definition: QMCDriver.h:218
MCWalkerConfiguration & W
walker ensemble
Definition: QMCDriver.h:323
int Period4CheckPoint
period of dumping walker configurations and everything else for restart
Definition: QMCDriver.h:242

◆ requestTraces()

void requestTraces ( bool  traces)
inlineoverridevirtual

Implements QMCDriverInterface.

Definition at line 156 of file QMCDriver.h.

References QMCDriver::allow_traces.

156 { allow_traces = traces; }
bool allow_traces
whether to allow traces
Definition: QMCDriver.h:96

◆ requestWalkerLogs()

void requestWalkerLogs ( bool  allow_walker_logs_)
inlineoverridevirtual

Implements QMCDriverInterface.

Definition at line 160 of file QMCDriver.h.

References QMCDriver::allow_walker_logs.

160 { allow_walker_logs = allow_walker_logs_; }
bool allow_walker_logs
whether to allow traces
Definition: QMCDriver.h:101

◆ setBranchEngine()

void setBranchEngine ( std::unique_ptr< BranchEngineType > &&  be)
inlineoverride

set the BranchEngineType

Definition at line 171 of file QMCDriver.h.

References QMCDriver::branchEngine.

171 { branchEngine = std::move(be); }
std::unique_ptr< BranchEngineType > branchEngine
branch engine
Definition: QMCDriver.h:218

◆ setStatus()

void setStatus ( const std::string &  aname,
const std::string &  h5name,
bool  append 
)
overridevirtual

Set the status of the QMCDriver.

Parameters
anamethe root file name
h5nameroot name of the master hdf5 file containing previous qmcrun
appendif true, the run is a continuation of the previous qmc

All output files will be of the form "aname.s00X.suffix", where "X" is number of previous QMC runs for the simulation and "suffix" is the suffix for the output file.

Implements QMCDriverInterface.

Definition at line 234 of file QMCDriver.cpp.

References qmcplusplus::app_log(), QMCDriver::AppendRun, QMCDriver::h5FileRoot, QMCDriver::QMCType, and QMCDriver::RootName.

235 {
236  RootName = aname;
237  app_log() << "\n========================================================="
238  << "\n Start " << QMCType << "\n File Root " << RootName;
239  if (append)
240  app_log() << " append = yes ";
241  else
242  app_log() << " append = no ";
243  app_log() << "\n=========================================================" << std::endl;
244  if (h5name.size())
245  h5FileRoot = h5name;
246  AppendRun = append;
247 }
std::string h5FileRoot
the root of h5File
Definition: QMCDriver.h:315
std::string RootName
root of all the output files
Definition: QMCDriver.h:317
std::ostream & app_log()
Definition: OutputManager.h:65
bool AppendRun
flag to append or restart the run
Definition: QMCDriver.h:224
const std::string QMCType
type of QMC driver
Definition: QMCDriver.h:313

◆ setTau()

void setTau ( RealType  i)
inline

Definition at line 186 of file QMCDriver.h.

References QMCDriver::Tau.

186 { Tau = i; }
RealType Tau
timestep
Definition: QMCDriver.h:299

◆ setUpdateMode()

void setUpdateMode ( bool  pbyp)
inlineoverridevirtual

set the update mode

Parameters
pbypif true, use particle-by-particle update

Implements QMCDriverInterface.

Definition at line 122 of file QMCDriver.h.

References QMCDriver::qmc_driver_mode, and QMCDriver::QMC_UPDATE_MODE.

122 { qmc_driver_mode[QMC_UPDATE_MODE] = pbyp; }
std::bitset< QMC_MODE_MAX > qmc_driver_mode
bits to classify QMCDriver
Definition: QMCDriver.h:93

◆ setValue()

void setValue ( const std::string &  aname,
PDT  x 
)
inline

Definition at line 165 of file QMCDriver.h.

References QMCDriver::m_param, and ParameterSet::setValue().

166  {
167  m_param.setValue(aname, x);
168  }
ParameterSet m_param
store any parameter that has to be read from a file
Definition: QMCDriver.h:320
void setValue(const std::string &aname_in, PDT aval)

◆ setWalkerOffsets()

void setWalkerOffsets ( )

set global offsets of the walkers

Definition at line 370 of file QMCDriver.cpp.

References Communicate::allreduce(), qmcplusplus::app_log(), WalkerConfigurations::EnsembleProperty, WalkerConfigurations::getActiveWalkers(), MPIObjectBase::myComm, MCDataType< T >::NumSamples, Communicate::rank(), WalkerConfigurations::setWalkerOffsets(), Communicate::size(), QMCDriver::W, and MCDataType< T >::Weight.

Referenced by QMCDriver::addWalkers(), and DMC::resetUpdateEngines().

371 {
372  std::vector<int> nw(myComm->size(), 0), nwoff(myComm->size() + 1, 0);
373  nw[myComm->rank()] = W.getActiveWalkers();
374  myComm->allreduce(nw);
375  for (int ip = 0; ip < myComm->size(); ip++)
376  nwoff[ip + 1] = nwoff[ip] + nw[ip];
377  W.setWalkerOffsets(nwoff);
378  long id = nwoff[myComm->rank()];
379  for (int iw = 0; iw < nw[myComm->rank()]; ++iw, ++id)
380  {
381  W[iw]->setWalkerID(id);
382  W[iw]->setParentID(id);
383  }
384  app_log() << " Total number of walkers: " << W.EnsembleProperty.NumSamples << std::endl;
385  app_log() << " Total weight: " << W.EnsembleProperty.Weight << std::endl;
386 }
int rank() const
return the rank
Definition: Communicate.h:116
size_t getActiveWalkers() const
return the number of active walkers
std::ostream & app_log()
Definition: OutputManager.h:65
void setWalkerOffsets(const std::vector< int > &o)
return the total number of active walkers among a MPI group
int size() const
return the number of tasks
Definition: Communicate.h:118
void allreduce(T &)
Communicate * myComm
pointer to Communicate
Definition: MPIObjectBase.h:62
MCWalkerConfiguration & W
walker ensemble
Definition: QMCDriver.h:323
MCDataType< FullPrecRealType > EnsembleProperty

Member Data Documentation

◆ allow_traces

bool allow_traces

whether to allow traces

Definition at line 96 of file QMCDriver.h.

Referenced by QMCDriver::process(), QMCDriver::QMCDriver(), and QMCDriver::requestTraces().

◆ allow_walker_logs

bool allow_walker_logs

whether to allow traces

Definition at line 101 of file QMCDriver.h.

Referenced by QMCDriver::process(), QMCDriver::QMCDriver(), and QMCDriver::requestWalkerLogs().

◆ AppendRun

bool AppendRun
protected

flag to append or restart the run

Definition at line 224 of file QMCDriver.h.

Referenced by QMCFixedSampleLinearOptimize::processOptXML(), QMCDriver::putQMCInfo(), QMCDriver::QMCDriver(), and QMCDriver::setStatus().

◆ branchEngine

◆ checkpoint_timer_

NewTimer& checkpoint_timer_
private

Definition at line 381 of file QMCDriver.h.

Referenced by QMCDriver::recordBlock().

◆ CurrentStep

◆ deltaR

ParticleSet::ParticlePos deltaR
protected

temporary storage for random displacement

Definition at line 350 of file QMCDriver.h.

Referenced by QMCDriver::process().

◆ drift

ParticleSet::ParticlePos drift
protected

temporary storage for drift

Definition at line 347 of file QMCDriver.h.

Referenced by QMCDriver::process().

◆ DriftModifier

DriftModifierBase* DriftModifier
protected

◆ driver_scope_profiler_

ScopedProfiler driver_scope_profiler_
private

profile the driver lifetime

Definition at line 383 of file QMCDriver.h.

◆ DumpConfig

bool DumpConfig
protected

flag to turn off dumping configurations

Definition at line 226 of file QMCDriver.h.

Referenced by QMCDriver::finalize(), VMC::put(), CSVMC::put(), QMCDriver::putQMCInfo(), QMCDriver::QMCDriver(), QMCDriver::recordBlock(), VMC::run(), DMC::run(), and CSVMC::run().

◆ Estimators

◆ H

◆ H1

std::vector<QMCHamiltonian*> H1
protected

a list of QMCHamiltonians for multiple method

Definition at line 338 of file QMCDriver.h.

Referenced by QMCDriver::add_H_and_Psi(), QMCDriver::process(), and CSVMC::resetRun().

◆ h5FileRoot

◆ IsQMCDriver

bool IsQMCDriver
protected

true, if it is a real QMC engine

Definition at line 228 of file QMCDriver.h.

Referenced by QMCDriver::putQMCInfo(), QMCDriver::QMCDriver(), and QMCFixedSampleLinearOptimize::QMCFixedSampleLinearOptimize().

◆ kDelay

int kDelay
protected

the number to delay updates by

Definition at line 237 of file QMCDriver.h.

Referenced by QMCDriver::putQMCInfo().

◆ m_oneover2tau

RealType m_oneover2tau
protected

Time-step factor $ 1/(2\tau)$.

Definition at line 305 of file QMCDriver.h.

◆ m_param

◆ m_sqrttau

RealType m_sqrttau
protected

Time-step factor $ \sqrt{\tau}$.

Definition at line 307 of file QMCDriver.h.

◆ MaxCPUSecs

int MaxCPUSecs
protected

maximum cpu in secs

Definition at line 302 of file QMCDriver.h.

Referenced by QMCDriver::QMCDriver(), VMC::run(), RMC::run(), and DMC::run().

◆ mcwalkerNodePtr

std::vector<xmlNodePtr> mcwalkerNodePtr
protected

a list of mcwalkerset element

Definition at line 344 of file QMCDriver.h.

Referenced by QMCFixedSampleLinearOptimize::processOptXML().

◆ MyCounter

int MyCounter
protected

the number of times this QMCDriver is executed

MyCounter is initialized to zero by the constructor and is incremented whenever a run is completed by calling finalize(int block) or using MyCounter++ as in RQMC.

Definition at line 235 of file QMCDriver.h.

Referenced by QMCDriver::finalize(), QMCFixedSampleLinearOptimize::finish(), VMC::put(), CSVMC::put(), and QMCDriver::QMCDriver().

◆ nAccept

IndexType nAccept
protected

counter for number of moves accepted

Definition at line 278 of file QMCDriver.h.

Referenced by QMCDriver::QMCDriver().

◆ nBlocks

◆ nBlocksBetweenRecompute

IndexType nBlocksBetweenRecompute
protected

the number of blocks between recomptePsi

Definition at line 284 of file QMCDriver.h.

Referenced by QMCDriver::QMCDriver(), VMC::run(), and DMC::run().

◆ nReject

IndexType nReject
protected

counter for number of moves /rejected

Definition at line 281 of file QMCDriver.h.

Referenced by QMCDriver::QMCDriver().

◆ nSamplesPerThread

RealType nSamplesPerThread
protected

samples per thread

Definition at line 293 of file QMCDriver.h.

Referenced by VMC::put(), CSVMC::put(), QMCDriver::QMCDriver(), VMC::resetRun(), and CSVMC::resetRun().

◆ nSteps

◆ nStepsBetweenSamples

IndexType nStepsBetweenSamples
protected

alternate method of setting QMC run parameters

Definition at line 291 of file QMCDriver.h.

Referenced by VMC::put(), CSVMC::put(), QMCDriver::QMCDriver(), and VMC::VMC().

◆ nSubSteps

IndexType nSubSteps
protected

number of steps between a step: VMCs do not evaluate energies

Definition at line 272 of file QMCDriver.h.

Referenced by VMC::put(), CSVMC::put(), QMCDriver::putQMCInfo(), QMCDriver::QMCDriver(), VMC::resetRun(), and RMC::resetRun().

◆ nTargetPopulation

RealType nTargetPopulation
protected

target population

Definition at line 295 of file QMCDriver.h.

Referenced by VMC::put(), CSVMC::put(), QMCDriver::QMCDriver(), and VMC::resetRun().

◆ nTargetSamples

IndexType nTargetSamples
protected

the number of saved samples

Definition at line 289 of file QMCDriver.h.

Referenced by VMC::put(), CSVMC::put(), QMCDriver::QMCDriver(), VMC::resetRun(), and CSVMC::resetRun().

◆ nTargetWalkers

IndexType nTargetWalkers
protected

the number of walkers

Definition at line 287 of file QMCDriver.h.

Referenced by QMCDriver::finalize(), QMCDriver::putQMCInfo(), and QMCDriver::QMCDriver().

◆ nWarmupSteps

IndexType nWarmupSteps
protected

number of warmup steps

Definition at line 275 of file QMCDriver.h.

Referenced by QMCDriver::QMCDriver(), VMC::resetRun(), CSVMC::resetRun(), and RMC::resetRun().

◆ Period4CheckPoint

int Period4CheckPoint
protected

period of dumping walker configurations and everything else for restart

The unit is a block.

Definition at line 242 of file QMCDriver.h.

Referenced by VMC::put(), CSVMC::put(), QMCDriver::putQMCInfo(), QMCDriver::QMCDriver(), QMCDriver::recordBlock(), and DMC::run().

◆ Period4CheckProperties

int Period4CheckProperties
protected

period of dumping walker positions and IDs for Forward Walking

The unit is in steps.Period to recalculate the walker properties from scratch.

Definition at line 249 of file QMCDriver.h.

Referenced by QMCDriver::QMCDriver(), VMC::run(), RMC::run(), DMC::run(), and CSVMC::run().

◆ Period4ConfigDump

int Period4ConfigDump
protected

period of recording walker positions and IDs for forward walking afterwards

Definition at line 260 of file QMCDriver.h.

Referenced by QMCDriver::putQMCInfo(), and QMCDriver::QMCDriver().

◆ Period4WalkerDump

int Period4WalkerDump
protected

period of recording walker configurations

Default is 0 indicating that only the last configuration will be saved.

Definition at line 255 of file QMCDriver.h.

Referenced by VMC::put(), CSVMC::put(), QMCDriver::putQMCInfo(), QMCDriver::QMCDriver(), RMC::resetRun(), VMC::run(), RMC::run(), and CSVMC::run().

◆ project_data_

const ProjectData& project_data_
protected

top-level project data information

Definition at line 216 of file QMCDriver.h.

Referenced by QMCFixedSampleLinearOptimize::processOptXML().

◆ Psi

◆ Psi1

std::vector<TrialWaveFunction*> Psi1
protected

a list of TrialWaveFunctions for multiple method

Definition at line 335 of file QMCDriver.h.

Referenced by QMCDriver::add_H_and_Psi(), and CSVMC::resetRun().

◆ qmc_driver_mode

std::bitset<QMC_MODE_MAX> qmc_driver_mode

bits to classify QMCDriver

  • qmc_driver_mode[QMC_UPDATE_MODE]? particle-by-particle: walker-by-walker
  • qmc_driver_mode[QMC_MULTIPLE]? multiple H/Psi : single H/Psi
  • qmc_driver_mode[QMC_OPTIMIZE]? optimization : vmc/dmc/rmc

Definition at line 93 of file QMCDriver.h.

Referenced by CSVMC::CSVMC(), DMC::DMC(), QMCDriver::getDriverMode(), QMCFixedSampleLinearOptimize::QMCFixedSampleLinearOptimize(), VMC::resetRun(), CSVMC::resetRun(), RMC::resetRun(), DMC::resetUpdateEngines(), RMC::RMC(), VMC::run(), RMC::run(), DMC::run(), CSVMC::run(), QMCDriver::setUpdateMode(), and VMC::VMC().

◆ qmcNode

xmlNodePtr qmcNode
protected

◆ QMCType

const std::string QMCType
protected

type of QMC driver

Definition at line 313 of file QMCDriver.h.

Referenced by QMCDriver::getEngineName(), and QMCDriver::setStatus().

◆ ResetRandom

bool ResetRandom
protected

randomize it

Definition at line 222 of file QMCDriver.h.

Referenced by QMCDriver::process(), QMCDriver::putQMCInfo(), and QMCDriver::QMCDriver().

◆ Rng

◆ RootName

◆ rotation

int rotation
protected

◆ SpinMass

RealType SpinMass
protected

spin mass for spinor calcs

Definition at line 353 of file QMCDriver.h.

Referenced by QMCDriver::QMCDriver(), VMC::resetRun(), and DMC::resetUpdateEngines().

◆ Tau

◆ Traces

std::unique_ptr<TraceManager> Traces

◆ traces_xml

xmlNodePtr traces_xml

traces xml

Definition at line 98 of file QMCDriver.h.

Referenced by QMCDriver::process(), and QMCDriver::putTraces().

◆ W

◆ walker_logs_xml

xmlNodePtr walker_logs_xml

traces xml

Definition at line 103 of file QMCDriver.h.

Referenced by QMCDriver::process(), QMCDriver::putWalkerLogs(), and QMCDriver::QMCDriver().

◆ wlog_manager_

std::unique_ptr<WalkerLogManager> wlog_manager_

Traces manager.

Definition at line 198 of file QMCDriver.h.

Referenced by QMCDriver::process(), VMC::resetRun(), DMC::resetUpdateEngines(), VMC::run(), and DMC::run().

◆ wOut

std::unique_ptr<HDFWalkerOutput> wOut
protected

record engine for walkers

Definition at line 332 of file QMCDriver.h.

Referenced by QMCDriver::finalize(), QMCDriver::process(), QMCDriver::recordBlock(), VMC::run(), and CSVMC::run().

◆ qmcplusplus::QMCDriverNew

class qmcplusplus::QMCDriverNew

QMCDriverNew Base class for Unified Drivers.

General Principals

  • Parameters used unchanged from input object are not copied into class state
  • The driver state machine should be as minimal as possible.
  • In non performance critical areas favor clarity over clever optimizations.

Definition at line 75 of file QMCDriverNew.h.

+ Inheritance diagram for QMCDriverNew:
+ Collaboration diagram for QMCDriverNew:

Public Types

enum  { QMC_UPDATE_MODE, QMC_MULTIPLE, QMC_OPTIMIZE, QMC_WARMUP }
 separate but similar to QMCModeEnum More...
 
using RealType = QMCTraits::RealType
 
using IndexType = QMCTraits::IndexType
 
using FullPrecRealType = QMCTraits::FullPrecRealType
 
using MCPWalker = MCPopulation::MCPWalker
 
using WFBuffer = MCPopulation::WFBuffer
 
using SetNonLocalMoveHandler = std::function< void(QMCHamiltonian &)>
 
- Public Types inherited from QMCDriverInterface
using BranchEngineType = SimpleFixedNodeBranch
 
using FullPrecRealType = QMCTraits::FullPrecRealType
 
- Public Types inherited from MPIObjectBase
using mpi_comm_type = Communicate::mpi_comm_type
 

Public Member Functions

 QMCDriverNew (const ProjectData &project_data, QMCDriverInput &&input, const std::optional< EstimatorManagerInput > &global_emi, WalkerConfigurations &wc, MCPopulation &&population, const std::string timer_prefix, Communicate *comm, const std::string &QMC_driver_type)
 Constructor. More...
 
 QMCDriverNew (QMCDriverNew &&)=default
 Move Constructor. More...
 
 QMCDriverNew (const QMCDriverNew &)=delete
 Copy Constructor (disabled). More...
 
QMCDriverNewoperator= (const QMCDriverNew &)=delete
 Copy operator (disabled). More...
 
 ~QMCDriverNew () override
 
bool putQMCInfo (xmlNodePtr cur)
 
void makeLocalWalkers (int nwalkers, RealType reserve)
 Adjust populations local walkers to this number. More...
 
DriftModifierBaseget_drift_modifier () const
 
void recordBlock (int block) override
 record the state of the block More...
 
bool finalize (int block, bool dumpwalkers=true)
 finalize a qmc section More...
 
IndexType current () const
 return current step More...
 
void setStatus (const std::string &aname, const std::string &h5name, bool append) override
 Set the status of the QMCDriver. More...
 
void add_H_and_Psi (QMCHamiltonian *h, TrialWaveFunction *psi) override
 
void createRngsStepContexts (int num_crowds)
 Creates Random Number generators for crowds and step contexts. More...
 
void putWalkers (std::vector< xmlNodePtr > &wset) override
 Read walker configurations from *.config.h5 files. More...
 
RefVector< RandomBase< FullPrecRealType > > getRngRefs () const
 
RandomBase< FullPrecRealType > & getRng (int i) override
 return the i-th random generator More...
 
std::string getEngineName () override
 intended for logging output and debugging you should base behavior on type preferably at compile time or if necessary at runtime using and protected by dynamic cast. More...
 
unsigned long getDriverMode () override
 
IndexType get_num_living_walkers () const
 
IndexType get_num_dead_walkers () const
 
const QMCDriverInputgetQMCDriverInput () const
 
- Public Member Functions inherited from QMCDriverInterface
virtual bool run ()=0
 
virtual QMCRunType getRunType ()=0
 
virtual ~QMCDriverInterface ()
 
virtual void setBranchEngine (std::unique_ptr< BranchEngineType > &&be)
 
virtual std::unique_ptr< BranchEngineTypegetBranchEngine ()
 
- Public Member Functions inherited from MPIObjectBase
 MPIObjectBase (Communicate *c)
 constructor with communicator More...
 
int rank () const
 return the rank of the communicator More...
 
int getGroupID () const
 return the group id of the communicator More...
 
CommunicategetCommunicator () const
 return myComm More...
 
CommunicategetCommRef () const
 return a TEMPORARY reference to Communicate More...
 
mpi_comm_type getMPI () const
 return MPI communicator if one wants to use MPI directly More...
 
bool is_manager () const
 return true if the rank == 0 More...
 
const std::string & getName () const
 return the name More...
 
void setName (const std::string &aname)
 

Public Attributes

std::bitset< QMC_MODE_MAXqmc_driver_mode_
 bits to classify QMCDriver More...
 
bool allow_walker_logs
 whether to allow walker logs More...
 
WalkerLogInput walker_logs_input
 walker logs input More...
 

Protected Member Functions

void initializeQMC (const AdjustedWalkerCounts &awc)
 Do common section starting tasks for VMC and DMC. More...
 
void measureImbalance (const std::string &tag) const
 inject additional barrier and measure load imbalance. More...
 
void endBlock ()
 end of a block operations. Aggregates statistics across all MPI ranks and write to disk. More...
 
QMCDriverInput qmcdriver_input_
 
RealType max_disp_sq_
 
they should be limited to values that can be changed from input or are live state. More...
 
IndexType target_samples_
 the number of saved samples More...
 
IndexType nBlocksBetweenRecompute
 the number of blocks between recomptePsi More...
 
UPtrVector< Crowdcrowds_
 }@ More...
 
std::string h5_file_root_
 
std::unique_ptr< DriftModifierBasedrift_modifier_
 drift modifer More...
 
int k_delay
 the number to delay updates by More...
 
int walker_dump_period
 period of recording walker configurations More...
 
IndexType current_step_
 
size_t steps_per_block_ = 0
 actual number of steps per block More...
 
IndexType nAccept
 counter for number of moves accepted More...
 
IndexType nReject
 counter for number of moves /rejected More...
 
RealType m_oneover2tau
 Time-step factor $ 1/(2\tau)$. More...
 
RealType m_sqrttau
 Time-step factor $ \sqrt{\tau}$. More...
 
const std::string QMCType
 type of qmc: assigned by subclasses More...
 
MCPopulation population_
 the entire (on node) walker population it serves VMCBatch and DMCBatch right now but will be polymorphic More...
 
struct DriverWalkerResourceCollection golden_resource_
 the golden multi walker shared resource serves ParticleSet TrialWaveFunction right now but actually should be based on MCPopulation. More...
 
const MultiWalkerDispatchers dispatchers_
 multi walker dispatchers More...
 
std::unique_ptr< EstimatorManagerNewestimator_manager_
 Observables manager Has very problematic owner ship and life cycle. More...
 
std::unique_ptr< HDFWalkerOutputwOut
 record engine for walkers More...
 
UPtrVector< ContextForStepsstep_contexts_
 Per crowd move contexts, this is where the DistanceTables etc. More...
 
UPtrVector< RandomBase< FullPrecRealType > > Rng
 Random number generators. More...
 
std::vector< xmlNodePtr > mcwalkerNodePtr
 a list of mcwalkerset element More...
 
DriverTimers timers_
 period of dumping walker configurations and everything else for restart More...
 
ScopedProfiler driver_scope_profiler_
 profile the driver lifetime More...
 
const ProjectDataproject_data_
 project info for accessing global fileroot and series id More...
 
WalkerConfigurationswalker_configs_ref_
 
class qmcplusplus::testing::VMCBatchedTest
 
class qmcplusplus::testing::DMCBatchedTest
 
class qmcplusplus::testing::QMCDriverNewTestWrapper
 
std::ostream & operator<< (std::ostream &o_stream, const QMCDriverNew &qmcd)
 
const std::string & get_root_name () const override
 
bool put (xmlNodePtr cur) override
 
More...
 
void process (xmlNodePtr cur) override=0
 QMCDriverNew driver second (3rd, 4th...) stage of constructing a valid driver. More...
 
void setUpdateMode (bool pbyp) override
 should be set in input don't see a reason to set individually More...
 
void putTraces (xmlNodePtr txml) override
 
void requestTraces (bool allow_traces) override
 
void putWalkerLogs (xmlNodePtr wlxml) override
 
void requestWalkerLogs (bool allow_walker_logs_) override
 
static void initialLogEvaluation (int crowd_id, UPtrVector< Crowd > &crowds, UPtrVector< ContextForSteps > &step_context)
 
template<typename RT , CoordsType CT>
static void scaleBySqrtTau (const TauParams< RT, CT > &taus, MCCoords< CT > &coords)
 
template<typename RT , CoordsType CT>
static void computeLogGreensFunction (const MCCoords< CT > &coords, const TauParams< RT, CT > &taus, std::vector< QMCTraits::RealType > &log_gb)
 calculates Green Function from displacements stored in MCCoords [param, out] log_g More...
 
static QMCDriverNew::AdjustedWalkerCounts adjustGlobalWalkerCount (Communicate &comm, const IndexType current_configs, const IndexType requested_total_walkers, const IndexType requested_walkers_per_rank, const RealType reserve_walkers, int num_crowds)
 }@ More...
 
static size_t determineStepsPerBlock (IndexType global_walkers, IndexType requested_samples, IndexType requested_steps, IndexType blocks)
 pure function calculating the actual number of steps per block More...
 
static void checkNumCrowdsLTNumThreads (const int num_crowds)
 
static void checkLogAndGL (Crowd &crowd, const std::string_view location)
 check logpsi and grad and lap against values computed from scratch More...
 
static void setWalkerOffsets (WalkerConfigurations &, Communicate *comm)
 update the global offsets of walker configurations after active walkers being touched. More...
 

Additional Inherited Members

- Protected Attributes inherited from MPIObjectBase
CommunicatemyComm
 pointer to Communicate More...
 
std::string ClassName
 class Name More...
 
std::string myName
 name of the object More...
 

Member Typedef Documentation

◆ FullPrecRealType

Definition at line 80 of file QMCDriverNew.h.

◆ IndexType

Definition at line 79 of file QMCDriverNew.h.

◆ MCPWalker

Definition at line 93 of file QMCDriverNew.h.

◆ RealType

Definition at line 78 of file QMCDriverNew.h.

◆ SetNonLocalMoveHandler

using SetNonLocalMoveHandler = std::function<void(QMCHamiltonian&)>

Definition at line 96 of file QMCDriverNew.h.

◆ WFBuffer

Definition at line 94 of file QMCDriverNew.h.

Member Enumeration Documentation

◆ anonymous enum

anonymous enum

separate but similar to QMCModeEnum

a code smell

Enumerator
QMC_UPDATE_MODE 
QMC_MULTIPLE 
QMC_OPTIMIZE 
QMC_WARMUP 

Definition at line 85 of file QMCDriverNew.h.

Constructor & Destructor Documentation

◆ QMCDriverNew() [1/3]

QMCDriverNew ( const ProjectData project_data,
QMCDriverInput &&  input,
const std::optional< EstimatorManagerInput > &  global_emi,
WalkerConfigurations wc,
MCPopulation &&  population,
const std::string  timer_prefix,
Communicate comm,
const std::string &  QMC_driver_type 
)

Constructor.

Has nasty workaround for RandomNumberControl.

Num crowds must be less than omp_get_max_threads because RandomNumberControl is global c lib function masquerading as a C++ object.

Definition at line 46 of file QMCDriverNew.cpp.

References qmcplusplus::comm, qmcplusplus::createDriftModifier(), QMCDriverNew::drift_modifier_, QMCDriverNew::estimator_manager_, QMCDriverInput::get_drift_modifier(), QMCDriverInput::get_drift_modifier_unr_a(), QMCDriverInput::get_estimator_manager_input(), MCPopulation::get_golden_hamiltonian(), QMCDriverNew::get_root_name(), qmcplusplus::lattice, QMCDriverNew::max_disp_sq_, MPIObjectBase::myComm, QMCDriverNew::population_, QMCDriverNew::qmcdriver_input_, and QMCDriverNew::wOut.

55  qmcdriver_input_(std::move(input)),
56  QMCType(QMC_driver_type),
57  population_(std::move(population)),
59  estimator_manager_(nullptr),
60  timers_(timer_prefix),
62  project_data_(project_data),
64 {
65  // This is done so that the application level input structures reflect the actual input to the code.
66  // While the actual simulation objects still take singular input structures at construction.
67  auto makeEstimatorManagerInput = [](auto& global_emi, auto& local_emi) -> EstimatorManagerInput {
68  if (global_emi.has_value() && local_emi.has_value())
69  return {global_emi.value(), local_emi.value()};
70  else if (global_emi.has_value())
71  return {global_emi.value()};
72  else if (local_emi.has_value())
73  return {local_emi.value()};
74  else
75  return {};
76  };
77 
79  std::make_unique<EstimatorManagerNew>(comm,
80  makeEstimatorManagerInput(global_emi,
82  population_.get_golden_hamiltonian(), population.get_golden_electrons(),
83  population.get_golden_twf());
84 
85  drift_modifier_.reset(
87 
88  // This needs to be done here to keep dependency on CrystalLattice out of the QMCDriverInput.
89  max_disp_sq_ = input.get_max_disp_sq();
90  if (max_disp_sq_ < 0)
91  {
92  auto& lattice = population.get_golden_electrons().getLattice();
93  max_disp_sq_ = lattice.LR_rc * lattice.LR_rc;
94  }
95 
96  wOut = std::make_unique<HDFWalkerOutput>(population.get_golden_electrons().getTotalNum(), get_root_name(), myComm);
97 }
RealType get_drift_modifier_unr_a() const
MCPopulation population_
the entire (on node) walker population it serves VMCBatch and DMCBatch right now but will be polymorp...
Definition: QMCDriverNew.h:426
QMCHamiltonian & get_golden_hamiltonian()
Definition: MCPopulation.h:181
std::unique_ptr< EstimatorManagerNew > estimator_manager_
Observables manager Has very problematic owner ship and life cycle.
Definition: QMCDriverNew.h:443
const MultiWalkerDispatchers dispatchers_
multi walker dispatchers
Definition: QMCDriverNew.h:436
CrystalLattice< OHMMS_PRECISION, OHMMS_DIM > lattice
std::unique_ptr< HDFWalkerOutput > wOut
record engine for walkers
Definition: QMCDriverNew.h:446
const std::string & get_root_name() const override
Definition: QMCDriverNew.h:331
const std::string QMCType
type of qmc: assigned by subclasses
Definition: QMCDriverNew.h:421
WalkerConfigurations & walker_configs_ref_
Definition: QMCDriverNew.h:481
Communicate * myComm
pointer to Communicate
Definition: MPIObjectBase.h:62
const std::string get_drift_modifier() const
std::unique_ptr< DriftModifierBase > drift_modifier_
drift modifer
Definition: QMCDriverNew.h:394
const std::optional< EstimatorManagerInput > & get_estimator_manager_input() const
const ProjectData & project_data_
project info for accessing global fileroot and series id
Definition: QMCDriverNew.h:478
ScopedProfiler driver_scope_profiler_
profile the driver lifetime
Definition: QMCDriverNew.h:475
testing::ValidSpinDensityInput input
MPIObjectBase(Communicate *c)
constructor with communicator
QMCDriverInput qmcdriver_input_
Definition: QMCDriverNew.h:372
DriverTimers timers_
period of dumping walker configurations and everything else for restart
Definition: QMCDriverNew.h:472
RealType max_disp_sq_
they should be limited to values that can be changed from input or are live state.
Definition: QMCDriverNew.h:380
DriftModifierBase * createDriftModifier(xmlNodePtr cur, const Communicate *myComm)
create DriftModifier

◆ QMCDriverNew() [2/3]

QMCDriverNew ( QMCDriverNew &&  )
default

Move Constructor.

◆ QMCDriverNew() [3/3]

QMCDriverNew ( const QMCDriverNew )
delete

Copy Constructor (disabled).

◆ ~QMCDriverNew()

~QMCDriverNew ( )
override

Definition at line 112 of file QMCDriverNew.cpp.

References RandomNumberControl::Children, and QMCDriverNew::Rng.

113 {
114  for (int i = 0; i < Rng.size(); ++i)
115  if (Rng[i])
116  RandomNumberControl::Children[i].reset(Rng[i].release());
117 }
static UPtrVector< RandomBase< FullPrecRealType > > Children
UPtrVector< RandomBase< FullPrecRealType > > Rng
Random number generators.
Definition: QMCDriverNew.h:453

Member Function Documentation

◆ add_H_and_Psi()

void add_H_and_Psi ( QMCHamiltonian h,
TrialWaveFunction psi 
)
inlineoverridevirtual

Implements QMCDriverInterface.

Definition at line 195 of file QMCDriverNew.h.

195 {};

◆ adjustGlobalWalkerCount()

QMCDriverNew::AdjustedWalkerCounts adjustGlobalWalkerCount ( Communicate comm,
const IndexType  current_configs,
const IndexType  requested_total_walkers,
const IndexType  requested_walkers_per_rank,
const RealType  reserve_walkers,
int  num_crowds 
)
staticprotected

}@

pure function returning AdjustedWalkerCounts data structure

The logic is now walker counts is fairly simple. TotalWalkers trumps all other walker parameters If TotalWalkers is absent walkers_per_rank is used. if they are both absent then the default is one walker per crowd, each rank has crowds walkers. if crowds aren't specified you get one per main level thread.

You can have crowds or ranks with no walkers. You cannot have more crowds than threads.

passing num_ranks instead of internally querying comm->size() makes unit testing much quicker.

Definition at line 407 of file QMCDriverNew.cpp.

References Communicate::allreduce(), qmcplusplus::app_warning(), QMCDriverNew::checkNumCrowdsLTNumThreads(), qmcplusplus::comm, error(), fairDivide(), qmcplusplus::num_ranks, Communicate::rank(), Communicate::size(), and QMCDriverNew::AdjustedWalkerCounts::walkers_per_rank.

Referenced by QMCDriverNewTestWrapper::process(), VMCBatched::process(), DMCBatched::process(), QMCFixedSampleLinearOptimizeBatched::processOptXML(), and QMCDriverNewTestWrapper::testAdjustGlobalWalkerCount().

413 {
414  const int num_ranks = comm.size();
415  const int rank_id = comm.rank();
416 
417  // Step 1. set num_crowds by input and Concurrency::maxCapacity<>()
418  checkNumCrowdsLTNumThreads(num_crowds);
419  if (num_crowds == 0)
420  num_crowds = Concurrency::maxCapacity<>();
421 
422  AdjustedWalkerCounts awc{0, {}, {}, reserve_walkers};
423  awc.walkers_per_rank.resize(num_ranks, 0);
424 
425  // Step 2. decide awc.global_walkers and awc.walkers_per_rank based on input values
426  if (requested_total_walkers != 0)
427  {
428  if (requested_total_walkers < num_ranks)
429  {
430  std::ostringstream error;
431  error << "Running on " << num_ranks << " MPI ranks. The request of " << requested_total_walkers
432  << " global walkers cannot be satisfied! Need at least one walker per MPI rank.";
433  throw UniformCommunicateError(error.str());
434  }
435  if (requested_walkers_per_rank != 0 && requested_total_walkers != requested_walkers_per_rank * num_ranks)
436  {
437  std::ostringstream error;
438  error << "Running on " << num_ranks << " MPI ranks, The request of " << requested_total_walkers
439  << " global walkers and " << requested_walkers_per_rank << " walkers per rank cannot be satisfied!";
440  throw UniformCommunicateError(error.str());
441  }
442  awc.global_walkers = requested_total_walkers;
443  awc.walkers_per_rank = fairDivide(requested_total_walkers, num_ranks);
444  }
445  else // requested_total_walkers == 0
446  {
447  if (requested_walkers_per_rank != 0)
448  awc.walkers_per_rank[rank_id] = requested_walkers_per_rank;
449  else if (current_configs) // requested_walkers_per_rank == 0 and current_configs > 0
450  awc.walkers_per_rank[rank_id] = current_configs;
451  else // requested_walkers_per_rank == 0 and current_configs == 0
452  awc.walkers_per_rank[rank_id] = num_crowds;
453  comm.allreduce(awc.walkers_per_rank);
454  awc.global_walkers = std::accumulate(awc.walkers_per_rank.begin(), awc.walkers_per_rank.end(), 0);
455  }
456 
457  if (awc.global_walkers % num_ranks)
458  app_warning() << "TotalWalkers (" << awc.global_walkers << ") not divisible by number of ranks (" << num_ranks
459  << "). This will result in a loss of efficiency.\n";
460 
461  // Step 3. decide awc.walkers_per_crowd
462  awc.walkers_per_crowd = fairDivide(awc.walkers_per_rank[rank_id], num_crowds);
463 
464  if (awc.walkers_per_rank[rank_id] % num_crowds)
465  app_warning() << "Walkers per rank (" << awc.walkers_per_rank[rank_id] << ") not divisible by number of crowds ("
466  << num_crowds << "). This will result in a loss of efficiency.\n";
467 
468  // \todo some warning if unreasonable number of threads are being used.
469 
470  return awc;
471 }
std::ostream & app_warning()
Definition: OutputManager.h:69
int rank() const
return the rank
Definition: Communicate.h:116
static void checkNumCrowdsLTNumThreads(const int num_crowds)
int size() const
return the number of tasks
Definition: Communicate.h:118
void allreduce(T &)
void error(char const *m)
Definition: Standard.h:204
std::vector< IV > fairDivide(IV ntot, IV npart)
return the occupation vector for ntot entities partitioned npart ways.
Definition: FairDivide.h:77

◆ checkLogAndGL()

void checkLogAndGL ( Crowd crowd,
const std::string_view  location 
)
staticprotected

check logpsi and grad and lap against values computed from scratch

Definition at line 548 of file QMCDriverNew.cpp.

References qmcplusplus::abs(), qmcplusplus::crowd, qmcplusplus::dot(), qmcplusplus::exp(), qmcplusplus::log_values(), and qmcplusplus::sqrt().

Referenced by VMCBatched::advanceWalkers(), and DMCBatched::advanceWalkers().

549 {
550  bool success = true;
551  auto& ps_dispatcher = crowd.dispatchers_.ps_dispatcher_;
552  auto& twf_dispatcher = crowd.dispatchers_.twf_dispatcher_;
553 
554  const RefVectorWithLeader<ParticleSet> walker_elecs(crowd.get_walker_elecs()[0], crowd.get_walker_elecs());
555  const RefVectorWithLeader<TrialWaveFunction> walker_twfs(crowd.get_walker_twfs()[0], crowd.get_walker_twfs());
556  std::vector<TrialWaveFunction::LogValue> log_values(walker_twfs.size());
557  std::vector<ParticleSet::ParticleGradient> Gs;
558  std::vector<ParticleSet::ParticleLaplacian> Ls;
559  Gs.reserve(log_values.size());
560  Ls.reserve(log_values.size());
561 
562  for (int iw = 0; iw < log_values.size(); iw++)
563  {
564  log_values[iw] = {walker_twfs[iw].getLogPsi(), walker_twfs[iw].getPhase()};
565  Gs.push_back(walker_twfs[iw].G);
566  Ls.push_back(walker_twfs[iw].L);
567  }
568 
569  ps_dispatcher.flex_update(walker_elecs);
570  twf_dispatcher.flex_evaluateLog(walker_twfs, walker_elecs);
571 
572  RealType threshold;
573  // mixed precision can't make this test with cuda direct inversion
574  if constexpr (std::is_same<RealType, FullPrecRealType>::value)
575  threshold = 100 * std::numeric_limits<float>::epsilon();
576  else
577  threshold = 500 * std::numeric_limits<float>::epsilon();
578 
579  std::ostringstream msg;
580  for (int iw = 0; iw < log_values.size(); iw++)
581  {
582  auto& ref_G = walker_twfs[iw].G;
583  auto& ref_L = walker_twfs[iw].L;
584  TrialWaveFunction::LogValue ref_log{walker_twfs[iw].getLogPsi(), walker_twfs[iw].getPhase()};
585  if (std::abs(std::exp(log_values[iw]) - std::exp(ref_log)) > std::abs(std::exp(ref_log)) * threshold)
586  {
587  success = false;
588  msg << "Logpsi walker[" << iw << "] " << log_values[iw] << " ref " << ref_log << std::endl;
589  }
590 
591  for (int iel = 0; iel < ref_G.size(); iel++)
592  {
593  auto grad_diff = ref_G[iel] - Gs[iw][iel];
594  if (std::sqrt(std::abs(dot(grad_diff, grad_diff))) > std::sqrt(std::abs(dot(ref_G[iel], ref_G[iel]))) * threshold)
595  {
596  success = false;
597  msg << "walker[" << iw << "] Grad[" << iel << "] ref = " << ref_G[iel] << " wrong = " << Gs[iw][iel]
598  << " Delta " << grad_diff << std::endl;
599  }
600 
601  auto lap_diff = ref_L[iel] - Ls[iw][iel];
602  if (std::abs(lap_diff) > std::abs(ref_L[iel]) * threshold)
603  {
604  // very hard to check mixed precision case, only print, no error out
605  if (std::is_same<RealType, FullPrecRealType>::value)
606  success = false;
607  msg << "walker[" << iw << "] lap[" << iel << "] ref = " << ref_L[iel] << " wrong = " << Ls[iw][iel] << " Delta "
608  << lap_diff << std::endl;
609  }
610  }
611  }
612 
613  std::cerr << msg.str();
614  if (!success)
615  throw std::runtime_error(std::string("checkLogAndGL failed at ") + std::string(location) + std::string("\n"));
616 }
MakeReturn< UnaryNode< FnFabs, typename CreateLeaf< Vector< T1, C1 > >::Leaf_t > >::Expression_t abs(const Vector< T1, C1 > &l)
std::vector< StdComp, CUDAHostAllocator< StdComp > > log_values(batch_size)
WaveFunctionComponent::LogValue LogValue
MakeReturn< UnaryNode< FnExp, typename CreateLeaf< Vector< T1, C1 > >::Leaf_t > >::Expression_t exp(const Vector< T1, C1 > &l)
MakeReturn< UnaryNode< FnSqrt, typename CreateLeaf< Vector< T1, C1 > >::Leaf_t > >::Expression_t sqrt(const Vector< T1, C1 > &l)
QMCTraits::RealType RealType
Tensor< typename BinaryReturn< T1, T2, OpMultiply >::Type_t, D > dot(const AntiSymTensor< T1, D > &lhs, const AntiSymTensor< T2, D > &rhs)

◆ checkNumCrowdsLTNumThreads()

void checkNumCrowdsLTNumThreads ( const int  num_crowds)
staticprotected

Definition at line 119 of file QMCDriverNew.cpp.

Referenced by QMCDriverNew::adjustGlobalWalkerCount().

120 {
121  int num_threads(Concurrency::maxCapacity<>());
122  if (num_crowds > num_threads)
123  {
124  std::stringstream error_msg;
125  error_msg << "Bad Input: num_crowds (" << num_crowds << ") > num_threads (" << num_threads << ")\n";
126  throw UniformCommunicateError(error_msg.str());
127  }
128 }

◆ computeLogGreensFunction()

static void computeLogGreensFunction ( const MCCoords< CT > &  coords,
const TauParams< RT, CT > &  taus,
std::vector< QMCTraits::RealType > &  log_gb 
)
inlinestatic

calculates Green Function from displacements stored in MCCoords [param, out] log_g

Definition at line 270 of file QMCDriverNew.h.

References qmcplusplus::dot(), and qmcplusplus::POS_SPIN.

Referenced by VMCBatched::advanceWalkers(), DMCBatched::advanceWalkers(), and qmcplusplus::TEST_CASE().

273  {
274  assert(coords.positions.size() == log_gb.size());
275  std::transform(coords.positions.begin(), coords.positions.end(), log_gb.begin(),
276  [halfovertau = taus.oneover2tau](const QMCTraits::PosType& pos) {
277  return -halfovertau * dot(pos, pos);
278  });
279  if constexpr (CT == CoordsType::POS_SPIN)
280  std::transform(coords.spins.begin(), coords.spins.end(), log_gb.begin(), log_gb.begin(),
281  [halfovertau = taus.spin_oneover2tau](const QMCTraits::FullPrecRealType& spin,
282  const QMCTraits::RealType& loggb) {
283  return loggb - halfovertau * spin * spin;
284  });
285  }
QTBase::RealType RealType
Definition: Configuration.h:58
QTBase::PosType PosType
Definition: Configuration.h:61
Tensor< typename BinaryReturn< T1, T2, OpMultiply >::Type_t, D > dot(const AntiSymTensor< T1, D > &lhs, const AntiSymTensor< T2, D > &rhs)
QTFull::RealType FullPrecRealType
Definition: Configuration.h:66

◆ createRngsStepContexts()

void createRngsStepContexts ( int  num_crowds)

Creates Random Number generators for crowds and step contexts.

This is quite dangerous in that number of crowds can be > omp_get_max_threads() This is used instead of actually passing number of threads/crowds controlling threads all over RandomNumberControl.

Definition at line 298 of file QMCDriverNew.cpp.

References qmcplusplus::app_warning(), RandomNumberControl::Children, RandomNumberControl::make_seeds(), QMCDriverNew::Rng, and QMCDriverNew::step_contexts_.

Referenced by QMCDriverNew::initializeQMC().

299 {
300  step_contexts_.resize(num_crowds);
301  Rng.resize(num_crowds);
302 
303  if (RandomNumberControl::Children.size() == 0)
304  {
305  app_warning() << " Initializing global RandomNumberControl! "
306  << "This message should not be seen in production code but only in unit tests." << std::endl;
308  }
309 
310  for (int i = 0; i < num_crowds; ++i)
311  {
312  Rng[i].reset(RandomNumberControl::Children[i].release());
313  step_contexts_[i] = std::make_unique<ContextForSteps>(*(Rng[i]));
314  }
315 }
std::ostream & app_warning()
Definition: OutputManager.h:69
UPtrVector< ContextForSteps > step_contexts_
Per crowd move contexts, this is where the DistanceTables etc.
Definition: QMCDriverNew.h:450
static UPtrVector< RandomBase< FullPrecRealType > > Children
UPtrVector< RandomBase< FullPrecRealType > > Rng
Random number generators.
Definition: QMCDriverNew.h:453
static void make_seeds()
reset the generator

◆ current()

IndexType current ( ) const
inline

return current step

Definition at line 181 of file QMCDriverNew.h.

References QMCDriverNew::current_step_.

181 { return current_step_; }

◆ determineStepsPerBlock()

size_t determineStepsPerBlock ( IndexType  global_walkers,
IndexType  requested_samples,
IndexType  requested_steps,
IndexType  blocks 
)
staticprotected

pure function calculating the actual number of steps per block

Parameters
global_walkersthe total number of walkers over all the MPI ranks
requested_samplesthe number of samples from user input "samples". <=0 treated as no input
requested_stepsthe number steps per block from user input "steps". <=0 treated as no input
blocksthe number of blocks. Must be positive.
Returns
calculated optimal number of steps per block

Definition at line 473 of file QMCDriverNew.cpp.

Referenced by VMCBatched::process(), DMCBatched::process(), and QMCDriverNewTestWrapper::testDetermineStepsPerBlock().

477 {
478  assert(global_walkers > 0 && "QMCDriverNew::determineStepsPerBlock global_walkers must be positive!");
479 
480  if (blocks <= 0)
481  throw UniformCommunicateError("QMCDriverNew::determineStepsPerBlock blocks must be positive!");
482 
483  if (requested_samples > 0 && requested_steps > 0)
484  {
485  if (requested_samples <= global_walkers * requested_steps * blocks)
486  return requested_steps;
487  else
488  throw UniformCommunicateError("The requested number of samples is more than the total number of walkers "
489  "multiplies the requested number of steps and blocks");
490  }
491  else if (requested_samples > 0)
492  {
493  IndexType one_step_minimal_samples = global_walkers * blocks;
494  return (requested_samples + one_step_minimal_samples - 1) / one_step_minimal_samples;
495  }
496  else if (requested_steps > 0)
497  return requested_steps;
498  else // neither requested_samples nor requested_steps is positive
499  return 1;
500 }
QMCTraits::IndexType IndexType
Definition: QMCDriverNew.h:79

◆ endBlock()

void endBlock ( )
protected

end of a block operations. Aggregates statistics across all MPI ranks and write to disk.

The scalar estimator collection is quite strange.

get the average cpu_block time per crowd cpu_block_time /= crowds_.size();

Definition at line 505 of file QMCDriverNew.cpp.

References qmcplusplus::app_warning(), qmcplusplus::crowd, QMCDriverNew::crowds_, QMCDriverNew::DriverTimers::endblock_timer, QMCDriverNew::estimator_manager_, and QMCDriverNew::timers_.

Referenced by VMCBatched::run(), and DMCBatched::run().

506 {
507  ScopedTimer local_timer(timers_.endblock_timer);
508  RefVector<ScalarEstimatorBase> main_scalar_estimators;
509 
510  FullPrecRealType total_block_weight = 0.0;
511  // Collect all the ScalarEstimatorsFrom EMCrowds
512  unsigned long block_accept = 0;
513  unsigned long block_reject = 0;
514 
515  std::vector<RefVector<OperatorEstBase>> crowd_operator_estimators;
516  // Seems uneeded see EstimatorManagerNew scalar_ests_ documentation.
517  std::vector<RefVector<ScalarEstimatorBase>> crowd_scalar_estimators;
518 
519  for (const UPtr<Crowd>& crowd : crowds_)
520  {
521  crowd->stopBlock();
522  main_scalar_estimators.push_back(crowd->get_estimator_manager_crowd().get_main_estimator());
523  crowd_scalar_estimators.emplace_back(crowd->get_estimator_manager_crowd().get_scalar_estimators());
524  total_block_weight += crowd->get_estimator_manager_crowd().get_block_weight();
525  block_accept += crowd->get_accept();
526  block_reject += crowd->get_reject();
527 
528  // This seems altogether easier and more sane.
529  crowd_operator_estimators.emplace_back(crowd->get_estimator_manager_crowd().get_operator_estimators());
530  }
531 
532 #ifdef DEBUG_PER_STEP_ACCEPT_REJECT
533  app_warning() << "accept: " << block_accept << " reject: " << block_reject;
534  FullPrecRealType total_accept_ratio =
535  static_cast<FullPrecRealType>(block_accept) / static_cast<FullPrecRealType>(block_accept + block_reject);
536  std::cerr << " total_accept_ratio: << " << total_accept_ratio << '\n';
537 #endif
538  estimator_manager_->collectMainEstimators(main_scalar_estimators);
539  estimator_manager_->collectScalarEstimators(crowd_scalar_estimators);
540  estimator_manager_->collectOperatorEstimators(crowd_operator_estimators);
541 
542  /// get the average cpu_block time per crowd
543  /// cpu_block_time /= crowds_.size();
544 
545  estimator_manager_->stopBlock(block_accept, block_reject, total_block_weight);
546 }
std::ostream & app_warning()
Definition: OutputManager.h:69
ScopeGuard< NewTimer > ScopedTimer
Definition: NewTimer.h:257
std::unique_ptr< EstimatorManagerNew > estimator_manager_
Observables manager Has very problematic owner ship and life cycle.
Definition: QMCDriverNew.h:443
QMCTraits::FullPrecRealType FullPrecRealType
Definition: QMCDriverNew.h:80
UPtrVector< Crowd > crowds_
}@
Definition: QMCDriverNew.h:389
DriverTimers timers_
period of dumping walker configurations and everything else for restart
Definition: QMCDriverNew.h:472

◆ finalize()

bool finalize ( int  block,
bool  dumpwalkers = true 
)

finalize a qmc section

Parameters
blockcurrent block
dumpwalkersif true, dump walkers

Accumulate energy and weight is written to a hdf5 file. Finialize the estimators

Definition at line 251 of file QMCDriverNew.cpp.

References qmcplusplus::app_log(), InfoStream::flush(), QMCDriverInput::get_dump_config(), QMCDriverNew::get_root_name(), WalkerConfigurations::getGlobalNumWalkers(), QMCDriverNew::getRngRefs(), infoLog, infoSummary, MPIObjectBase::myComm, QMCDriverNew::population_, QMCDriverNew::qmcdriver_input_, MCPopulation::saveWalkerConfigurations(), QMCDriverNew::setWalkerOffsets(), QMCDriverNew::walker_configs_ref_, QMCDriverNew::wOut, and RandomNumberControl::write().

Referenced by VMCBatched::run(), and DMCBatched::run().

252 {
255  app_log() << " Carry over " << walker_configs_ref_.getGlobalNumWalkers()
256  << " walker configurations to the next QMC driver." << std::endl;
257 
258  const bool DumpConfig = qmcdriver_input_.get_dump_config();
259  if (DumpConfig && dumpwalkers)
260  wOut->dump(walker_configs_ref_, block);
261 
262  infoSummary.flush();
263  infoLog.flush();
264 
265  if (DumpConfig)
267 
268  return true;
269 }
MCPopulation population_
the entire (on node) walker population it serves VMCBatch and DMCBatch right now but will be polymorp...
Definition: QMCDriverNew.h:426
InfoStream infoSummary
std::ostream & app_log()
Definition: OutputManager.h:65
static void write(const std::string &fname, Communicate *comm)
write in parallel or serial
size_t getGlobalNumWalkers() const
return the total number of active walkers among a MPI group
InfoStream infoLog
static void setWalkerOffsets(WalkerConfigurations &, Communicate *comm)
update the global offsets of walker configurations after active walkers being touched.
std::unique_ptr< HDFWalkerOutput > wOut
record engine for walkers
Definition: QMCDriverNew.h:446
const std::string & get_root_name() const override
Definition: QMCDriverNew.h:331
WalkerConfigurations & walker_configs_ref_
Definition: QMCDriverNew.h:481
Communicate * myComm
pointer to Communicate
Definition: MPIObjectBase.h:62
RefVector< RandomBase< FullPrecRealType > > getRngRefs() const
Definition: QMCDriverNew.h:201
void saveWalkerConfigurations(WalkerConfigurations &walker_configs)
save walker configurations to walker_configs_ref_
void flush()
flush stream buffer
Definition: InfoStream.cpp:39
QMCDriverInput qmcdriver_input_
Definition: QMCDriverNew.h:372

◆ get_drift_modifier()

DriftModifierBase& get_drift_modifier ( ) const
inline

Definition at line 162 of file QMCDriverNew.h.

References QMCDriverNew::drift_modifier_.

162 { return *drift_modifier_; }
std::unique_ptr< DriftModifierBase > drift_modifier_
drift modifer
Definition: QMCDriverNew.h:394

◆ get_num_dead_walkers()

IndexType get_num_dead_walkers ( ) const
inline

Definition at line 221 of file QMCDriverNew.h.

References MCPopulation::get_dead_walkers(), and QMCDriverNew::population_.

221 { return population_.get_dead_walkers().size(); }
MCPopulation population_
the entire (on node) walker population it serves VMCBatch and DMCBatch right now but will be polymorp...
Definition: QMCDriverNew.h:426
const UPtrVector< MCPWalker > & get_dead_walkers() const
Definition: MCPopulation.h:196

◆ get_num_living_walkers()

IndexType get_num_living_walkers ( ) const
inline

Definition at line 220 of file QMCDriverNew.h.

References MCPopulation::get_walkers(), and QMCDriverNew::population_.

Referenced by qmcplusplus::TEST_CASE().

220 { return population_.get_walkers().size(); }
MCPopulation population_
the entire (on node) walker population it serves VMCBatch and DMCBatch right now but will be polymorp...
Definition: QMCDriverNew.h:426
UPtrVector< MCPWalker > & get_walkers()
Definition: MCPopulation.h:194

◆ get_root_name()

const std::string& get_root_name ( ) const
inlineoverrideprotectedvirtual

◆ getDriverMode()

unsigned long getDriverMode ( )
inlineoverridevirtual

Implements QMCDriverInterface.

Definition at line 218 of file QMCDriverNew.h.

References QMCDriverNew::qmc_driver_mode_.

218 { return qmc_driver_mode_.to_ulong(); }
std::bitset< QMC_MODE_MAX > qmc_driver_mode_
bits to classify QMCDriver
Definition: QMCDriverNew.h:103

◆ getEngineName()

std::string getEngineName ( )
inlineoverridevirtual

intended for logging output and debugging you should base behavior on type preferably at compile time or if necessary at runtime using and protected by dynamic cast.

QMCType is primarily for use in the debugger.

Implements QMCDriverInterface.

Definition at line 217 of file QMCDriverNew.h.

References QMCDriverNew::QMCType.

217 { return QMCType; }
const std::string QMCType
type of qmc: assigned by subclasses
Definition: QMCDriverNew.h:421

◆ getQMCDriverInput()

const QMCDriverInput& getQMCDriverInput ( ) const
inline

Definition at line 223 of file QMCDriverNew.h.

References QMCDriverNew::qmcdriver_input_.

223 { return qmcdriver_input_; }
QMCDriverInput qmcdriver_input_
Definition: QMCDriverNew.h:372

◆ getRng()

RandomBase<FullPrecRealType>& getRng ( int  i)
inlineoverridevirtual

return the i-th random generator

Implements QMCDriverInterface.

Definition at line 210 of file QMCDriverNew.h.

References QMCDriverNew::Rng.

210 { return (*Rng[i]); }
UPtrVector< RandomBase< FullPrecRealType > > Rng
Random number generators.
Definition: QMCDriverNew.h:453

◆ getRngRefs()

RefVector<RandomBase<FullPrecRealType> > getRngRefs ( ) const
inline

Definition at line 201 of file QMCDriverNew.h.

References QMCDriverNew::Rng.

Referenced by QMCDriverNew::finalize(), and QMCDriverNew::recordBlock().

202  {
203  RefVector<RandomBase<FullPrecRealType>> RngRefs;
204  for (int i = 0; i < Rng.size(); ++i)
205  RngRefs.push_back(*Rng[i]);
206  return RngRefs;
207  }
UPtrVector< RandomBase< FullPrecRealType > > Rng
Random number generators.
Definition: QMCDriverNew.h:453

◆ initializeQMC()

void initializeQMC ( const AdjustedWalkerCounts awc)
protected

Do common section starting tasks for VMC and DMC.

set up population_, crowds_, rngs and step_contexts_

Definition at line 130 of file QMCDriverNew.cpp.

References app_debug, qmcplusplus::app_summary(), QMCDriverInput::areWalkersSerialized(), QMCHamiltonian::createResource(), TrialWaveFunction::createResource(), ParticleSet::createResource(), QMCDriverNew::createRngsStepContexts(), QMCDriverNew::crowds_, QMCDriverNew::dispatchers_, QMCDriverNew::estimator_manager_, MCPopulation::get_golden_electrons(), MCPopulation::get_golden_hamiltonian(), MCPopulation::get_golden_twf(), QMCDriverInput::get_max_blocks(), QMCDriverInput::get_measure_imbalance(), QMCDriverInput::get_requested_steps(), QMCDriverNew::AdjustedWalkerCounts::global_walkers, QMCDriverNew::golden_resource_, DriverWalkerResourceCollection::ham_res, QMCHamiltonian::informOperatorsOfListener(), QMCDriverNew::makeLocalWalkers(), QMCDriverNew::measureImbalance(), MPIObjectBase::myComm, QMCDriverNew::population_, DriverWalkerResourceCollection::pset_res, QMCDriverNew::qmcdriver_input_, QMCDriverNew::QMCType, Communicate::rank(), MCPopulation::redistributeWalkers(), QMCDriverNew::AdjustedWalkerCounts::reserve_walkers, MCPopulation::set_num_global_walkers(), QMCDriverNew::DriverTimers::startup_timer, QMCDriverNew::steps_per_block_, QMCDriverNew::timers_, DriverWalkerResourceCollection::twf_res, QMCDriverNew::AdjustedWalkerCounts::walkers_per_crowd, and QMCDriverNew::AdjustedWalkerCounts::walkers_per_rank.

Referenced by QMCDriverNewTestWrapper::process(), VMCBatched::process(), and DMCBatched::process().

131 {
132  ScopedTimer local_timer(timers_.startup_timer);
133 
134  app_summary() << QMCType << " Driver running with" << std::endl
135  << " total_walkers = " << awc.global_walkers << std::endl
136  << " walkers_per_rank = " << awc.walkers_per_rank << std::endl
137  << " num_crowds = " << awc.walkers_per_crowd.size() << std::endl
138  << " on rank 0, walkers_per_crowd = " << awc.walkers_per_crowd << std::endl
139  << std::endl
140  << " steps = " << steps_per_block_
142  ? ""
143  : " (different from input value " + std::to_string(qmcdriver_input_.get_requested_steps()) + ")")
144  << std::endl
145  << " blocks = " << qmcdriver_input_.get_max_blocks() << std::endl
146  << std::endl;
147 
148  // set num_global_walkers explicitly and then make local walkers.
149  population_.set_num_global_walkers(awc.global_walkers);
150 
152  {
153  if (estimator_manager_->areThereListeners())
154  throw UniformCommunicateError("Serialized walkers ignore multiwalker API's and multiwalker resources and are "
155  "incompatible with estimators requiring per particle listeners");
156  }
157  else
158  {
159  // This needs to happen before walkers are made. i.e. this allows hamiltonian operators to update state
160  // the based on the presence of per particle listeners. In the case immediately encountered the operator CoulombPBCAA will
161  // call its associated particle set and turnOnPerParticleSK.
162  // The design for "initialization" of walker elements is for the golden elements to go through all pre walking state changes
163  // and then for the golden elements to be cloned for each walker.
164  if (estimator_manager_->areThereListeners())
166 
167  app_debug() << "Creating multi walker shared resources" << std::endl;
171  app_debug() << "Multi walker shared resources creation completed" << std::endl;
172  }
173 
174  makeLocalWalkers(awc.walkers_per_rank[myComm->rank()], awc.reserve_walkers);
175 
176  crowds_.resize(awc.walkers_per_crowd.size());
177 
178  // at this point we can finally construct the Crowd objects.
179  for (int i = 0; i < crowds_.size(); ++i)
180  {
181  crowds_[i] =
184  }
185 
186  //now give walkers references to their walkers
188 
189  // Once they are created move contexts can be created.
191 
193  measureImbalance("Startup");
194 }
void informOperatorsOfListener()
Some Hamiltonian components need to be informed that they are in a per particle reporting situation s...
size_t steps_per_block_
actual number of steps per block
Definition: QMCDriverNew.h:407
const ParticleSet & get_golden_electrons() const
Definition: MCPopulation.h:176
MCPopulation population_
the entire (on node) walker population it serves VMCBatch and DMCBatch right now but will be polymorp...
Definition: QMCDriverNew.h:426
QMCHamiltonian & get_golden_hamiltonian()
Definition: MCPopulation.h:181
int rank() const
return the rank
Definition: Communicate.h:116
void createResource(ResourceCollection &collection) const
initialize a shared resource and hand it to a collection
IndexType get_requested_steps() const
#define app_debug
Definition: OutputManager.h:75
void makeLocalWalkers(int nwalkers, RealType reserve)
Adjust populations local walkers to this number.
std::ostream & app_summary()
Definition: OutputManager.h:63
void createResource(ResourceCollection &collection) const
initialize a shared resource and hand it to a collection
ScopeGuard< NewTimer > ScopedTimer
Definition: NewTimer.h:257
void createRngsStepContexts(int num_crowds)
Creates Random Number generators for crowds and step contexts.
std::unique_ptr< EstimatorManagerNew > estimator_manager_
Observables manager Has very problematic owner ship and life cycle.
Definition: QMCDriverNew.h:443
void createResource(ResourceCollection &collection) const
initialize a shared resource and hand it to a collection
const MultiWalkerDispatchers dispatchers_
multi walker dispatchers
Definition: QMCDriverNew.h:436
const std::string QMCType
type of qmc: assigned by subclasses
Definition: QMCDriverNew.h:421
Communicate * myComm
pointer to Communicate
Definition: MPIObjectBase.h:62
struct DriverWalkerResourceCollection golden_resource_
the golden multi walker shared resource serves ParticleSet TrialWaveFunction right now but actually s...
Definition: QMCDriverNew.h:433
void set_num_global_walkers(IndexType num_global_walkers)
Definition: MCPopulation.h:183
const TrialWaveFunction & get_golden_twf() const
Definition: MCPopulation.h:178
IndexType get_max_blocks() const
UPtrVector< Crowd > crowds_
}@
Definition: QMCDriverNew.h:389
QMCDriverInput qmcdriver_input_
Definition: QMCDriverNew.h:372
void measureImbalance(const std::string &tag) const
inject additional barrier and measure load imbalance.
DriverTimers timers_
period of dumping walker configurations and everything else for restart
Definition: QMCDriverNew.h:472
void redistributeWalkers(WTTV &walker_consumers)
distributes walkers and their "cloned" elements to the elements of a vector of unique_ptr to "walker_...
Definition: MCPopulation.h:131

◆ initialLogEvaluation()

void initialLogEvaluation ( int  crowd_id,
UPtrVector< Crowd > &  crowds,
UPtrVector< ContextForSteps > &  step_context 
)
static

Definition at line 317 of file QMCDriverNew.cpp.

References QMCHamiltonian::auxHevaluate(), qmcplusplus::crowd, qmcplusplus::ham, qmcplusplus::pset, QMCHamiltonian::saveProperty(), qmcplusplus::twf, qmcplusplus::walker, and qmcplusplus::hdf::walkers.

Referenced by VMCBatched::run(), and DMCBatched::run().

320 {
321  Crowd& crowd = *(crowds[crowd_id]);
322  if (crowd.size() == 0)
323  return;
324 
325  crowd.setRNGForHamiltonian(context_for_steps[crowd_id]->get_random_gen());
326  auto& ps_dispatcher = crowd.dispatchers_.ps_dispatcher_;
327  auto& twf_dispatcher = crowd.dispatchers_.twf_dispatcher_;
328  auto& ham_dispatcher = crowd.dispatchers_.ham_dispatcher_;
329 
330  const RefVectorWithLeader<ParticleSet> walker_elecs(crowd.get_walker_elecs()[0], crowd.get_walker_elecs());
331  const RefVectorWithLeader<TrialWaveFunction> walker_twfs(crowd.get_walker_twfs()[0], crowd.get_walker_twfs());
332  const RefVectorWithLeader<QMCHamiltonian> walker_hamiltonians(crowd.get_walker_hamiltonians()[0],
333  crowd.get_walker_hamiltonians());
334 
335  ResourceCollectionTeamLock<ParticleSet> pset_res_lock(crowd.getSharedResource().pset_res, walker_elecs);
336  ResourceCollectionTeamLock<TrialWaveFunction> twfs_res_lock(crowd.getSharedResource().twf_res, walker_twfs);
337  ResourceCollectionTeamLock<QMCHamiltonian> hams_res_lock(crowd.getSharedResource().ham_res, walker_hamiltonians);
338 
339  auto& walkers = crowd.get_walkers();
340  std::vector<bool> recompute_mask(walkers.size(), true);
341  ps_dispatcher.flex_loadWalker(walker_elecs, walkers, recompute_mask, true);
342  ps_dispatcher.flex_donePbyP(walker_elecs);
343  twf_dispatcher.flex_evaluateLog(walker_twfs, walker_elecs);
344 
345  // For consistency this should be in ParticleSet as a flex call, but I think its a problem
346  // in the algorithm logic and should be removed.
347  auto saveElecPosAndGLToWalkers = [](ParticleSet& pset, ParticleSet::Walker_t& walker) { pset.saveWalker(walker); };
348  for (int iw = 0; iw < crowd.size(); ++iw)
349  saveElecPosAndGLToWalkers(walker_elecs[iw], walkers[iw]);
350 
351  std::vector<QMCHamiltonian::FullPrecRealType> local_energies(
352  ham_dispatcher.flex_evaluate(walker_hamiltonians, walker_twfs, walker_elecs));
353 
354  // \todo rename these are sets not resets.
355  auto resetSigNLocalEnergy = [](MCPWalker& walker, TrialWaveFunction& twf, auto local_energy) {
356  walker.resetProperty(twf.getLogPsi(), twf.getPhase(), local_energy);
357  };
358  for (int iw = 0; iw < crowd.size(); ++iw)
359  resetSigNLocalEnergy(walkers[iw], walker_twfs[iw], local_energies[iw]);
360 
361  auto evaluateNonPhysicalHamiltonianElements = [](QMCHamiltonian& ham, ParticleSet& pset, MCPWalker& walker) {
363  };
364  for (int iw = 0; iw < crowd.size(); ++iw)
365  evaluateNonPhysicalHamiltonianElements(walker_hamiltonians[iw], walker_elecs[iw], walkers[iw]);
366 
367  auto savePropertiesIntoWalker = [](QMCHamiltonian& ham, MCPWalker& walker) {
368  ham.saveProperty(walker.getPropertyBase());
369  };
370  for (int iw = 0; iw < crowd.size(); ++iw)
371  savePropertiesIntoWalker(walker_hamiltonians[iw], walkers[iw]);
372 
373  auto doesDoinTheseLastMatter = [](MCPWalker& walker) {
374  walker.Weight = 1.;
375  walker.wasTouched = false;
376  };
377  for (int iw = 0; iw < crowd.size(); ++iw)
378  doesDoinTheseLastMatter(walkers[iw]);
379 }
Walker< QMCTraits, PtclOnLatticeTraits > Walker_t
walker type
Definition: ParticleSet.h:59
void saveProperty(IT first)
save the values of Hamiltonian elements to the Properties
MCPopulation::MCPWalker MCPWalker
Definition: QMCDriverNew.h:93
const char walkers[]
Definition: HDFVersion.h:36
void auxHevaluate(ParticleSet &P)

◆ makeLocalWalkers()

void makeLocalWalkers ( int  nwalkers,
RealType  reserve 
)

Adjust populations local walkers to this number.

Parameters
nwalkersnumber of walkers to add

Definition at line 271 of file QMCDriverNew.cpp.

References QMCDriverNew::DriverTimers::create_walkers_timer, MCPopulation::createWalkers(), MCPopulation::get_walkers(), MCPopulation::killLastWalker(), QMCDriverNew::population_, MCPopulation::spawnWalker(), QMCDriverNew::timers_, and QMCDriverNew::walker_configs_ref_.

Referenced by QMCDriverNew::initializeQMC().

272 {
274  // ensure nwalkers local walkers in population_
275  if (population_.get_walkers().size() == 0)
276  population_.createWalkers(nwalkers, walker_configs_ref_, reserve);
277  else if (population_.get_walkers().size() < nwalkers)
278  {
279  throw std::runtime_error("Unexpected walker count resulting in dangerous spawning");
280  IndexType num_additional_walkers = nwalkers - population_.get_walkers().size();
281  for (int i = 0; i < num_additional_walkers; ++i)
283  }
284  else
285  {
286  IndexType num_walkers_to_kill = population_.get_walkers().size() - nwalkers;
287  for (int i = 0; i < num_walkers_to_kill; ++i)
289  }
290 }
WalkerElementsRef spawnWalker()
State Requirement:
MCPopulation population_
the entire (on node) walker population it serves VMCBatch and DMCBatch right now but will be polymorp...
Definition: QMCDriverNew.h:426
UPtrVector< MCPWalker > & get_walkers()
Definition: MCPopulation.h:194
ScopeGuard< NewTimer > ScopedTimer
Definition: NewTimer.h:257
WalkerConfigurations & walker_configs_ref_
Definition: QMCDriverNew.h:481
QMCTraits::IndexType IndexType
Definition: QMCDriverNew.h:79
void createWalkers(IndexType num_walkers, const WalkerConfigurations &walker_configs, RealType reserve=1.0)
}@
DriverTimers timers_
period of dumping walker configurations and everything else for restart
Definition: QMCDriverNew.h:472
void killLastWalker()
Kill last walker (just barely)

◆ measureImbalance()

void measureImbalance ( const std::string &  tag) const
protected

inject additional barrier and measure load imbalance.

Definition at line 618 of file QMCDriverNew.cpp.

References qmcplusplus::app_log(), Communicate::barrier(), Timer::elapsed(), Communicate::gather(), QMCDriverNew::DriverTimers::imbalance_timer, MPIObjectBase::myComm, Communicate::rank(), Communicate::size(), and QMCDriverNew::timers_.

Referenced by QMCDriverNew::initializeQMC(), VMCBatched::run(), DMCBatched::run(), and QMCDriverNewTestWrapper::testMeasureImbalance().

619 {
620  ScopedTimer local_timer(timers_.imbalance_timer);
621  Timer only_this_barrier;
622  myComm->barrier();
623  std::vector<double> my_barrier_time(1, only_this_barrier.elapsed());
624  std::vector<double> barrier_time_all_ranks(myComm->size(), 0.0);
625  myComm->gather(my_barrier_time, barrier_time_all_ranks, 0);
626  if (!myComm->rank())
627  {
628  auto const count = static_cast<double>(barrier_time_all_ranks.size());
629  const auto max_it = std::max_element(barrier_time_all_ranks.begin(), barrier_time_all_ranks.end());
630  const auto min_it = std::min_element(barrier_time_all_ranks.begin(), barrier_time_all_ranks.end());
631  app_log() << std::endl
632  << tag << " MPI imbalance measured by an additional barrier (slow ranks wait less):" << std::endl
633  << " average wait seconds = "
634  << std::accumulate(barrier_time_all_ranks.begin(), barrier_time_all_ranks.end(), 0.0) / count << std::endl
635  << " min wait at rank " << std::distance(barrier_time_all_ranks.begin(), min_it)
636  << ", seconds = " << *min_it << std::endl
637  << " max wait at rank " << std::distance(barrier_time_all_ranks.begin(), max_it)
638  << ", seconds = " << *max_it << std::endl;
639  }
640 }
void barrier() const
int rank() const
return the rank
Definition: Communicate.h:116
std::ostream & app_log()
Definition: OutputManager.h:65
ScopeGuard< NewTimer > ScopedTimer
Definition: NewTimer.h:257
int size() const
return the number of tasks
Definition: Communicate.h:118
Communicate * myComm
pointer to Communicate
Definition: MPIObjectBase.h:62
void gather(T &sb, T &rb, int dest=0)
DriverTimers timers_
period of dumping walker configurations and everything else for restart
Definition: QMCDriverNew.h:472

◆ operator=()

QMCDriverNew& operator= ( const QMCDriverNew )
delete

Copy operator (disabled).

◆ process()

void process ( xmlNodePtr  cur)
overridepure virtual

QMCDriverNew driver second (3rd, 4th...) stage of constructing a valid driver.

This is the shared entry point with legacy, from QMCMain so the API cannot be updated yet

Todo:
remove cur, the driver and all its child nodes should be completely processed before this stage of driver initialization is hit.

Implements QMCDriverInterface.

Implemented in DMCBatched, VMCBatched, QMCFixedSampleLinearOptimizeBatched, and QMCDriverNewTestWrapper.

◆ put()

bool put ( xmlNodePtr  cur)
inlineoverridevirtual


Implements QMCDriverInterface.

Definition at line 228 of file QMCDriverNew.h.

228 { return false; };

◆ putQMCInfo()

bool putQMCInfo ( xmlNodePtr  cur)

◆ putTraces()

void putTraces ( xmlNodePtr  txml)
inlineoverridevirtual

Implements QMCDriverInterface.

Definition at line 248 of file QMCDriverNew.h.

248 {}

◆ putWalkerLogs()

void putWalkerLogs ( xmlNodePtr  wlxml)
overridevirtual

Implements QMCDriverInterface.

Definition at line 382 of file QMCDriverNew.cpp.

References WalkerLogInput::present, InputSection::readXML(), and QMCDriverNew::walker_logs_input.

383 {
384  walker_logs_input.present = false;
385  if(wlxml)
386  {
387  walker_logs_input.readXML(wlxml);
388  walker_logs_input.present = true;
389  }
390 }
WalkerLogInput walker_logs_input
walker logs input
Definition: QMCDriverNew.h:108
void readXML(xmlNodePtr cur)
Read variable values (initialize) from XML input, call checkValid.

◆ putWalkers()

void putWalkers ( std::vector< xmlNodePtr > &  wset)
overridevirtual

Read walker configurations from *.config.h5 files.

Parameters
wsetlist of xml elements containing mcwalkerset

All this does is look in the walker xml section for the hdf file. It reads that (I think) and if there are active walkers declares it a restart run.

This inferred behavior is asking for trouble. Unified driver will not support until restart feature is re-architected

Implements QMCDriverInterface.

Definition at line 221 of file QMCDriverNew.cpp.

References Communicate::bcast(), MCPopulation::get_golden_electrons(), WalkerConfigurations::getActiveWalkers(), ParticleSet::getTotalNum(), QMCDriverNew::h5_file_root_, MPIObjectBase::myComm, QMCDriverNew::population_, QMCDriverNew::setWalkerOffsets(), and QMCDriverNew::walker_configs_ref_.

222 {
223  if (wset.empty())
224  return;
225  const int nfile = wset.size();
226 
227  HDFWalkerInputManager W_in(walker_configs_ref_, population_.get_golden_electrons().getTotalNum(), myComm);
228  for (int i = 0; i < wset.size(); i++)
229  if (W_in.put(wset[i]))
230  h5_file_root_ = W_in.getFileRoot();
231  //clear the walker set
232  wset.clear();
234  myComm->bcast(nwtot);
235  if (nwtot)
237 }
const ParticleSet & get_golden_electrons() const
Definition: MCPopulation.h:176
MCPopulation population_
the entire (on node) walker population it serves VMCBatch and DMCBatch right now but will be polymorp...
Definition: QMCDriverNew.h:426
size_t getActiveWalkers() const
return the number of active walkers
size_t getTotalNum() const
Definition: ParticleSet.h:493
static void setWalkerOffsets(WalkerConfigurations &, Communicate *comm)
update the global offsets of walker configurations after active walkers being touched.
WalkerConfigurations & walker_configs_ref_
Definition: QMCDriverNew.h:481
Communicate * myComm
pointer to Communicate
Definition: MPIObjectBase.h:62
void bcast(T &)

◆ recordBlock()

void recordBlock ( int  block)
overridevirtual

record the state of the block

Parameters
blockcurrent block

virtual function with a default implementation

Implements QMCDriverInterface.

Definition at line 239 of file QMCDriverNew.cpp.

References QMCDriverNew::DriverTimers::checkpoint_timer, QMCDriverInput::get_check_point_period(), QMCDriverInput::get_dump_config(), QMCDriverNew::get_root_name(), QMCDriverNew::getRngRefs(), MPIObjectBase::myComm, QMCDriverNew::population_, QMCDriverNew::qmcdriver_input_, MCPopulation::saveWalkerConfigurations(), QMCDriverNew::setWalkerOffsets(), QMCDriverNew::timers_, QMCDriverNew::walker_configs_ref_, QMCDriverNew::wOut, and RandomNumberControl::write().

Referenced by VMCBatched::run(), and DMCBatched::run().

240 {
242  {
243  ScopedTimer local_timer(timers_.checkpoint_timer);
246  wOut->dump(walker_configs_ref_, block);
248  }
249 }
MCPopulation population_
the entire (on node) walker population it serves VMCBatch and DMCBatch right now but will be polymorp...
Definition: QMCDriverNew.h:426
ScopeGuard< NewTimer > ScopedTimer
Definition: NewTimer.h:257
static void write(const std::string &fname, Communicate *comm)
write in parallel or serial
static void setWalkerOffsets(WalkerConfigurations &, Communicate *comm)
update the global offsets of walker configurations after active walkers being touched.
std::unique_ptr< HDFWalkerOutput > wOut
record engine for walkers
Definition: QMCDriverNew.h:446
const std::string & get_root_name() const override
Definition: QMCDriverNew.h:331
WalkerConfigurations & walker_configs_ref_
Definition: QMCDriverNew.h:481
Communicate * myComm
pointer to Communicate
Definition: MPIObjectBase.h:62
RefVector< RandomBase< FullPrecRealType > > getRngRefs() const
Definition: QMCDriverNew.h:201
void saveWalkerConfigurations(WalkerConfigurations &walker_configs)
save walker configurations to walker_configs_ref_
input::PeriodStride get_check_point_period() const
QMCDriverInput qmcdriver_input_
Definition: QMCDriverNew.h:372
DriverTimers timers_
period of dumping walker configurations and everything else for restart
Definition: QMCDriverNew.h:472

◆ requestTraces()

void requestTraces ( bool  allow_traces)
inlineoverridevirtual

Implements QMCDriverInterface.

Definition at line 249 of file QMCDriverNew.h.

249 {}

◆ requestWalkerLogs()

void requestWalkerLogs ( bool  allow_walker_logs_)
inlineoverridevirtual

Implements QMCDriverInterface.

Definition at line 253 of file QMCDriverNew.h.

References QMCDriverNew::allow_walker_logs.

253 { allow_walker_logs = allow_walker_logs_; }
bool allow_walker_logs
whether to allow walker logs
Definition: QMCDriverNew.h:106

◆ scaleBySqrtTau()

static void scaleBySqrtTau ( const TauParams< RT, CT > &  taus,
MCCoords< CT > &  coords 
)
inlinestatic

Definition at line 257 of file QMCDriverNew.h.

References qmcplusplus::POS_SPIN.

Referenced by VMCBatched::advanceWalkers(), DMCBatched::advanceWalkers(), and qmcplusplus::TEST_CASE().

258  {
259  for (auto& pos : coords.positions)
260  pos *= taus.sqrttau;
261  if constexpr (CT == CoordsType::POS_SPIN)
262  for (auto& spin : coords.spins)
263  spin *= taus.spin_sqrttau;
264  }

◆ setStatus()

void setStatus ( const std::string &  aname,
const std::string &  h5name,
bool  append 
)
overridevirtual

Set the status of the QMCDriver.

QMCDriverNew ignores h5name if you want to read and h5 config you have to explicitly do so.

Parameters
anamethe root file name, ignored
h5nameroot name of the master hdf5 file containing previous qmcrun
appendif true, the run is a continuation of the previous qmc

All output files will be of the form "aname.s00X.suffix", where "X" is number of previous QMC runs for the simulation and "suffix" is the suffix for the output file.

Implements QMCDriverInterface.

Definition at line 199 of file QMCDriverNew.cpp.

References qmcplusplus::app_log(), QMCDriverNew::get_root_name(), QMCDriverNew::h5_file_root_, and QMCDriverNew::QMCType.

Referenced by qmcplusplus::TEST_CASE().

200 {
201  app_log() << "\n=========================================================" << "\n Start " << QMCType
202  << "\n File Root " << get_root_name();
203  app_log() << "\n=========================================================" << std::endl;
204 
205  if (h5name.size())
206  h5_file_root_ = h5name;
207 }
std::ostream & app_log()
Definition: OutputManager.h:65
const std::string & get_root_name() const override
Definition: QMCDriverNew.h:331
const std::string QMCType
type of qmc: assigned by subclasses
Definition: QMCDriverNew.h:421

◆ setUpdateMode()

void setUpdateMode ( bool  pbyp)
inlineoverridevirtual

should be set in input don't see a reason to set individually

Parameters
pbypif true, use particle-by-particle update

Implements QMCDriverInterface.

Definition at line 246 of file QMCDriverNew.h.

References QMCDriverNew::qmc_driver_mode_, and QMCDriverNew::QMC_UPDATE_MODE.

std::bitset< QMC_MODE_MAX > qmc_driver_mode_
bits to classify QMCDriver
Definition: QMCDriverNew.h:103

◆ setWalkerOffsets()

void setWalkerOffsets ( WalkerConfigurations walker_configs,
Communicate comm 
)
staticprotected

update the global offsets of walker configurations after active walkers being touched.

Definition at line 642 of file QMCDriverNew.cpp.

References Communicate::allreduce(), qmcplusplus::comm, WalkerConfigurations::getActiveWalkers(), Communicate::rank(), WalkerConfigurations::setWalkerOffsets(), and Communicate::size().

Referenced by QMCDriverNew::finalize(), QMCDriverNew::putWalkers(), and QMCDriverNew::recordBlock().

643 {
644  std::vector<int> nw(comm->size(), 0);
645  std::vector<int> nwoff(comm->size() + 1, 0);
646  nw[comm->rank()] = walker_configs.getActiveWalkers();
647  comm->allreduce(nw);
648  for (int ip = 0; ip < comm->size(); ip++)
649  nwoff[ip + 1] = nwoff[ip] + nw[ip];
650 
651  walker_configs.setWalkerOffsets(nwoff);
652 }
int rank() const
return the rank
Definition: Communicate.h:116
int size() const
return the number of tasks
Definition: Communicate.h:118
void allreduce(T &)

Friends And Related Function Documentation

◆ operator<<

std::ostream& operator<< ( std::ostream &  o_stream,
const QMCDriverNew qmcd 
)
friend

Definition at line 393 of file QMCDriverNew.cpp.

394 {
395  o_stream << " time step = " << qmcd.qmcdriver_input_.get_tau() << '\n';
396  o_stream << " blocks = " << qmcd.qmcdriver_input_.get_max_blocks() << '\n';
397  o_stream << " steps = " << qmcd.steps_per_block_ << '\n';
398  o_stream << " substeps = " << qmcd.qmcdriver_input_.get_sub_steps() << '\n';
399  o_stream << " current = " << qmcd.current_step_ << '\n';
400  o_stream << " target samples = " << qmcd.target_samples_ << '\n';
401  o_stream << " walkers/mpi = " << qmcd.population_.get_num_local_walkers() << std::endl;
402  app_log().flush();
403 
404  return o_stream;
405 }
std::ostream & app_log()
Definition: OutputManager.h:65

◆ qmcplusplus::testing::DMCBatchedTest

Definition at line 490 of file QMCDriverNew.h.

◆ qmcplusplus::testing::QMCDriverNewTestWrapper

Definition at line 491 of file QMCDriverNew.h.

◆ qmcplusplus::testing::VMCBatchedTest

Definition at line 489 of file QMCDriverNew.h.

Member Data Documentation

◆ allow_walker_logs

bool allow_walker_logs

whether to allow walker logs

Definition at line 106 of file QMCDriverNew.h.

Referenced by QMCDriverNew::requestWalkerLogs(), VMCBatched::run(), and DMCBatched::run().

◆ crowds_

◆ current_step_

IndexType current_step_
protected

Definition at line 405 of file QMCDriverNew.h.

Referenced by QMCDriverNew::current(), and qmcplusplus::operator<<().

◆ dispatchers_

const MultiWalkerDispatchers dispatchers_
protected

multi walker dispatchers

Definition at line 436 of file QMCDriverNew.h.

Referenced by QMCDriverNew::initializeQMC().

◆ drift_modifier_

std::unique_ptr<DriftModifierBase> drift_modifier_
protected

◆ driver_scope_profiler_

ScopedProfiler driver_scope_profiler_
protected

profile the driver lifetime

Definition at line 475 of file QMCDriverNew.h.

◆ estimator_manager_

std::unique_ptr<EstimatorManagerNew> estimator_manager_
protected

Observables manager Has very problematic owner ship and life cycle.

Can be transferred via branch manager one driver to the next indefinitely TODO: Modify Branch manager and others to clear this up.

Definition at line 443 of file QMCDriverNew.h.

Referenced by QMCDriverNew::endBlock(), QMCDriverNew::initializeQMC(), QMCDriverNew::QMCDriverNew(), VMCBatched::run(), and DMCBatched::run().

◆ golden_resource_

struct DriverWalkerResourceCollection golden_resource_
protected

the golden multi walker shared resource serves ParticleSet TrialWaveFunction right now but actually should be based on MCPopulation.

per crowd resources are copied from this gold instance it should be activated when dispatchers don't serialize walkers

Definition at line 433 of file QMCDriverNew.h.

Referenced by QMCDriverNew::initializeQMC().

◆ h5_file_root_

◆ k_delay

int k_delay
protected

the number to delay updates by

Definition at line 397 of file QMCDriverNew.h.

◆ m_oneover2tau

RealType m_oneover2tau
protected

Time-step factor $ 1/(2\tau)$.

Definition at line 416 of file QMCDriverNew.h.

◆ m_sqrttau

RealType m_sqrttau
protected

Time-step factor $ \sqrt{\tau}$.

Definition at line 418 of file QMCDriverNew.h.

◆ max_disp_sq_

RealType max_disp_sq_
protected


they should be limited to values that can be changed from input or are live state.

Definition at line 380 of file QMCDriverNew.h.

Referenced by QMCDriverNew::QMCDriverNew().

◆ mcwalkerNodePtr

std::vector<xmlNodePtr> mcwalkerNodePtr
protected

a list of mcwalkerset element

Definition at line 456 of file QMCDriverNew.h.

Referenced by QMCFixedSampleLinearOptimizeBatched::processOptXML().

◆ nAccept

IndexType nAccept
protected

counter for number of moves accepted

Definition at line 410 of file QMCDriverNew.h.

◆ nBlocksBetweenRecompute

IndexType nBlocksBetweenRecompute
protected

the number of blocks between recomptePsi

Definition at line 385 of file QMCDriverNew.h.

◆ nReject

IndexType nReject
protected

counter for number of moves /rejected

Definition at line 413 of file QMCDriverNew.h.

◆ population_

◆ project_data_

const ProjectData& project_data_
protected

project info for accessing global fileroot and series id

Definition at line 478 of file QMCDriverNew.h.

Referenced by QMCDriverNew::get_root_name(), QMCFixedSampleLinearOptimizeBatched::processOptXML(), VMCBatched::run(), and DMCBatched::run().

◆ qmc_driver_mode_

std::bitset<QMC_MODE_MAX> qmc_driver_mode_

bits to classify QMCDriver

  • qmc_driver_mode[QMC_UPDATE_MODE]? particle-by-particle: walker-by-walker
  • qmc_driver_mode[QMC_MULTIPLE]? multiple H/Psi : single H/Psi
  • qmc_driver_mode[QMC_OPTIMIZE]? optimization : vmc/dmc/rmc

Definition at line 103 of file QMCDriverNew.h.

Referenced by QMCDriverNew::getDriverMode(), QMCFixedSampleLinearOptimizeBatched::QMCFixedSampleLinearOptimizeBatched(), VMCBatched::run(), DMCBatched::run(), and QMCDriverNew::setUpdateMode().

◆ qmcdriver_input_

◆ QMCType

const std::string QMCType
protected

type of qmc: assigned by subclasses

Definition at line 421 of file QMCDriverNew.h.

Referenced by QMCDriverNew::getEngineName(), QMCDriverNew::initializeQMC(), and QMCDriverNew::setStatus().

◆ Rng

◆ step_contexts_

UPtrVector<ContextForSteps> step_contexts_
protected

Per crowd move contexts, this is where the DistanceTables etc.

reside

Definition at line 450 of file QMCDriverNew.h.

Referenced by QMCDriverNew::createRngsStepContexts(), VMCBatched::run(), and DMCBatched::run().

◆ steps_per_block_

size_t steps_per_block_ = 0
protected

◆ target_samples_

IndexType target_samples_
protected

the number of saved samples

Definition at line 382 of file QMCDriverNew.h.

Referenced by qmcplusplus::operator<<().

◆ timers_

DriverTimers timers_
protected

period of dumping walker configurations and everything else for restart

The unit is a block.}@

Definition at line 472 of file QMCDriverNew.h.

Referenced by QMCDriverNew::endBlock(), QMCDriverNew::initializeQMC(), QMCDriverNew::makeLocalWalkers(), QMCDriverNew::measureImbalance(), QMCDriverNew::recordBlock(), VMCBatched::run(), and DMCBatched::run().

◆ walker_configs_ref_

◆ walker_dump_period

int walker_dump_period
protected

period of recording walker configurations

Default is 0 indicating that only the last configuration will be saved.

Definition at line 403 of file QMCDriverNew.h.

◆ walker_logs_input

WalkerLogInput walker_logs_input

walker logs input

Definition at line 108 of file QMCDriverNew.h.

Referenced by QMCDriverNew::putWalkerLogs(), VMCBatched::run(), and DMCBatched::run().

◆ wOut

std::unique_ptr<HDFWalkerOutput> wOut
protected

record engine for walkers

Definition at line 446 of file QMCDriverNew.h.

Referenced by QMCDriverNew::finalize(), QMCDriverNew::QMCDriverNew(), and QMCDriverNew::recordBlock().

◆ qmcplusplus::RMC

class qmcplusplus::RMC


Implements a RMC using threaded execution.

Definition at line 25 of file RMC.h.

+ Inheritance diagram for RMC:
+ Collaboration diagram for RMC:

Public Types

using ParticlePos = ParticleSet::ParticlePos
 Constructor. More...
 
using ReptileConfig_t = Reptile::ReptileConfig_t
 
- Public Types inherited from QMCDriver
enum  { QMC_UPDATE_MODE, QMC_MULTIPLE, QMC_OPTIMIZE, QMC_WARMUP }
 enumeration coupled with QMCMode More...
 
using Walker_t = MCWalkerConfiguration::Walker_t
 
using Buffer_t = Walker_t::Buffer_t
 
using FullPrecRealType = QMCTraits::FullPrecRealType
 
- Public Types inherited from QMCDriverInterface
using BranchEngineType = SimpleFixedNodeBranch
 
using FullPrecRealType = QMCTraits::FullPrecRealType
 
- Public Types inherited from QMCTraits
enum  { DIM = OHMMS_DIM, DIM_VGL = OHMMS_DIM + 2 }
 
using QTBase = QMCTypes< OHMMS_PRECISION, DIM >
 
using QTFull = QMCTypes< OHMMS_PRECISION_FULL, DIM >
 
using RealType = QTBase::RealType
 
using ComplexType = QTBase::ComplexType
 
using ValueType = QTBase::ValueType
 
using PosType = QTBase::PosType
 
using GradType = QTBase::GradType
 
using TensorType = QTBase::TensorType
 
using IndexType = OHMMS_INDEXTYPE
 define other types More...
 
using FullPrecRealType = QTFull::RealType
 
using FullPrecValueType = QTFull::ValueType
 
using PropertySetType = RecordNamedProperty< FullPrecRealType >
 define PropertyList_t More...
 
using PtclGrpIndexes = std::vector< std::pair< int, int > >
 
- Public Types inherited from MPIObjectBase
using mpi_comm_type = Communicate::mpi_comm_type
 

Public Member Functions

 RMC (const ProjectData &project_data, MCWalkerConfiguration &w, TrialWaveFunction &psi, QMCHamiltonian &h, Communicate *comm)
 Constructor. More...
 
bool run () override
 
bool put (xmlNodePtr cur) override
 
QMCRunType getRunType () override
 
- Public Member Functions inherited from QMCDriver
 QMCDriver (const ProjectData &project_data, MCWalkerConfiguration &w, TrialWaveFunction &psi, QMCHamiltonian &h, Communicate *comm, const std::string &QMC_driver_type, bool enable_profiling=false)
 Constructor. More...
 
 ~QMCDriver () override
 
int current () const
 return current step More...
 
void setUpdateMode (bool pbyp) override
 set the update mode More...
 
void setStatus (const std::string &aname, const std::string &h5name, bool append) override
 Set the status of the QMCDriver. More...
 
void add_H_and_Psi (QMCHamiltonian *h, TrialWaveFunction *psi) override
 add QMCHamiltonian/TrialWaveFunction pair for multiple More...
 
void process (xmlNodePtr cur) override
 initialize with xmlNode More...
 
xmlNodePtr getQMCNode ()
 return a xmlnode with update More...
 
void putWalkers (std::vector< xmlNodePtr > &wset) override
 Read walker configurations from *.config.h5 files. More...
 
void putTraces (xmlNodePtr txml) override
 
void requestTraces (bool traces) override
 
void putWalkerLogs (xmlNodePtr wlxml) override
 
void requestWalkerLogs (bool allow_walker_logs_) override
 
std::string getEngineName () override
 
template<class PDT >
void setValue (const std::string &aname, PDT x)
 
void setBranchEngine (std::unique_ptr< BranchEngineType > &&be) override
 set the BranchEngineType More...
 
std::unique_ptr< BranchEngineTypegetBranchEngine () override
 return BranchEngineType* More...
 
int addObservable (const std::string &aname)
 
RealType getObservable (int i)
 
void setTau (RealType i)
 
void setWalkerOffsets ()
 set global offsets of the walkers More...
 
RefVector< RandomBase< FullPrecRealType > > getRngRefs () const
 return the random generators More...
 
RandomBase< FullPrecRealType > & getRng (int i) override
 return the i-th random generator More...
 
unsigned long getDriverMode () override
 
- Public Member Functions inherited from QMCDriverInterface
virtual ~QMCDriverInterface ()
 
virtual void setBranchEngine (std::unique_ptr< BranchEngineType > &&be)
 
- Public Member Functions inherited from MPIObjectBase
 MPIObjectBase (Communicate *c)
 constructor with communicator More...
 
int rank () const
 return the rank of the communicator More...
 
int getGroupID () const
 return the group id of the communicator More...
 
CommunicategetCommunicator () const
 return myComm More...
 
CommunicategetCommRef () const
 return a TEMPORARY reference to Communicate More...
 
mpi_comm_type getMPI () const
 return MPI communicator if one wants to use MPI directly More...
 
bool is_manager () const
 return true if the rank == 0 More...
 
const std::string & getName () const
 return the name More...
 
void setName (const std::string &aname)
 
- Public Member Functions inherited from CloneManager
 CloneManager ()
 Constructor. More...
 
virtual ~CloneManager ()
 virtual destructor More...
 
void makeClones (MCWalkerConfiguration &w, TrialWaveFunction &psi, QMCHamiltonian &ham)
 
void makeClones (MCWalkerConfiguration &w, std::vector< TrialWaveFunction *> &psi, std::vector< QMCHamiltonian *> &ham)
 
void makeClones (MCWalkerConfiguration &wg, TrialWaveFunction &guide)
 
void makeClones (TrialWaveFunction &guide)
 
RealType acceptRatio () const
 

Private Member Functions

void resetVars ()
 check the run-time environments More...
 
void resetRun ()
 
void resetReptiles (int nReptiles, int nbeads, RealType tau)
 
void resetReptiles (std::vector< ReptileConfig_t > &reptile_samps, RealType tau)
 
void resetReptiles (std::vector< ParticlePos > &walker_samps, int nbeads, RealType tau)
 
 RMC (const RMC &)=delete
 copy constructor (disabled) More...
 
RMCoperator= (const RMC &)=delete
 Copy operator (disabled). More...
 

Private Attributes

int prestepsVMC
 
std::string rescaleDrift
 option to enable/disable drift equation for RMC More...
 
RealType beta
 projection time of reptile More...
 
int myPeriod4WalkerDump
 period for walker dump More...
 
int beads
 number of beads on the reptile, beta/tau More...
 
int nReptiles
 
int resizeReptile
 rescale for time step studies. some int>2 and new beads are inserted in between the old ones. More...
 
bool fromScratch
 
std::vector< int > Action
 
std::vector< int > TransProb
 

Additional Inherited Members

- Static Public Member Functions inherited from CloneManager
static void clearClones ()
 
- Public Attributes inherited from QMCDriver
std::bitset< QMC_MODE_MAXqmc_driver_mode
 bits to classify QMCDriver More...
 
bool allow_traces
 whether to allow traces More...
 
xmlNodePtr traces_xml
 traces xml More...
 
bool allow_walker_logs
 whether to allow traces More...
 
xmlNodePtr walker_logs_xml
 traces xml More...
 
EstimatorManagerBaseEstimators
 Observables manager. More...
 
std::unique_ptr< TraceManagerTraces
 Traces manager. More...
 
std::unique_ptr< WalkerLogManagerwlog_manager_
 Traces manager. More...
 
- Protected Member Functions inherited from QMCDriver
bool putQMCInfo (xmlNodePtr cur)
 Parses the xml input file for parameter definitions for a single qmc simulation. More...
 
void addWalkers (int nwalkers)
 Add walkers to the end of the ensemble of walkers. More...
 
void recordBlock (int block) override
 record the state of the block More...
 
bool finalize (int block, bool dumpwalkers=true)
 finalize a qmc section More...
 
std::string getRotationName (std::string RootName)
 
std::string getLastRotationName (std::string RootName)
 
const std::string & get_root_name () const override
 
- Protected Member Functions inherited from CloneManager
RefVector< WalkerLogCollectorgetWalkerLogCollectorRefs ()
 
- Protected Attributes inherited from QMCDriver
const ProjectDataproject_data_
 top-level project data information More...
 
std::unique_ptr< BranchEngineTypebranchEngine
 branch engine More...
 
DriftModifierBaseDriftModifier
 drift modifer More...
 
bool ResetRandom
 randomize it More...
 
bool AppendRun
 flag to append or restart the run More...
 
bool DumpConfig
 flag to turn off dumping configurations More...
 
bool IsQMCDriver
 true, if it is a real QMC engine More...
 
int MyCounter
 the number of times this QMCDriver is executed More...
 
int kDelay
 the number to delay updates by More...
 
int Period4CheckPoint
 period of dumping walker configurations and everything else for restart More...
 
int Period4CheckProperties
 period of dumping walker positions and IDs for Forward Walking More...
 
int Period4WalkerDump
 period of recording walker configurations More...
 
int Period4ConfigDump
 period of recording walker positions and IDs for forward walking afterwards More...
 
IndexType CurrentStep
 current step More...
 
IndexType nBlocks
 maximum number of blocks More...
 
IndexType nSteps
 maximum number of steps More...
 
IndexType nSubSteps
 number of steps between a step: VMCs do not evaluate energies More...
 
IndexType nWarmupSteps
 number of warmup steps More...
 
IndexType nAccept
 counter for number of moves accepted More...
 
IndexType nReject
 counter for number of moves /rejected More...
 
IndexType nBlocksBetweenRecompute
 the number of blocks between recomptePsi More...
 
IndexType nTargetWalkers
 the number of walkers More...
 
IndexType nTargetSamples
 the number of saved samples More...
 
IndexType nStepsBetweenSamples
 alternate method of setting QMC run parameters More...
 
RealType nSamplesPerThread
 samples per thread More...
 
RealType nTargetPopulation
 target population More...
 
RealType Tau
 timestep More...
 
int MaxCPUSecs
 maximum cpu in secs More...
 
RealType m_oneover2tau
 Time-step factor $ 1/(2\tau)$. More...
 
RealType m_sqrttau
 Time-step factor $ \sqrt{\tau}$. More...
 
xmlNodePtr qmcNode
 pointer to qmc node in xml file More...
 
const std::string QMCType
 type of QMC driver More...
 
std::string h5FileRoot
 the root of h5File More...
 
std::string RootName
 root of all the output files More...
 
ParameterSet m_param
 store any parameter that has to be read from a file More...
 
MCWalkerConfigurationW
 walker ensemble More...
 
TrialWaveFunctionPsi
 trial function More...
 
QMCHamiltonianH
 Hamiltonian. More...
 
std::unique_ptr< HDFWalkerOutputwOut
 record engine for walkers More...
 
std::vector< TrialWaveFunction * > Psi1
 a list of TrialWaveFunctions for multiple method More...
 
std::vector< QMCHamiltonian * > H1
 a list of QMCHamiltonians for multiple method More...
 
UPtrVector< RandomBase< FullPrecRealType > > Rng
 Random number generators. More...
 
std::vector< xmlNodePtr > mcwalkerNodePtr
 a list of mcwalkerset element More...
 
ParticleSet::ParticlePos drift
 temporary storage for drift More...
 
ParticleSet::ParticlePos deltaR
 temporary storage for random displacement More...
 
RealType SpinMass
 spin mass for spinor calcs More...
 
int rotation
 
- Protected Attributes inherited from MPIObjectBase
CommunicatemyComm
 pointer to Communicate More...
 
std::string ClassName
 class Name More...
 
std::string myName
 name of the object More...
 
- Protected Attributes inherited from CloneManager
const IndexType NumThreads
 number of threads More...
 
std::vector< QMCUpdateBase * > Movers
 update engines More...
 
std::vector< EstimatorManagerBase * > estimatorClones
 estimator managers More...
 
std::vector< TraceManager * > traceClones
 trace managers More...
 
UPtrVector< WalkerLogCollectorwlog_collectors
 trace collectors More...
 
UPtrVector< CSUpdateBaseCSMovers
 
std::vector< int > wPerRank
 Walkers per MPI rank. More...
 
- Static Protected Attributes inherited from CloneManager
static UPtrVector< MCWalkerConfigurationwClones_uptr
 walkers More...
 
static std::vector< MCWalkerConfiguration * > wClones
 
static UPtrVector< MCWalkerConfigurationwgClones
 
static UPtrVector< TrialWaveFunctionpsiClones_uptr
 trial wavefunctions More...
 
static std::vector< TrialWaveFunction * > psiClones
 
static UPtrVector< TrialWaveFunctionguideClones_uptr
 guide wavefunctions More...
 
static std::vector< TrialWaveFunction * > guideClones
 
static UPtrVector< QMCHamiltonianhClones_uptr
 Hamiltonians. More...
 
static std::vector< QMCHamiltonian * > hClones
 
static std::vector< UPtrVector< MCWalkerConfiguration > > WPoolClones_uptr
 
static std::vector< std::vector< MCWalkerConfiguration * > > WPoolClones
 
static std::vector< UPtrVector< TrialWaveFunction > > PsiPoolClones_uptr
 
static std::vector< std::vector< TrialWaveFunction * > > PsiPoolClones
 
static std::vector< UPtrVector< QMCHamiltonian > > HPoolClones_uptr
 
static std::vector< std::vector< QMCHamiltonian * > > HPoolClones
 

Member Typedef Documentation

◆ ParticlePos

Constructor.

Definition at line 29 of file RMC.h.

◆ ReptileConfig_t

Definition at line 30 of file RMC.h.

Constructor & Destructor Documentation

◆ RMC() [1/2]

RMC ( const ProjectData project_data,
MCWalkerConfiguration w,
TrialWaveFunction psi,
QMCHamiltonian h,
Communicate comm 
)

Constructor.

Definition at line 38 of file RMC.cpp.

References RMC::Action, ParameterSet::add(), ParticleSet::addProperty(), RMC::beads, RMC::beta, QMCDriver::m_param, RMC::prestepsVMC, QMCDriver::qmc_driver_mode, QMCDriver::QMC_UPDATE_MODE, QMCDriver::QMC_WARMUP, RMC::rescaleDrift, RMC::resizeReptile, QMCDriver::RootName, and RMC::TransProb.

43  : QMCDriver(project_data, w, psi, h, comm, "RMC"),
44  prestepsVMC(-1),
45  rescaleDrift("no"),
46  beta(-1),
47  beads(-1),
48  fromScratch(true)
49 {
50  RootName = "rmc";
53  m_param.add(rescaleDrift, "drift");
54  m_param.add(beta, "beta");
55  m_param.add(beads, "beads");
56  m_param.add(resizeReptile, "resize");
57  m_param.add(prestepsVMC, "vmcpresteps");
58 
59  Action.resize(3);
60  Action[0] = w.addProperty("ActionBackward");
61  Action[1] = w.addProperty("ActionForward");
62  Action[2] = w.addProperty("ActionLocal");
63  TransProb.resize(2);
64  TransProb[0] = w.addProperty("TransProbBackward");
65  TransProb[1] = w.addProperty("TransProbForward");
66 }
int prestepsVMC
Definition: RMC.h:42
QMCDriver(const ProjectData &project_data, MCWalkerConfiguration &w, TrialWaveFunction &psi, QMCHamiltonian &h, Communicate *comm, const std::string &QMC_driver_type, bool enable_profiling=false)
Constructor.
Definition: QMCDriver.cpp:44
std::string RootName
root of all the output files
Definition: QMCDriver.h:317
bool fromScratch
Definition: RMC.h:57
ParameterSet m_param
store any parameter that has to be read from a file
Definition: QMCDriver.h:320
std::bitset< QMC_MODE_MAX > qmc_driver_mode
bits to classify QMCDriver
Definition: QMCDriver.h:93
void add(PDT &aparam, const std::string &aname_in, std::vector< PDT > candidate_values={}, TagStatus status=TagStatus::OPTIONAL)
add a new parameter corresponding to an xmlNode <parameter>
int resizeReptile
rescale for time step studies. some int>2 and new beads are inserted in between the old ones...
Definition: RMC.h:54
std::vector< int > Action
Definition: RMC.h:59
RealType beta
projection time of reptile
Definition: RMC.h:46
std::vector< int > TransProb
Definition: RMC.h:60
int beads
number of beads on the reptile, beta/tau
Definition: RMC.h:50
std::string rescaleDrift
option to enable/disable drift equation for RMC
Definition: RMC.h:44

◆ RMC() [2/2]

RMC ( const RMC )
privatedelete

copy constructor (disabled)

Member Function Documentation

◆ getRunType()

QMCRunType getRunType ( )
inlineoverridevirtual

Implements QMCDriverInterface.

Definition at line 39 of file RMC.h.

References qmcplusplus::RMC.

39 { return QMCRunType::RMC; }
RMC type: rmc, rmc-ptcl.

◆ operator=()

RMC& operator= ( const RMC )
privatedelete

Copy operator (disabled).

◆ put()

bool put ( xmlNodePtr  cur)
overridevirtual

Implements QMCDriverInterface.

Definition at line 305 of file RMC.cpp.

References QMCDriver::m_param, and ParameterSet::put().

306 {
307  m_param.put(q);
308  return true;
309 }
bool put(std::istream &is) override
read from std::istream
Definition: ParameterSet.h:42
ParameterSet m_param
store any parameter that has to be read from a file
Definition: QMCDriver.h:320

◆ resetReptiles() [1/3]

void resetReptiles ( int  nReptiles,
int  nbeads,
RealType  tau 
)
private

Definition at line 312 of file RMC.cpp.

References QMCDriver::addWalkers(), WalkerConfigurations::begin(), FairDivideLow(), WalkerConfigurations::getActiveWalkers(), MCWalkerConfiguration::ReptileList, and QMCDriver::W.

Referenced by RMC::resetReptiles(), and RMC::resetRun().

313 {
314  W.ReptileList.clear();
315  // Maybe we should be more vigorous in cleaning the MCWC WalkerList?
316  std::vector<int> repWalkerSlice;
317  int nwtot = nbeads_in * nReptiles_in;
318  FairDivideLow(nwtot, nReptiles_in, repWalkerSlice);
319  if (W.getActiveWalkers() - nwtot != 0)
320  addWalkers(nwtot - W.getActiveWalkers());
321 
322  for (int i = 0; i < nReptiles_in; i++)
323  {
324  W.ReptileList.push_back(
325  std::make_unique<Reptile>(W, W.begin() + repWalkerSlice[i], W.begin() + repWalkerSlice[i + 1]));
326  W.ReptileList[i]->setTau(tau);
327  }
328 }
ReptileList_t ReptileList
a collection of reptiles contained in MCWalkerConfiguration.
size_t getActiveWalkers() const
return the number of active walkers
void FairDivideLow(int ntot, int npart, IV &adist)
partition ntot elements among npart
Definition: FairDivide.h:114
MCWalkerConfiguration & W
walker ensemble
Definition: QMCDriver.h:323
void addWalkers(int nwalkers)
Add walkers to the end of the ensemble of walkers.
Definition: QMCDriver.cpp:338
iterator begin()
return the first iterator

◆ resetReptiles() [2/3]

void resetReptiles ( std::vector< ReptileConfig_t > &  reptile_samps,
RealType  tau 
)
private

Definition at line 330 of file RMC.cpp.

References APP_ABORT, MCWalkerConfiguration::ReptileList, RMC::resetReptiles(), and QMCDriver::W.

331 {
332  if (reptile_samps.empty())
333  {
334  APP_ABORT("RMC::resetReptiles(std::vector< ReptileConfig_t > reptile_samps): No samples!\n");
335  }
336  else
337  {
338  IndexType nReptiles_in = reptile_samps.size();
339  IndexType nBeads_in = reptile_samps[0].size();
340  resetReptiles(nReptiles_in, nBeads_in, tau);
341 
342  for (IndexType i = 0; i < W.ReptileList.size(); i++)
343  {
344  W.ReptileList[i]->setReptileSlicePositions(reptile_samps[i]);
345  }
346  }
347 }
ReptileList_t ReptileList
a collection of reptiles contained in MCWalkerConfiguration.
#define APP_ABORT(msg)
Widely used but deprecated fatal error macros from legacy code.
Definition: AppAbort.h:27
void resetReptiles(int nReptiles, int nbeads, RealType tau)
Definition: RMC.cpp:312
MCWalkerConfiguration & W
walker ensemble
Definition: QMCDriver.h:323
OHMMS_INDEXTYPE IndexType
define other types
Definition: Configuration.h:65

◆ resetReptiles() [3/3]

void resetReptiles ( std::vector< ParticlePos > &  walker_samps,
int  nbeads,
RealType  tau 
)
private

Definition at line 349 of file RMC.cpp.

References APP_ABORT, MCWalkerConfiguration::ReptileList, RMC::resetReptiles(), and QMCDriver::W.

350 {
351  if (walker_samps.empty())
352  {
353  APP_ABORT("RMC::resetReptiles(std::vector< ParticlePos > walker_samps): No samples!\n");
354  }
355  else
356  {
357  IndexType nReptiles_in = walker_samps.size();
358  resetReptiles(nReptiles_in, nBeads_in, tau);
359 
360  for (IndexType i = 0; i < W.ReptileList.size(); i++)
361  {
362  W.ReptileList[i]->setReptileSlicePositions(walker_samps[i]);
363  }
364  }
365 }
ReptileList_t ReptileList
a collection of reptiles contained in MCWalkerConfiguration.
#define APP_ABORT(msg)
Widely used but deprecated fatal error macros from legacy code.
Definition: AppAbort.h:27
void resetReptiles(int nReptiles, int nbeads, RealType tau)
Definition: RMC.cpp:312
MCWalkerConfiguration & W
walker ensemble
Definition: QMCDriver.h:323
OHMMS_INDEXTYPE IndexType
define other types
Definition: Configuration.h:65

◆ resetRun()

void resetRun ( )
private

Definition at line 143 of file RMC.cpp.

References RMC::Action, qmcplusplus::app_log(), RMC::beads, WalkerConfigurations::begin(), RMC::beta, QMCDriver::branchEngine, RandomNumberControl::Children, QMCDriver::CurrentStep, QMCDriver::DriftModifier, WalkerConfigurations::end(), CloneManager::estimatorClones, QMCDriver::Estimators, RMC::fromScratch, QMCDriver::H, CloneManager::hClones, QMCDriver::m_param, CloneManager::makeClones(), CloneManager::Movers, RMC::myPeriod4WalkerDump, QMCDriver::nBlocks, RMC::nReptiles, QMCDriver::nSteps, QMCDriver::nSubSteps, CloneManager::NumThreads, QMCDriver::nWarmupSteps, QMCDriver::Period4WalkerDump, RMC::prestepsVMC, QMCDriver::Psi, CloneManager::psiClones, ParameterSet::put(), QMCDriver::qmc_driver_mode, QMCDriver::QMC_UPDATE_MODE, QMCDriver::qmcNode, MCWalkerConfiguration::ReptileList, RMC::resetReptiles(), QMCDriver::Rng, QMCDriver::Tau, CloneManager::traceClones, QMCDriver::Traces, RMC::TransProb, QMCDriver::W, CloneManager::wClones, and CloneManager::wPerRank.

Referenced by RMC::run().

144 {
146  //For now, assume that nReptiles=NumThreads;
148 
149  if (beads < 1)
150  beads = beta / Tau;
151  else
152  beta = beads * Tau;
153 
154  app_log() << "Projection time: " << beta << " Ha^-1" << std::endl;
155  //Calculate the number of VMC presteps if not given:
156  if (prestepsVMC == -1 && fromScratch == true)
157  prestepsVMC = beads + 2;
158  //Check to see if the MCWalkerConfiguration is in a state suitable for reptation
159  if (!W.ReptileList.empty())
160  {
161  fromScratch = false;
162 
163  app_log() << "Previous RMC reptiles detected...\n";
164  if (Tau == W.ReptileList[0]->getTau() && beads == W.ReptileList[0]->size())
165  app_log() << " Using current reptiles\n"; //do nothing
166  else //we need to extrapolate off of the current reptile set.
167  {
168  //pull the reptile configurations out
169  app_log() << " Previous Tau/Beta: " << W.ReptileList[0]->getTau() << "/"
170  << W.ReptileList[0]->getTau() * W.ReptileList[0]->size() << std::endl;
171  app_log() << " New Tau/Beta: " << Tau << "/" << beta << std::endl;
172  app_log() << " Linear interpolation to get new reptile.\n";
173  std::vector<ReptileConfig_t> repSamps(0);
174  for (IndexType sampid = 0; sampid < W.ReptileList.size() && sampid < nReptiles; sampid++)
175  repSamps.push_back(W.ReptileList[sampid]->getReptileSlicePositions(Tau, beta));
176 
177  //In the event of a disparity in the number of requested reptiles and the ones received.... just copy
178  //Copies cyclically. First iteration copies the first entry, second the second, and so on. So we don't replicate just one config.
179  for (IndexType copyid = 0; repSamps.size() < nReptiles; copyid++)
180  repSamps.push_back(repSamps[copyid]);
181 
182 
183  resetReptiles(repSamps, Tau);
184  }
185  }
186 
187  //Previous run was nothing, VMC, or DMC. No reptiles--so we initialize based on whatever is there.
188  else
189  {
190  //Initialize on whatever walkers are in MCWalkerConfiguration.
191  app_log() << "Using walkers from previous non-RMC run.\n";
192  std::vector<ParticlePos> wSamps(0);
193  MCWalkerConfiguration::iterator wit(W.begin()), wend(W.end());
194  for (IndexType sampid = 0; wit != wend && sampid < nReptiles; wit++)
195  wSamps.push_back((**wit).R);
196 
197  for (IndexType copyid = 0; wSamps.size() < nReptiles; copyid++)
198  wSamps.push_back(wSamps[copyid]);
199  resetReptiles(wSamps, beads, Tau);
200  }
201 
202  //Now that we know if we're starting from scratch... decide whether to force VMC warmup.
203  if (prestepsVMC == -1 && fromScratch == true)
204  prestepsVMC = beads + 2;
205  makeClones(W, Psi, H);
207 
208  if (Movers.empty())
209  {
210  Movers.resize(NumThreads, nullptr);
211  estimatorClones.resize(NumThreads, nullptr);
212  traceClones.resize(NumThreads, nullptr);
213  Rng.resize(NumThreads);
214  branchEngine->initReptile(W);
215 
216  // hdf_archive::hdf_archive() is not thread-safe
217  for (int ip = 0; ip < NumThreads; ++ip)
218  estimatorClones[ip] = new EstimatorManagerBase(*Estimators);
219 
220 #pragma omp parallel for
221  for (int ip = 0; ip < NumThreads; ++ip)
222  {
223  std::ostringstream os;
224  estimatorClones[ip]->resetTargetParticleSet(*wClones[ip]);
225  estimatorClones[ip]->setCollectionMode(false);
226  Rng[ip] = RandomNumberControl::Children[ip]->makeClone();
227 #if !defined(REMOVE_TRACEMANAGER)
228  traceClones[ip] = Traces->makeClone();
229 #endif
230  hClones[ip]->setRandomGenerator(Rng[ip].get());
232  {
233  os << " PbyP moves with drift, using RMCUpdatePbyPWithDriftFast" << std::endl;
234  Movers[ip] =
235  new RMCUpdatePbyPWithDrift(*wClones[ip], *psiClones[ip], *hClones[ip], *Rng[ip], Action, TransProb);
236  }
237  else
238  {
239  os << " walker moves with drift, using RMCUpdateAllWithDriftFast" << std::endl;
240  Movers[ip] = new RMCUpdateAllWithDrift(*wClones[ip], *psiClones[ip], *hClones[ip], *Rng[ip], Action, TransProb);
241  }
242  Movers[ip]->nSubSteps = nSubSteps;
243  if (ip == 0)
244  app_log() << os.str() << std::endl;
245  }
246  }
247 #if !defined(REMOVE_TRACEMANAGER)
248  else
249  {
250 #pragma omp parallel for
251  for (int ip = 0; ip < NumThreads; ++ip)
252  {
253  traceClones[ip]->transfer_state_from(*Traces);
254  }
255  }
256 #endif
257  app_log().flush();
258 #pragma omp parallel for
259  for (int ip = 0; ip < NumThreads; ++ip)
260  {
261  Movers[ip]->put(qmcNode);
262  Movers[ip]->resetRun(branchEngine.get(), estimatorClones[ip], traceClones[ip], DriftModifier);
263 
264  wClones[ip]->reptile = W.ReptileList[ip].get();
265  wClones[ip]->activeBead = 0;
266  wClones[ip]->direction = +1;
267 
269  {
270  // app_log () << ip << " initWalkers for pbyp...\n";
271  Movers[ip]->initWalkersForPbyP(W.ReptileList[ip]->repstart, W.ReptileList[ip]->repend);
272  }
273  else
274  {
275  Movers[ip]->initWalkers(W.begin() + wPerRank[ip], W.begin() + wPerRank[ip + 1]);
276  }
277 
278  //this will "unroll" the reptile according to forced VMC steps (no bounce). See beginning of function for logic of setting prestepVMC.
279  for (IndexType prestep = 0; prestep < prestepsVMC; prestep++)
280  {
281  Movers[ip]->advanceWalkers(W.begin(), W.begin(), true);
282  }
283 
284  //set up initial action and transprob.
285  MCWalkerConfiguration::iterator wit(W.begin() + wPerRank[ip]), wit_end(W.begin() + wPerRank[ip + 1]);
286  }
287 
288 
289  app_log() << "Finished " << prestepsVMC << " VMC presteps\n";
290  branchEngine->checkParameters(W);
291 
292 #pragma omp parallel for
293  for (int ip = 0; ip < NumThreads; ++ip)
294  {
295  for (int prestep = 0; prestep < nWarmupSteps; ++prestep)
296  {
297  Movers[ip]->advanceWalkers(W.begin() + wPerRank[ip], W.begin() + wPerRank[ip + 1], false);
298  branchEngine->collect(CurrentStep, W);
299  }
300  }
301 
302  fromScratch = false;
303 }
int prestepsVMC
Definition: RMC.h:42
static std::vector< TrialWaveFunction * > psiClones
Definition: CloneManager.h:65
ReptileList_t ReptileList
a collection of reptiles contained in MCWalkerConfiguration.
std::vector< int > wPerRank
Walkers per MPI rank.
Definition: CloneManager.h:91
static std::vector< MCWalkerConfiguration * > wClones
Definition: CloneManager.h:61
std::ostream & app_log()
Definition: OutputManager.h:65
xmlNodePtr qmcNode
pointer to qmc node in xml file
Definition: QMCDriver.h:310
bool fromScratch
Definition: RMC.h:57
IndexType CurrentStep
current step
Definition: QMCDriver.h:263
std::vector< QMCUpdateBase * > Movers
update engines
Definition: CloneManager.h:73
std::unique_ptr< TraceManager > Traces
Traces manager.
Definition: QMCDriver.h:195
bool put(std::istream &is) override
read from std::istream
Definition: ParameterSet.h:42
ParameterSet m_param
store any parameter that has to be read from a file
Definition: QMCDriver.h:320
IndexType nSubSteps
number of steps between a step: VMCs do not evaluate energies
Definition: QMCDriver.h:272
int nReptiles
Definition: RMC.h:52
IndexType nSteps
maximum number of steps
Definition: QMCDriver.h:269
WalkerList_t::iterator iterator
FIX: a type alias of iterator for an object should not be for just one of many objects it holds...
std::bitset< QMC_MODE_MAX > qmc_driver_mode
bits to classify QMCDriver
Definition: QMCDriver.h:93
int myPeriod4WalkerDump
period for walker dump
Definition: RMC.h:48
std::unique_ptr< BranchEngineType > branchEngine
branch engine
Definition: QMCDriver.h:218
std::vector< EstimatorManagerBase * > estimatorClones
estimator managers
Definition: CloneManager.h:75
const IndexType NumThreads
number of threads
Definition: CloneManager.h:54
QMCHamiltonian & H
Hamiltonian.
Definition: QMCDriver.h:329
DriftModifierBase * DriftModifier
drift modifer
Definition: QMCDriver.h:220
void makeClones(MCWalkerConfiguration &w, TrialWaveFunction &psi, QMCHamiltonian &ham)
void resetReptiles(int nReptiles, int nbeads, RealType tau)
Definition: RMC.cpp:312
MCWalkerConfiguration & W
walker ensemble
Definition: QMCDriver.h:323
static UPtrVector< RandomBase< FullPrecRealType > > Children
OHMMS_INDEXTYPE IndexType
define other types
Definition: Configuration.h:65
static std::vector< QMCHamiltonian * > hClones
Definition: CloneManager.h:71
EstimatorManagerBase * Estimators
Observables manager.
Definition: QMCDriver.h:192
TrialWaveFunction & Psi
trial function
Definition: QMCDriver.h:326
RealType Tau
timestep
Definition: QMCDriver.h:299
IndexType nBlocks
maximum number of blocks
Definition: QMCDriver.h:266
std::vector< int > Action
Definition: RMC.h:59
std::vector< TraceManager * > traceClones
trace managers
Definition: CloneManager.h:77
int Period4WalkerDump
period of recording walker configurations
Definition: QMCDriver.h:255
RealType beta
projection time of reptile
Definition: RMC.h:46
IndexType nWarmupSteps
number of warmup steps
Definition: QMCDriver.h:275
UPtrVector< RandomBase< FullPrecRealType > > Rng
Random number generators.
Definition: QMCDriver.h:341
iterator end()
return the last iterator, [begin(), end())
std::vector< int > TransProb
Definition: RMC.h:60
int beads
number of beads on the reptile, beta/tau
Definition: RMC.h:50
iterator begin()
return the first iterator

◆ resetVars()

void resetVars ( )
inlineprivate

check the run-time environments

Definition at line 63 of file RMC.h.

References RMC::beads, RMC::beta, RMC::nReptiles, and RMC::prestepsVMC.

Referenced by RMC::run().

64  {
65  prestepsVMC = -1;
66  beads = -1;
67  beta = -1;
68  nReptiles = -1;
69  };
int prestepsVMC
Definition: RMC.h:42
int nReptiles
Definition: RMC.h:52
RealType beta
projection time of reptile
Definition: RMC.h:46
int beads
number of beads on the reptile, beta/tau
Definition: RMC.h:50

◆ run()

bool run ( )
overridevirtual

Implements QMCDriverInterface.

Definition at line 68 of file RMC.cpp.

References qmcplusplus::app_log(), Communicate::bcast(), WalkerConfigurations::begin(), QMCDriver::branchEngine, RandomNumberControl::Children, ParticleSet::Collectables, QMCDriver::CurrentStep, CloneManager::estimatorClones, QMCDriver::Estimators, QMCDriver::finalize(), Communicate::getName(), QMCDriver::MaxCPUSecs, CloneManager::Movers, MPIObjectBase::myComm, RMC::myPeriod4WalkerDump, QMCDriver::nBlocks, QMCDriver::nSteps, CloneManager::NumThreads, omp_get_thread_num(), QMCDriver::Period4CheckProperties, QMCDriver::Period4WalkerDump, QMCDriver::qmc_driver_mode, QMCDriver::QMC_UPDATE_MODE, Communicate::rank(), QMCDriver::recordBlock(), RMC::resetRun(), RMC::resetVars(), QMCDriver::Rng, qmcplusplus::run_time_manager, PooledData< T >::size(), LoopTimer< CLOCK >::start(), EstimatorManagerBase::start(), LoopTimer< CLOCK >::stop(), EstimatorManagerBase::stop(), EstimatorManagerBase::stopBlock(), CloneManager::traceClones, QMCDriver::Traces, QMCDriver::W, CloneManager::wClones, and CloneManager::wPerRank.

69 {
70  resetRun();
71  //start the main estimator
73  for (int ip = 0; ip < NumThreads; ++ip)
74  Movers[ip]->startRun(nBlocks, false);
75 #if !defined(REMOVE_TRACEMANAGER)
76  Traces->startRun(nBlocks, traceClones);
77 #endif
78  const bool has_collectables = W.Collectables.size();
79 
80  LoopTimer<> rmc_loop;
81  RunTimeControl<> runtimeControl(run_time_manager, MaxCPUSecs, myComm->getName(), myComm->rank() == 0);
82  for (int block = 0; block < nBlocks; ++block)
83  {
84  rmc_loop.start();
85 #pragma omp parallel
86  {
87  int ip = omp_get_thread_num();
89  //assign the iterators and resuse them
90  MCWalkerConfiguration::iterator wit(W.begin() + wPerRank[ip]), wit_end(W.begin() + wPerRank[ip + 1]);
91  Movers[ip]->startBlock(nSteps);
92  int now_loc = CurrentStep;
93 
94  RealType cnorm = 1.0; //This is because there is only one reptile per walkerset.
95 
96  for (int step = 0; step < nSteps; ++step)
97  {
98  //collectables are reset, it is accumulated while advancing walkers
99  wClones[ip]->resetCollectables();
100  Movers[ip]->advanceWalkers(wit, wit_end, false);
101  if (has_collectables)
102  wClones[ip]->Collectables *= cnorm;
103  Movers[ip]->accumulate(wit, wit_end);
104 
105  ++now_loc;
106  if (Period4WalkerDump && now_loc % myPeriod4WalkerDump == 0)
107  wClones[ip]->saveEnsemble(wit, wit_end);
108 
109  branchEngine->collect(
110  CurrentStep,
111  W); //Ray Clay: For now, collects and syncs based on first reptile. Need a better way to do this.
112  }
113  Movers[ip]->stopBlock(false);
114  } //end-of-parallel for
115  CurrentStep += nSteps;
117  recordBlock(block);
118  rmc_loop.stop();
119 
120  bool stop_requested = false;
121  // Rank 0 decides whether the time limit was reached
122  if (!myComm->rank())
123  stop_requested = runtimeControl.checkStop(rmc_loop);
124  myComm->bcast(stop_requested);
125 
126  if (stop_requested)
127  {
128  if (!myComm->rank())
129  app_log() << runtimeControl.generateStopMessage("RMC", block);
130  run_time_manager.markStop();
131  break;
132  }
133  } //block
135  //copy back the random states
136  for (int ip = 0; ip < NumThreads; ++ip)
137  RandomNumberControl::Children[ip] = Rng[ip]->makeClone();
138  //return nbeads and stuff to its original unset state;
139  resetVars();
140  return finalize(nBlocks);
141 }
size_type size() const
return the size of the data
Definition: PooledData.h:48
int MaxCPUSecs
maximum cpu in secs
Definition: QMCDriver.h:302
std::vector< int > wPerRank
Walkers per MPI rank.
Definition: CloneManager.h:91
int rank() const
return the rank
Definition: Communicate.h:116
void recordBlock(int block) override
record the state of the block
Definition: QMCDriver.cpp:307
static std::vector< MCWalkerConfiguration * > wClones
Definition: CloneManager.h:61
std::ostream & app_log()
Definition: OutputManager.h:65
RunTimeManager< ChronoClock > run_time_manager
IndexType CurrentStep
current step
Definition: QMCDriver.h:263
std::vector< QMCUpdateBase * > Movers
update engines
Definition: CloneManager.h:73
std::unique_ptr< TraceManager > Traces
Traces manager.
Definition: QMCDriver.h:195
omp_int_t omp_get_thread_num()
Definition: OpenMP.h:25
IndexType nSteps
maximum number of steps
Definition: QMCDriver.h:269
bool finalize(int block, bool dumpwalkers=true)
finalize a qmc section
Definition: QMCDriver.cpp:318
const std::string & getName() const
Definition: Communicate.h:131
WalkerList_t::iterator iterator
FIX: a type alias of iterator for an object should not be for just one of many objects it holds...
std::bitset< QMC_MODE_MAX > qmc_driver_mode
bits to classify QMCDriver
Definition: QMCDriver.h:93
Communicate * myComm
pointer to Communicate
Definition: MPIObjectBase.h:62
int myPeriod4WalkerDump
period for walker dump
Definition: RMC.h:48
std::unique_ptr< BranchEngineType > branchEngine
branch engine
Definition: QMCDriver.h:218
std::vector< EstimatorManagerBase * > estimatorClones
estimator managers
Definition: CloneManager.h:75
const IndexType NumThreads
number of threads
Definition: CloneManager.h:54
MCWalkerConfiguration & W
walker ensemble
Definition: QMCDriver.h:323
static UPtrVector< RandomBase< FullPrecRealType > > Children
OHMMS_INDEXTYPE IndexType
define other types
Definition: Configuration.h:65
Buffer_t Collectables
observables in addition to those registered in Properties/PropertyList
Definition: ParticleSet.h:126
void resetRun()
Definition: RMC.cpp:143
QMCTraits::RealType RealType
EstimatorManagerBase * Estimators
Observables manager.
Definition: QMCDriver.h:192
void stopBlock(RealType accept, bool collectall=true)
stop a block
void bcast(T &)
IndexType nBlocks
maximum number of blocks
Definition: QMCDriver.h:266
int Period4WalkerDump
period of recording walker configurations
Definition: QMCDriver.h:255
std::vector< TraceManager * > traceClones
trace managers
Definition: CloneManager.h:77
int Period4CheckProperties
period of dumping walker positions and IDs for Forward Walking
Definition: QMCDriver.h:249
UPtrVector< RandomBase< FullPrecRealType > > Rng
Random number generators.
Definition: QMCDriver.h:341
void start(int blocks, bool record=true)
start a run
void resetVars()
check the run-time environments
Definition: RMC.h:63
iterator begin()
return the first iterator

Member Data Documentation

◆ Action

std::vector<int> Action
private

Definition at line 59 of file RMC.h.

Referenced by RMC::resetRun(), and RMC::RMC().

◆ beads

int beads
private

number of beads on the reptile, beta/tau

Definition at line 50 of file RMC.h.

Referenced by RMC::resetRun(), RMC::resetVars(), and RMC::RMC().

◆ beta

RealType beta
private

projection time of reptile

Definition at line 46 of file RMC.h.

Referenced by RMC::resetRun(), RMC::resetVars(), and RMC::RMC().

◆ fromScratch

bool fromScratch
private

Definition at line 57 of file RMC.h.

Referenced by RMC::resetRun().

◆ myPeriod4WalkerDump

int myPeriod4WalkerDump
private

period for walker dump

Definition at line 48 of file RMC.h.

Referenced by RMC::resetRun(), and RMC::run().

◆ nReptiles

int nReptiles
private

Definition at line 52 of file RMC.h.

Referenced by RMC::resetRun(), and RMC::resetVars().

◆ prestepsVMC

int prestepsVMC
private

Definition at line 42 of file RMC.h.

Referenced by RMC::resetRun(), RMC::resetVars(), and RMC::RMC().

◆ rescaleDrift

std::string rescaleDrift
private

option to enable/disable drift equation for RMC

Definition at line 44 of file RMC.h.

Referenced by RMC::RMC().

◆ resizeReptile

int resizeReptile
private

rescale for time step studies. some int>2 and new beads are inserted in between the old ones.

Definition at line 54 of file RMC.h.

Referenced by RMC::RMC().

◆ TransProb

std::vector<int> TransProb
private

Definition at line 60 of file RMC.h.

Referenced by RMC::resetRun(), and RMC::RMC().

◆ qmcplusplus::RMCUpdateAllWithDrift

class qmcplusplus::RMCUpdateAllWithDrift


Implements the RMC algorithm using all electron moves

Definition at line 23 of file RMCUpdateAll.h.

+ Inheritance diagram for RMCUpdateAllWithDrift:
+ Collaboration diagram for RMCUpdateAllWithDrift:

Public Types

enum  { SYM_ACTION, DMC_ACTION }
 Constructor. More...
 
- Public Types inherited from QMCUpdateBase
using Walker_t = MCWalkerConfiguration::Walker_t
 
using WalkerIter_t = MCWalkerConfiguration::iterator
 
using BranchEngineType = SimpleFixedNodeBranch
 
using mPosType = PosType
 
using mTensorType = TensorType
 
- Public Types inherited from QMCTraits
enum  { DIM = OHMMS_DIM, DIM_VGL = OHMMS_DIM + 2 }
 
using QTBase = QMCTypes< OHMMS_PRECISION, DIM >
 
using QTFull = QMCTypes< OHMMS_PRECISION_FULL, DIM >
 
using RealType = QTBase::RealType
 
using ComplexType = QTBase::ComplexType
 
using ValueType = QTBase::ValueType
 
using PosType = QTBase::PosType
 
using GradType = QTBase::GradType
 
using TensorType = QTBase::TensorType
 
using IndexType = OHMMS_INDEXTYPE
 define other types More...
 
using FullPrecRealType = QTFull::RealType
 
using FullPrecValueType = QTFull::ValueType
 
using PropertySetType = RecordNamedProperty< FullPrecRealType >
 define PropertyList_t More...
 
using PtclGrpIndexes = std::vector< std::pair< int, int > >
 

Public Member Functions

 RMCUpdateAllWithDrift (MCWalkerConfiguration &w, TrialWaveFunction &psi, QMCHamiltonian &h, RandomBase< FullPrecRealType > &rg, std::vector< int > act, std::vector< int > tp)
 Constructor. More...
 
 ~RMCUpdateAllWithDrift () override
 
void advanceWalker (Walker_t &thisWalker, bool recompute) override
 move a walker More...
 
void advanceWalkers (WalkerIter_t it, WalkerIter_t it_end, bool measure) override
 advance walkers executed at each step More...
 
void advanceWalkersVMC ()
 
void advanceWalkersRMC ()
 
void checkReptile (WalkerIter_t it, WalkerIter_t it_end)
 
void initWalkers (WalkerIter_t it, WalkerIter_t it_end) override
 initialize Walker for walker update More...
 
void accumulate (WalkerIter_t it, WalkerIter_t it_end)
 
bool put (xmlNodePtr cur) override
 process options More...
 
- Public Member Functions inherited from QMCUpdateBase
 QMCUpdateBase (MCWalkerConfiguration &w, TrialWaveFunction &psi, QMCHamiltonian &h, RandomBase< FullPrecRealType > &rg)
 Constructor. More...
 
 QMCUpdateBase (MCWalkerConfiguration &w, TrialWaveFunction &psi, TrialWaveFunction &guide, QMCHamiltonian &h, RandomBase< FullPrecRealType > &rg)
 Alt Constructor. More...
 
virtual ~QMCUpdateBase ()
 destructor More...
 
RealType acceptRatio () const
 
void resetRun (BranchEngineType *brancher, EstimatorManagerBase *est, TraceManager *traces, const DriftModifierBase *driftmodifer)
 reset the QMCUpdateBase parameters More...
 
void resetRun2 (BranchEngineType *brancher, EstimatorManagerBase *est, TraceManager *traces, WalkerLogCollector *wlog_collector_, const DriftModifierBase *driftmodifer)
 
RealType getTau ()
 
void setTau (RealType t)
 
RealType getSpinMass ()
 
void setSpinMass (RealType m)
 
void getLogs (std::vector< RealType > &logs)
 
void set_step (int step)
 
void startRun (int blocks, bool record)
 start a run More...
 
void stopRun ()
 stop a run More...
 
void stopRun2 ()
 
void startBlock (int steps)
 prepare to start a block More...
 
void stopBlock (bool collectall=true)
 stop a block More...
 
void setMultiplicity (WalkerIter_t it, WalkerIter_t it_end)
 set the multiplicity of the walkers to branch More...
 
void setMultiplicity (Walker_t &awalker) const
 
virtual void initWalkersForPbyP (WalkerIter_t it, WalkerIter_t it_end)
 initialize Walker buffers for PbyP update More...
 
void accumulate (WalkerIter_t it, WalkerIter_t it_end)
 
virtual RealType advanceWalkerForEE (Walker_t &w1, std::vector< PosType > &dR, std::vector< int > &iats, std::vector< int > &rs, std::vector< RealType > &ratios)
 
int RMC_checkIndex (int N, int NMax)
 
void RMC_checkWalkerBounds (WalkerIter_t &it, WalkerIter_t first, WalkerIter_t last)
 
RealType logBackwardGF (const ParticleSet::ParticlePos &displ)
 

Private Member Functions

 RMCUpdateAllWithDrift (const RMCUpdateAllWithDrift &)=delete
 Copy Constructor (disabled) More...
 
RMCUpdateAllWithDriftoperator= (const RMCUpdateAllWithDrift &)=delete
 Copy operator (disabled). More...
 

Private Attributes

std::vector< int > Action
 
std::vector< int > TransProb
 
bool scaleDrift
 
IndexType actionType
 
IndexType vmcSteps
 
IndexType equilSteps
 
IndexType vmcToDoSteps
 
IndexType equilToDoSteps
 

Additional Inherited Members

- Public Attributes inherited from QMCUpdateBase
int nSubSteps
 number of steps per measurement More...
 
DriverDebugChecks debug_checks_ = DriverDebugChecks::ALL_OFF
 determine additional checks for debugging purpose More...
 
std::string debug_checks_str_
 
IndexType MaxAge
 MaxAge>0 indicates branch is done. More...
 
IndexType nAccept
 counter for number of moves accepted More...
 
IndexType nReject
 counter for number of moves rejected More...
 
IndexType nAllRejected
 Total number of the steps when all the particle moves are rejected. More...
 
IndexType nNodeCrossing
 Total number of node crossings per block. More...
 
IndexType NonLocalMoveAccepted
 Total numer of non-local moves accepted. More...
 
RealType Tau
 timestep More...
 
RealType spinMass
 spin mass More...
 
bool UseDrift
 use Drift More...
 
RealType csoffset
 normalization offset for cs type runs. More...
 
TraceManagerTraces
 traces More...
 
WalkerLogCollectorwlog_collector
 
- Protected Member Functions inherited from QMCUpdateBase
RealType getNodeCorrection (const ParticleSet::ParticleGradient &g, ParticleSet::ParticlePos &gscaled)
 evaluate the ratio of scaled velocity and velocity More...
 
 QMCUpdateBase (const QMCUpdateBase &)=delete
 copy constructor (disabled) More...
 
- Static Protected Member Functions inherited from QMCUpdateBase
static void checkLogAndGL (ParticleSet &pset, TrialWaveFunction &twf, const std::string_view location)
 check logpsi and grad and lap against values computed from scratch More...
 
- Protected Attributes inherited from QMCUpdateBase
bool UpdatePbyP
 update particle-by-particle More...
 
IndexType NumPtcl
 number of particles More...
 
RealType m_oneover2tau
 Time-step factor $ 1/(2\tau)$. More...
 
RealType m_sqrttau
 Time-step factor $ \sqrt{\tau}$. More...
 
RealType m_tauovermass
 tau/mass More...
 
RealType m_r2max
 maximum displacement^2 More...
 
MCWalkerConfigurationW
 walker ensemble More...
 
TrialWaveFunctionPsi
 trial function More...
 
TrialWaveFunctionGuide
 guide function More...
 
QMCHamiltonianH
 Hamiltonian. More...
 
RandomBase< FullPrecRealType > & RandomGen
 random number generator More...
 
const BranchEngineTypebranchEngine
 branch engine, stateless reference to the one in QMCDriver More...
 
const DriftModifierBaseDriftModifier
 drift modifer, stateless reference to the one in QMCDriver More...
 
EstimatorManagerBaseEstimators
 estimator More...
 
ParameterSet myParams
 parameters More...
 
std::vector< RealTypeMassInvS
 1/Mass per species More...
 
std::vector< RealTypeMassInvP
 1/Mass per particle More...
 
std::vector< RealTypeSqrtTauOverMass
 sqrt(tau/Mass) per particle More...
 
ParticleSet::ParticlePos drift
 temporary storage for drift More...
 
ParticleSet::ParticlePos deltaR
 temporary storage for random displacement More...
 
ParticleSet::ParticleScalar deltaS
 temporart storage for spin displacement More...
 
ParticleSet::ParticleGradient G
 storage for differential gradients for PbyP update More...
 
ParticleSet::ParticleGradient dG
 
ParticleSet::ParticleLaplacian L
 storage for differential laplacians for PbyP update More...
 
ParticleSet::ParticleLaplacian dL
 

Member Enumeration Documentation

◆ anonymous enum

anonymous enum

Constructor.

Enumerator
SYM_ACTION 
DMC_ACTION 

Definition at line 28 of file RMCUpdateAll.h.

Constructor & Destructor Documentation

◆ RMCUpdateAllWithDrift() [1/2]

RMCUpdateAllWithDrift ( MCWalkerConfiguration w,
TrialWaveFunction psi,
QMCHamiltonian h,
RandomBase< FullPrecRealType > &  rg,
std::vector< int >  act,
std::vector< int >  tp 
)

Constructor.

Definition at line 40 of file RMCUpdateAll.cpp.

References RMCUpdateAllWithDrift::actionType, RMCUpdateAllWithDrift::equilSteps, RMCUpdateAllWithDrift::equilToDoSteps, RMCUpdateAllWithDrift::scaleDrift, RMCUpdateAllWithDrift::SYM_ACTION, RMCUpdateAllWithDrift::vmcSteps, and RMCUpdateAllWithDrift::vmcToDoSteps.

46  : QMCUpdateBase(w, psi, h, rg), Action(act), TransProb(tp)
47 {
48  scaleDrift = false;
50  vmcToDoSteps = 0;
51  equilToDoSteps = 0;
52  vmcSteps = 0;
53  equilSteps = 0;
54 }
QMCUpdateBase(MCWalkerConfiguration &w, TrialWaveFunction &psi, QMCHamiltonian &h, RandomBase< FullPrecRealType > &rg)
Constructor.

◆ ~RMCUpdateAllWithDrift()

~RMCUpdateAllWithDrift ( )
override

Definition at line 56 of file RMCUpdateAll.cpp.

56 {}

◆ RMCUpdateAllWithDrift() [2/2]

RMCUpdateAllWithDrift ( const RMCUpdateAllWithDrift )
privatedelete

Copy Constructor (disabled)

Member Function Documentation

◆ accumulate()

void accumulate ( WalkerIter_t  it,
WalkerIter_t  it_end 
)

Definition at line 533 of file RMCUpdateAll.cpp.

References EstimatorManagerBase::accumulate(), RMCUpdateAllWithDrift::equilToDoSteps, QMCUpdateBase::Estimators, RMCUpdateAllWithDrift::vmcToDoSteps, and QMCUpdateBase::W.

534 {
535  if (vmcToDoSteps == 0 && equilToDoSteps == 0)
536  Estimators->accumulate(W, it, it_end);
537  else
538  ;
539 }
void accumulate(MCWalkerConfiguration &W)
accumulate the measurements
EstimatorManagerBase * Estimators
estimator
MCWalkerConfiguration & W
walker ensemble

◆ advanceWalker()

void advanceWalker ( Walker_t thisWalker,
bool  recompute 
)
overridevirtual

move a walker

Implements QMCUpdateBase.

Definition at line 292 of file RMCUpdateAll.cpp.

292 {}

◆ advanceWalkers()

void advanceWalkers ( WalkerIter_t  it,
WalkerIter_t  it_end,
bool  recompute 
)
overridevirtual

advance walkers executed at each step

Derived classes implement how to move walkers and accept/reject moves.

Reimplemented from QMCUpdateBase.

Definition at line 294 of file RMCUpdateAll.cpp.

References RMCUpdateAllWithDrift::advanceWalkersRMC(), RMCUpdateAllWithDrift::advanceWalkersVMC(), RMCUpdateAllWithDrift::equilToDoSteps, and RMCUpdateAllWithDrift::vmcToDoSteps.

295 {
296  if (vmcToDoSteps > 0)
297  {
299  vmcToDoSteps--;
300  }
301  else if (vmcToDoSteps == 0 && equilToDoSteps > 0)
302  {
304  equilToDoSteps--;
305  }
306  else
307  {
309  }
310 }

◆ advanceWalkersRMC()

void advanceWalkersRMC ( )

Like DMC, this filters the local energy to ignore divergences near pathological points in phase space.

RealType eest = W.reptile->eest; RealType fbet = std::max(eest - curhead.Properties(LOCALENERGY), eest - eloc);

RealType rawcutoff=100*stdsqrt(W.reptile->evar); RealType cutoffmax = 1.5*rawcutoff; RealType cutoff=1; if (fbet > rawcutoff) cutoff = 1-(fbet - rawcutoff)/(rawcutoff*0.5); if( fbet > cutoffmax ) cutoff=0;

RealType tauscale = W.reptile->tauscale; W.Properties(W.reptile->Action[2])= 0.5*Tau*eloc*cutoff*tauscale;
RealType dS_old = +(curhead.Properties(LOGPSI) + lastbead.Properties(LOGPSI) - logpsi - nextlastbead.Properties(LOGPSI))

  • curhead.Properties(W.reptile->Action[2]) + W.Properties(W.reptile->Action[2])
  • curhead.Properties(W.reptile->Action[forward]) + W.Properties(W.reptile->Action[backward])
  • (lastbead.Properties(W.reptile->Action[2]) + nextlastbead.Properties(W.reptile->Action[2]))
  • (lastbead.Properties(W.reptile->Action[forward]) + nextlastbead.Properties(W.reptile->Action[backward])); acceptProb=std::exp(-dS_0 + (nextlastbead.Properties(W.reptile->TransProb[backward]) - curhead.Properties(W.reptile->TransProb[forward])));

Definition at line 312 of file RMCUpdateAll.cpp.

References Reptile::Action, RMCUpdateAllWithDrift::actionType, Walker< t_traits, p_traits >::Age, qmcplusplus::app_log(), qmcplusplus::assignDrift(), QMCHamiltonian::auxHevaluate(), QMCUpdateBase::branchEngine, QMCUpdateBase::deltaR, Reptile::direction, SimpleFixedNodeBranch::DMCLinkAction(), qmcplusplus::Dot(), QMCUpdateBase::drift, RMCUpdateAllWithDrift::equilSteps, RMCUpdateAllWithDrift::equilToDoSteps, QMCHamiltonian::evaluate(), TrialWaveFunction::evaluateLog(), qmcplusplus::exp(), Reptile::flip(), ParticleSet::G, Reptile::getCenter(), Reptile::getHead(), Reptile::getNewHead(), Reptile::getNext(), TrialWaveFunction::getPhase(), TrialWaveFunction::getPhaseDiff(), ParticleSet::getPropertyBase(), Reptile::getTail(), Reptile::getTransProb(), QMCUpdateBase::H, ParticleSet::loadWalker(), QMCUpdateBase::m_oneover2tau, QMCUpdateBase::m_sqrttau, QMCUpdateBase::m_tauovermass, qmcplusplus::makeGaussRandomWithEngine(), ParticleSet::makeMoveAllParticlesWithDrift(), QMCUpdateBase::MaxAge, omptarget::min(), QMCUpdateBase::nAccept, QMCUpdateBase::nReject, SimpleFixedNodeBranch::phaseChanged(), ParticleSet::Properties, Walker< t_traits, p_traits >::Properties, QMCUpdateBase::Psi, ParticleSet::R, Walker< t_traits, p_traits >::R, QMCUpdateBase::RandomGen, QMCHamiltonian::rejectedMove(), MCWalkerConfiguration::reptile, QMCHamiltonian::saveProperty(), Reptile::saveTransProb(), ParticleSet::saveWalker(), RMCUpdateAllWithDrift::scaleDrift, qmcplusplus::setScaledDrift(), RMCUpdateAllWithDrift::SYM_ACTION, SimpleFixedNodeBranch::symLinkAction(), Reptile::TransProb, ParticleSet::update(), and QMCUpdateBase::W.

Referenced by RMCUpdateAllWithDrift::advanceWalkers().

313 {
314  IndexType direction = W.reptile->direction;
315  IndexType forward = (1 - direction) / 2;
316  IndexType backward = (1 + direction) / 2;
317  Walker_t& curhead = W.reptile->getHead();
318  Walker_t& centerbead = W.reptile->getCenter();
319 
320  // if(centerbead.Age>=MaxAge)
321  // {
322  // vmcToDoSteps=vmcSteps;
323  // equilToDoSteps=equilSteps;
324  // app_log()<<"MaxAge for center bead exceeded. Reequilibrating. "<<vmcSteps<<" "<<equilSteps<< std::endl;
325  // }
326 
327  //We are going to monitor the center bead's age to determine whether we force
328  //moves. This is because the ends are less likely to get pinned.
329 
330  // centerbead.Age+=1;
331 
332  W.loadWalker(curhead, false);
333  //RealType nodecorr=1;
334  if (scaleDrift == true)
335  setScaledDrift(m_tauovermass, curhead.G, drift);
336  else
337  assignDrift(m_tauovermass, curhead.G, drift);
338  //app_log()<<"Sign head = "<<curhead.Properties(SIGN)<< std::endl;
339  //app_log()<<"Old phase = "<<Psi.getPhase()<< std::endl;
341  RealType r2proposed = Dot(deltaR, deltaR);
342  RealType r2accept = 0.0;
343  // W.reptile->r2prop += r2proposed;
344  // W.reptile->r2samp++;
346  {
347  ++nReject;
348  H.rejectedMove(W, curhead);
349  curhead.Age += 1;
350  W.reptile->flip();
351  return;
352  }
353  RealType logpsi(Psi.evaluateLog(W));
354  // app_log()<<"Sign newhead = "<<W.Properties(SIGN)<< std::endl;
355  //RealType* restrict old_headProp ((*it)->getPropertyBase());
356  //old_headProp[TransProb[forward]]= 0.5*Dot(deltaR,deltaR);
357 
358  curhead.Properties(W.reptile->TransProb[forward]) = -0.5 * Dot(deltaR, deltaR);
359  curhead.Properties(W.reptile->Action[forward]) = 0.5 * 0.5 * Dot(deltaR, deltaR);
360 
361  RealType logGf = -0.5 * Dot(deltaR, deltaR);
362  //W.reptile->saveTransProb(curhead,+1,logGf);
363 
364  Walker_t::ParticlePos fromdeltaR(deltaR);
365 
366 
367  if (scaleDrift == true)
369  else
371  fromdeltaR = curhead.R - W.R - drift;
372  FullPrecRealType* restrict new_headProp(W.getPropertyBase());
373  W.Properties(W.reptile->TransProb[backward]) = -m_oneover2tau * Dot(fromdeltaR, fromdeltaR);
374  W.Properties(W.reptile->Action[backward]) = 0.5 * m_oneover2tau * Dot(fromdeltaR, fromdeltaR);
375 
376  RealType logGb = -m_oneover2tau * Dot(fromdeltaR, fromdeltaR);
377 
378  // W.reptile->saveTransProb(W,-1, logGb);
379 
380  Walker_t &lastbead(W.reptile->getTail()), nextlastbead(W.reptile->getNext());
381  //Implementing the fixed-node approximation. If phase difference is not a multiple of 2pi, bounce away from node.
382  RealType newphase = Psi.getPhase();
383  RealType phasediff = newphase - curhead.Properties(WP::SIGN);
384  //Reject & bounce if node crossed.
386  {
387  ++nReject;
388  H.rejectedMove(W, curhead);
389  curhead.Age += 1;
390  W.reptile->flip();
391  //app_log()<<"hit a node. Bouncing...\n";
392  return;
393  }
394  RealType eloc = H.evaluate(W);
395  W.Properties(WP::LOCALENERGY) = eloc;
396  //new_headProp[Action[2]]= 0.5*Tau*eloc;
397  ////////////////////////////////////////////////////////////////////////
398  /// Like DMC, this filters the local energy to ignore divergences near pathological points in phase space.
399  ////////////////////////////////////////////////////////////////////////
400  /// RealType eest = W.reptile->eest;
401  /// RealType fbet = std::max(eest - curhead.Properties(LOCALENERGY), eest - eloc);
402 
403  /// RealType rawcutoff=100*std::sqrt(W.reptile->evar);
404  /// RealType cutoffmax = 1.5*rawcutoff;
405  /// RealType cutoff=1;
406  /// if (fbet > rawcutoff)
407  /// cutoff = 1-(fbet - rawcutoff)/(rawcutoff*0.5);
408  /// if( fbet > cutoffmax )
409  /// cutoff=0;
410  //////////////////////////////////////////////////////////////////////////
411  /// RealType tauscale = W.reptile->tauscale;
412  /// W.Properties(W.reptile->Action[2])= 0.5*Tau*eloc*cutoff*tauscale;
413  RealType dS = 0;
414  RealType acceptProb = 0;
415 
416  if (actionType == SYM_ACTION)
417  {
418  RealType oldhead_logpsi = curhead.Properties(WP::LOGPSI);
419  RealType oldtail_logpsi = lastbead.Properties(WP::LOGPSI);
420  RealType newtail_logpsi = nextlastbead.Properties(WP::LOGPSI);
421 
422  RealType oldhead_e = curhead.Properties(WP::LOCALENERGY);
423  RealType oldtail_e = lastbead.Properties(WP::LOCALENERGY);
424  RealType newhead_e = W.Properties(WP::LOCALENERGY);
425  RealType newtail_e = nextlastbead.Properties(WP::LOCALENERGY);
426 
427  RealType head_forward = W.reptile->getTransProb(curhead, +1);
428  RealType head_backward = W.reptile->getTransProb(W, -1);
429  RealType tail_forward = W.reptile->getTransProb(lastbead, +1);
430  RealType tail_backward = W.reptile->getTransProb(nextlastbead, -1);
431 
432  // RealType head_forward=curhead.Properties(W.reptile->TransProb[forward]);
433  // RealType head_backward=W.Properties(W.reptile->TransProb[backward]);
434  // RealType tail_forward=lastbead.Properties(W.reptile->TransProb[forward]);
435  // RealType tail_backward=nextlastbead.Properties(W.reptile->TransProb[backward]);
436 
437 
438  // RealType dS_head=branchEngine->symLinkActionBare(head_forward, head_backward, newhead_e, oldhead_e);
439  // RealType dS_tail=branchEngine->symLinkActionBare(tail_forward, tail_backward, newtail_e, oldtail_e);
440  RealType dS_head = branchEngine->symLinkAction(head_forward, head_backward, newhead_e, oldhead_e);
441  RealType dS_tail = branchEngine->symLinkAction(tail_forward, tail_backward, newtail_e, oldtail_e);
442 
443 
444  RealType dS_0 = dS_head - dS_tail +
445  (curhead.Properties(WP::LOGPSI) + lastbead.Properties(WP::LOGPSI) - logpsi -
446  nextlastbead.Properties(WP::LOGPSI));
447 
448  /// RealType dS_old = +(curhead.Properties(LOGPSI) + lastbead.Properties(LOGPSI) - logpsi - nextlastbead.Properties(LOGPSI))
449  /// + curhead.Properties(W.reptile->Action[2]) + W.Properties(W.reptile->Action[2])
450  /// + curhead.Properties(W.reptile->Action[forward]) + W.Properties(W.reptile->Action[backward])
451  /// - (lastbead.Properties(W.reptile->Action[2]) + nextlastbead.Properties(W.reptile->Action[2]))
452  /// - (lastbead.Properties(W.reptile->Action[forward]) + nextlastbead.Properties(W.reptile->Action[backward]));
453  ///acceptProb=std::exp(-dS_0 + (nextlastbead.Properties(W.reptile->TransProb[backward]) - curhead.Properties(W.reptile->TransProb[forward])));
454 
455  // acceptProb=std::exp(-dS_0 + tail_backward - head_forward);
456  // app_log()<<"logGf (calced) = "
457  // app_log()<<"dS_old="<<dS_old<< std::endl;
458  // app_log()<<"dS_head="<<dS_head<< std::endl;
459  // app_log()<<"dS_tail="<<dS_tail<< std::endl;
460  // app_log()<<"dS' = "<<dS_0<< std::endl;
461  // app_log()<<"W.Properties(WP::LOCALENERGY)="<<W.Properties(WP::LOCALENERGY)<< std::endl;
462 
463  // app_log()<<"---------------\n";
464  acceptProb = std::exp(-dS_0 +
465  (nextlastbead.Properties(W.reptile->TransProb[backward]) -
466  curhead.Properties(W.reptile->TransProb[forward]))); //tail_backward - head_forward);
467  // acceptProb=std::min(1.0,std::exp(-dS + -(curhead.Properties(LOGPSI) + lastbead.Properties(LOGPSI) - logpsi - nextlastbead.Properties(LOGPSI)) + tail_backward - head_forward));
468  }
469  else
470  {
471  // dS = curhead.Properties(W.reptile->Action[2]) + W.Properties(W.reptile->Action[2])
472  //- (lastbead.Properties(W.reptile->Action[2]) + nextlastbead.Properties(W.reptile->Action[2]));
473  RealType dS_head = branchEngine->DMCLinkAction(eloc, curhead.Properties(WP::LOCALENERGY));
474  RealType dS_tail =
475  branchEngine->DMCLinkAction(lastbead.Properties(WP::LOCALENERGY), nextlastbead.Properties(WP::LOCALENERGY));
476  //dS=branchEngine->DMCLinkAction(eloc,curhead.Properties(WP::LOCALENERGY)) - branchEngine->DMCLinkAction(lastbead.Properties(WP::LOCALENERGY),nextlastbead.Properties(WP::LOCALENERGY));
477  dS = dS_head - dS_tail;
478  acceptProb = std::min((RealType)1.0, std::exp(-dS));
479  }
480 
481  //app_log()<<acceptProb<< std::endl;
482  // app_log()<<"r2proposed.... = "<<r2proposed<< std::endl;
483  if ((RandomGen() < acceptProb) || curhead.Age >= MaxAge)
484  {
485  r2accept = r2proposed;
486  // W.reptile->r2accept+=r2accept;
488  if (curhead.Age >= MaxAge)
489  {
490  app_log() << "\tForce Acceptance...\n";
492  }
493  W.saveWalker(overwriteWalker);
494  overwriteWalker.Properties(WP::LOCALENERGY) = eloc;
495  overwriteWalker.Properties(W.reptile->Action[forward]) = 0;
496  overwriteWalker.Properties(W.reptile->Action[backward]) = W.Properties(W.reptile->Action[backward]);
497  overwriteWalker.Properties(W.reptile->Action[2]) = W.Properties(W.reptile->Action[2]);
498  //overwriteWalker.Properties(W.reptile->TransProb[forward])=W.Properties(W.reptile->TransProb[forward]);
499  W.reptile->saveTransProb(overwriteWalker, +1, 0);
500  W.reptile->saveTransProb(overwriteWalker, -1, logGb);
501  // overwriteWalker.Properties(W.reptile->TransProb[backward])=W.Properties(W.reptile->TransProb[backward]);
502  overwriteWalker.resetProperty(logpsi, Psi.getPhase(), eloc);
503  overwriteWalker.Properties(WP::R2ACCEPTED) = r2accept;
504  overwriteWalker.Properties(WP::R2PROPOSED) = r2proposed;
505 
506  // lastbead.Properties(R2PROPOSED)=lastbead.Properties(R2ACCEPTED)=nextlastbead.Properties(R2PROPOSED);
507  H.auxHevaluate(W, overwriteWalker, true, false); //evaluate properties but not collectables.
508  H.saveProperty(overwriteWalker.getPropertyBase());
509  overwriteWalker.Age = 0;
510 
511  ++nAccept;
512  }
513  else
514  {
515  // app_log()<<"Reject\n";
516  curhead.Properties(WP::R2ACCEPTED) = 0;
517  curhead.Properties(WP::R2PROPOSED) = r2proposed;
518  lastbead.Properties(WP::R2ACCEPTED) = 0;
519  //lastbead.Properties(R2PROPOSED)=nextlastbead.Properties(R2PROPOSED);
520  //curhead.Properties(R2
521  ++nReject;
522  H.rejectedMove(W, curhead);
523  curhead.Age += 1;
524  W.reptile->flip();
525  // app_log()<<"Reject\n";
526  return;
527  }
528  W.loadWalker(centerbead, true);
529  W.update(false); //skip S(k) evaluation? False
530  H.auxHevaluate(W, centerbead, false, true); //collectables, but not properties
531 }
RealType evaluateLog(ParticleSet &P)
evalaute the log (internally gradients and laplacian) of the trial wavefunction.
const BranchEngineType * branchEngine
branch engine, stateless reference to the one in QMCDriver
ParticleSet::ParticlePos drift
temporary storage for drift
RealType m_tauovermass
tau/mass
PropertyContainer_t Properties
properties of the current walker
Definition: ParticleSet.h:119
Walker_t & getTail()
Definition: Reptile.h:98
TrialWaveFunction & Psi
trial function
typename p_traits::ParticlePos ParticlePos
array of particles
Definition: Walker.h:64
std::ostream & app_log()
Definition: OutputManager.h:65
void saveProperty(IT first)
save the values of Hamiltonian elements to the Properties
bool phaseChanged(RealType psi0) const
RealType DMCLinkAction(RealType enew, RealType eold) const
MCWalkerConfiguration::Walker_t Walker_t
Definition: QMCUpdateBase.h:44
Walker_t & getNewHead()
Definition: Reptile.h:128
void assignDrift(T s, const ParticleAttrib< TinyVector< TG, D >> &ga, ParticleAttrib< TinyVector< T, D >> &da)
RealType m_sqrttau
Time-step factor .
void update(bool skipSK=false)
update the internal data
RealType symLinkAction(RealType logGf, RealType logGb, RealType enew, RealType eold) const
Walker_t & getCenter()
Definition: Reptile.h:100
ParticleSet::ParticlePos deltaR
temporary storage for random displacement
T Dot(const ParticleAttrib< TinyVector< T, D >> &pa, const ParticleAttrib< TinyVector< T, D >> &pb)
T min(T a, T b)
std::vector< IndexType > TransProb
Definition: Reptile.h:48
std::vector< IndexType > Action
Definition: Reptile.h:47
ParticleGradient G
gradients of the particles
Definition: ParticleSet.h:83
void saveWalker(Walker_t &awalker)
save this to awalker
ParticlePos R
Position.
Definition: ParticleSet.h:79
MakeReturn< UnaryNode< FnExp, typename CreateLeaf< Vector< T1, C1 > >::Leaf_t > >::Expression_t exp(const Vector< T1, C1 > &l)
Walker_t & getNext()
Definition: Reptile.h:99
MCWalkerConfiguration & W
walker ensemble
OHMMS_INDEXTYPE IndexType
define other types
Definition: Configuration.h:65
void loadWalker(Walker_t &awalker, bool pbyp)
load a Walker_t to the current ParticleSet
WalkerConfigurations::Walker_t Walker_t
void auxHevaluate(ParticleSet &P)
IndexType MaxAge
MaxAge>0 indicates branch is done.
Definition: QMCUpdateBase.h:61
QMCTraits::RealType RealType
void rejectedMove(ParticleSet &P, Walker_t &ThisWalker)
Looks like a hack see DMCBatched.cpp and DMC.cpp weight is used like temporary flag from DMC...
RandomBase< FullPrecRealType > & RandomGen
random number generator
FullPrecRealType evaluate(ParticleSet &P)
evaluate Local Energy
Walker_t & getHead()
Definition: Reptile.h:97
bool makeMoveAllParticlesWithDrift(const Walker_t &awalker, const ParticlePos &drift, const ParticlePos &deltaR, RealType dt)
move all the particles including the drift
QTFull::RealType FullPrecRealType
Definition: Configuration.h:66
IndexType nAccept
counter for number of moves accepted
Definition: QMCUpdateBase.h:63
RealType m_oneover2tau
Time-step factor .
IndexType nReject
counter for number of moves rejected
Definition: QMCUpdateBase.h:65
void saveTransProb(Walker_t &walker, IndexType d, RealType val, IndexType nPsi=0)
Definition: Reptile.h:162
FullPrecRealType *restrict getPropertyBase()
return the address of the values of Hamiltonian terms
Definition: ParticleSet.h:470
QMCHamiltonian & H
Hamiltonian.
void setScaledDrift(T tau, const ParticleAttrib< TinyVector< TG, D >> &qf, ParticleAttrib< TinyVector< T, D >> &drift)
da = scaled(tau)*ga
RealType getTransProb(Walker_t &walker, IndexType d, RealType nPsi=0)
Definition: Reptile.h:175
IndexType direction
Definition: Reptile.h:59
void makeGaussRandomWithEngine(ParticleAttrib< TinyVector< T, D >> &a, RG &rng)

◆ advanceWalkersVMC()

void advanceWalkersVMC ( )

Like DMC, this filters the local energy to ignore divergences near pathological points in phase space.

Definition at line 104 of file RMCUpdateAll.cpp.

References Reptile::Action, RMCUpdateAllWithDrift::Action, RMCUpdateAllWithDrift::actionType, qmcplusplus::assignDrift(), QMCHamiltonian::auxHevaluate(), QMCUpdateBase::branchEngine, QMCUpdateBase::deltaR, Reptile::direction, SimpleFixedNodeBranch::DMCLinkAction(), qmcplusplus::Dot(), QMCUpdateBase::drift, QMCHamiltonian::evaluate(), TrialWaveFunction::evaluateLog(), qmcplusplus::exp(), ParticleSet::G, Reptile::getHead(), Reptile::getNewHead(), Reptile::getNext(), TrialWaveFunction::getPhase(), TrialWaveFunction::getPhaseDiff(), ParticleSet::getPropertyBase(), Reptile::getTail(), Reptile::getTransProb(), QMCUpdateBase::H, ParticleSet::loadWalker(), QMCUpdateBase::m_oneover2tau, QMCUpdateBase::m_sqrttau, QMCUpdateBase::m_tauovermass, qmcplusplus::makeGaussRandomWithEngine(), ParticleSet::makeMoveAllParticlesWithDrift(), QMCUpdateBase::nAccept, QMCUpdateBase::nReject, SimpleFixedNodeBranch::phaseChanged(), ParticleSet::Properties, Walker< t_traits, p_traits >::Properties, QMCUpdateBase::Psi, ParticleSet::R, Walker< t_traits, p_traits >::R, QMCUpdateBase::RandomGen, QMCHamiltonian::rejectedMove(), MCWalkerConfiguration::reptile, Reptile::saveAction(), QMCHamiltonian::saveProperty(), Reptile::saveTransProb(), ParticleSet::saveWalker(), RMCUpdateAllWithDrift::scaleDrift, qmcplusplus::setScaledDrift(), qmcplusplus::setScaledDriftPbyPandNodeCorr(), RMCUpdateAllWithDrift::SYM_ACTION, SimpleFixedNodeBranch::symLinkAction(), QMCUpdateBase::Tau, Reptile::TransProb, and QMCUpdateBase::W.

Referenced by RMCUpdateAllWithDrift::advanceWalkers(), and RMCUpdateAllWithDrift::initWalkers().

105 {
106  IndexType direction = W.reptile->direction;
107  IndexType forward = (1 - direction) / 2;
108  IndexType backward = (1 + direction) / 2;
109  Walker_t& curhead = W.reptile->getHead();
110  W.loadWalker(curhead, false);
111  if (scaleDrift == true)
113  else
114  assignDrift(m_tauovermass, curhead.G, drift);
115  //app_log()<<"Sign head = "<<curhead.Properties(SIGN)<< std::endl;
116  //app_log()<<"Old phase = "<<Psi.getPhase()<< std::endl;
118  RealType r2proposed = Dot(deltaR, deltaR);
119  // W.reptile->r2prop += r2proposed;
120  // W.reptile->r2samp++;
122  {
123  ++nReject;
124  H.rejectedMove(W, curhead);
125  // curhead.Age+=1;
126  //W.reptile->flip();
127  return;
128  }
129 
130  RealType logpsi(Psi.evaluateLog(W));
131  RealType logGf = -0.5 * Dot(deltaR, deltaR);
132  RealType Action_forward = -0.5 * logGf;
133  curhead.Properties(W.reptile->TransProb[forward]) = -0.5 * Dot(deltaR, deltaR);
134  curhead.Properties(W.reptile->Action[forward]) = 0.5 * 0.5 * Dot(deltaR, deltaR);
135 
136  W.reptile->saveTransProb(curhead, +1, logGf);
137  W.reptile->saveAction(curhead, +1, Action_forward);
138 
139  Walker_t::ParticlePos fromdeltaR(deltaR);
140 
141 
142  if (scaleDrift == true)
144  else
146  fromdeltaR = curhead.R - W.R - drift;
147  FullPrecRealType* restrict new_headProp(W.getPropertyBase());
148 
149  RealType logGb = -m_oneover2tau * Dot(fromdeltaR, fromdeltaR);
150 
151  W.reptile->saveTransProb(W, -1, logGb);
152  //W.reptile->saveAction(W,-1,Action_backward);
153 
154  W.Properties(W.reptile->TransProb[backward]) = -m_oneover2tau * Dot(fromdeltaR, fromdeltaR);
155  W.Properties(W.reptile->Action[backward]) = 0.5 * m_oneover2tau * Dot(fromdeltaR, fromdeltaR);
156 
157  Walker_t &lastbead(W.reptile->getTail()), nextlastbead(W.reptile->getNext());
158  //Implementing the fixed-node approximation. If phase difference is not a multiple of 2pi, bounce away from node.
159  RealType newphase = Psi.getPhase();
160  RealType phasediff = newphase - curhead.Properties(WP::SIGN);
161  //Reject & bounce if node crossed.
163  {
164  ++nReject;
165  H.rejectedMove(W, curhead);
166  // curhead.Age+=1;
167  // W.reptile->flip();
168  //app_log()<<"hit a node. Bouncing...\n";
169  return;
170  }
171  RealType eloc = H.evaluate(W);
172  new_headProp[Action[2]] = 0.5 * Tau * eloc;
173 
174  ////////////////////////////////////////////////////////////////////////
175  /// Like DMC, this filters the local energy to ignore divergences near pathological points in phase space.
176  ////////////////////////////////////////////////////////////////////////
177  // RealType eest = W.reptile->eest;
178 
179  // RealType fbet = std::max(eest - curhead.Properties(WP::LOCALENERGY), eest - eloc);
180  // app_log()<<"eval = "<<eest<<" estdev="<<stddev<< std::endl;
181  // RealType rawcutoff=100*std::sqrt(W.reptile->evar);
182  // RealType cutoffmax = 1.5*rawcutoff;
183  // RealType cutoff=1;
184  // if (fbet > rawcutoff)
185  // cutoff = 1-(fbet - rawcutoff)/(rawcutoff*0.5);
186  // if( fbet > cutoffmax )
187  // cutoff=0;
188  //////////////////////////////////////////////////////////////////////////
189  // RealType tauscale = W.reptile->tauscale;
190  // W.Properties(W.reptile->Action[2])= 0.5*Tau*eloc*cutoff*tauscale;
191  RealType acceptProb = 1;
192  if (actionType == SYM_ACTION)
193  {
194  RealType oldhead_logpsi = curhead.Properties(WP::LOGPSI);
195  RealType oldtail_logpsi = lastbead.Properties(WP::LOGPSI);
196  RealType newtail_logpsi = nextlastbead.Properties(WP::LOGPSI);
197 
198  RealType oldhead_e = curhead.Properties(WP::LOCALENERGY);
199  RealType oldtail_e = lastbead.Properties(WP::LOCALENERGY);
200  RealType newhead_e = W.Properties(WP::LOCALENERGY);
201  RealType newtail_e = nextlastbead.Properties(WP::LOCALENERGY);
202 
203  RealType head_forward = W.reptile->getTransProb(curhead, +1);
204  RealType head_backward = W.reptile->getTransProb(W, -1);
205  RealType tail_forward = W.reptile->getTransProb(lastbead, +1);
206  RealType tail_backward = W.reptile->getTransProb(nextlastbead, -1);
207 
208  RealType dS_head = branchEngine->symLinkAction(head_forward, head_backward, newhead_e, oldhead_e);
209  RealType dS_tail = branchEngine->symLinkAction(tail_forward, tail_backward, newtail_e, oldtail_e);
210 
211  // dS=dS_head-dS_tail;
212 
213  // RealType dS_old = +(curhead.Properties(LOGPSI) + lastbead.Properties(LOGPSI) - logpsi - nextlastbead.Properties(LOGPSI))
214  // + curhead.Properties(W.reptile->Action[2]) + W.Properties(W.reptile->Action[2])
215  // + curhead.Properties(W.reptile->Action[forward]) + W.Properties(W.reptile->Action[backward])
216  // - (lastbead.Properties(W.reptile->Action[2]) + nextlastbead.Properties(W.reptile->Action[2]))
217  // - (lastbead.Properties(W.reptile->Action[forward]) + nextlastbead.Properties(W.reptile->Action[backward]));
218  // acceptProb=std::exp(-dS_old + (nextlastbead.Properties(W.reptile->TransProb[backward]) - curhead.Properties(W.reptile->TransProb[forward])));
219  // acceptProb=std::min(1.0,std::exp(-dS + -(curhead.Properties(LOGPSI) + lastbead.Properties(LOGPSI) - logpsi - nextlastbead.Properties(LOGPSI)) + tail_backward - head_forward));
220  }
221  else
222  {
223  // dS = curhead.Properties(W.reptile->Action[2]) + W.Properties(W.reptile->Action[2])
224  //- (lastbead.Properties(W.reptile->Action[2]) + nextlastbead.Properties(W.reptile->Action[2]));
225  RealType dS_head = branchEngine->DMCLinkAction(eloc, curhead.Properties(WP::LOCALENERGY));
226  RealType dS_tail =
227  branchEngine->DMCLinkAction(lastbead.Properties(WP::LOCALENERGY), nextlastbead.Properties(WP::LOCALENERGY));
228  //dS=branchEngine->DMCLinkAction(eloc,curhead.Properties(LOCALENERGY)) - branchEngine->DMCLinkAction(lastbead.Properties(LOCALENERGY),nextlastbead.Properties(LOCALENERGY));
229  // dS=dS_head - dS_tail;
230  // acceptProb=std::min(1.0,std::exp(-dS ));
231  }
232  acceptProb = std::exp(logGb - logGf + 2.0 * (logpsi - curhead.Properties(WP::LOGPSI)));
233 
234 
235  /* RealType dS = curhead.Properties(W.reptile->Action[2]) + W.Properties(W.reptile->Action[2])
236  - (lastbead.Properties(W.reptile->Action[2]) + nextlastbead.Properties(W.reptile->Action[2]));
237  RealType acceptProb=std::min(1.0,std::exp(-dS )); */
238  if (RandomGen() < acceptProb)
239  {
240  //Assuming the VMC step is fine, we are forcing the move.
242 
243  W.saveWalker(overwriteWalker);
244  overwriteWalker.Properties(WP::LOCALENERGY) = eloc;
245  overwriteWalker.Properties(W.reptile->Action[forward]) = 0;
246  overwriteWalker.Properties(W.reptile->Action[backward]) = W.Properties(W.reptile->Action[backward]);
247  overwriteWalker.Properties(W.reptile->Action[2]) = W.Properties(W.reptile->Action[2]);
248  overwriteWalker.Properties(W.reptile->TransProb[forward]) = W.Properties(W.reptile->TransProb[forward]);
249  overwriteWalker.Properties(W.reptile->TransProb[backward]) = W.Properties(W.reptile->TransProb[backward]);
250  overwriteWalker.resetProperty(logpsi, Psi.getPhase(), eloc);
251  H.auxHevaluate(W, overwriteWalker, true, false); //properties but not collectables.
252  H.saveProperty(overwriteWalker.getPropertyBase());
253  overwriteWalker.Age = 0;
254  ++nAccept;
255  }
256  else
257  {
258  ++nReject;
259  H.rejectedMove(W, curhead);
260  // curhead.Age+=1;
261  // W.reptile->flip();
262  return;
263  }
264 }
RealType evaluateLog(ParticleSet &P)
evalaute the log (internally gradients and laplacian) of the trial wavefunction.
const BranchEngineType * branchEngine
branch engine, stateless reference to the one in QMCDriver
ParticleSet::ParticlePos drift
temporary storage for drift
RealType m_tauovermass
tau/mass
PropertyContainer_t Properties
properties of the current walker
Definition: ParticleSet.h:119
Walker_t & getTail()
Definition: Reptile.h:98
TrialWaveFunction & Psi
trial function
typename p_traits::ParticlePos ParticlePos
array of particles
Definition: Walker.h:64
void saveProperty(IT first)
save the values of Hamiltonian elements to the Properties
bool phaseChanged(RealType psi0) const
RealType DMCLinkAction(RealType enew, RealType eold) const
MCWalkerConfiguration::Walker_t Walker_t
Definition: QMCUpdateBase.h:44
Walker_t & getNewHead()
Definition: Reptile.h:128
void assignDrift(T s, const ParticleAttrib< TinyVector< TG, D >> &ga, ParticleAttrib< TinyVector< T, D >> &da)
RealType m_sqrttau
Time-step factor .
RealType symLinkAction(RealType logGf, RealType logGb, RealType enew, RealType eold) const
ParticleSet::ParticlePos deltaR
temporary storage for random displacement
T Dot(const ParticleAttrib< TinyVector< T, D >> &pa, const ParticleAttrib< TinyVector< T, D >> &pb)
std::vector< IndexType > TransProb
Definition: Reptile.h:48
T setScaledDriftPbyPandNodeCorr(T tau, const ParticleAttrib< TinyVector< T1, D >> &qf, ParticleAttrib< TinyVector< T, D >> &drift)
scale drift
std::vector< IndexType > Action
Definition: Reptile.h:47
ParticleGradient G
gradients of the particles
Definition: ParticleSet.h:83
void saveWalker(Walker_t &awalker)
save this to awalker
RealType Tau
timestep
Definition: QMCUpdateBase.h:73
ParticlePos R
Position.
Definition: ParticleSet.h:79
MakeReturn< UnaryNode< FnExp, typename CreateLeaf< Vector< T1, C1 > >::Leaf_t > >::Expression_t exp(const Vector< T1, C1 > &l)
Walker_t & getNext()
Definition: Reptile.h:99
MCWalkerConfiguration & W
walker ensemble
OHMMS_INDEXTYPE IndexType
define other types
Definition: Configuration.h:65
void loadWalker(Walker_t &awalker, bool pbyp)
load a Walker_t to the current ParticleSet
WalkerConfigurations::Walker_t Walker_t
void auxHevaluate(ParticleSet &P)
QMCTraits::RealType RealType
void rejectedMove(ParticleSet &P, Walker_t &ThisWalker)
Looks like a hack see DMCBatched.cpp and DMC.cpp weight is used like temporary flag from DMC...
RandomBase< FullPrecRealType > & RandomGen
random number generator
FullPrecRealType evaluate(ParticleSet &P)
evaluate Local Energy
Walker_t & getHead()
Definition: Reptile.h:97
bool makeMoveAllParticlesWithDrift(const Walker_t &awalker, const ParticlePos &drift, const ParticlePos &deltaR, RealType dt)
move all the particles including the drift
QTFull::RealType FullPrecRealType
Definition: Configuration.h:66
void saveAction(Walker_t &walker, IndexType d, RealType val, IndexType nPsi=0)
Definition: Reptile.h:135
IndexType nAccept
counter for number of moves accepted
Definition: QMCUpdateBase.h:63
RealType m_oneover2tau
Time-step factor .
IndexType nReject
counter for number of moves rejected
Definition: QMCUpdateBase.h:65
void saveTransProb(Walker_t &walker, IndexType d, RealType val, IndexType nPsi=0)
Definition: Reptile.h:162
FullPrecRealType *restrict getPropertyBase()
return the address of the values of Hamiltonian terms
Definition: ParticleSet.h:470
QMCHamiltonian & H
Hamiltonian.
void setScaledDrift(T tau, const ParticleAttrib< TinyVector< TG, D >> &qf, ParticleAttrib< TinyVector< T, D >> &drift)
da = scaled(tau)*ga
RealType getTransProb(Walker_t &walker, IndexType d, RealType nPsi=0)
Definition: Reptile.h:175
IndexType direction
Definition: Reptile.h:59
void makeGaussRandomWithEngine(ParticleAttrib< TinyVector< T, D >> &a, RG &rng)

◆ checkReptile()

void checkReptile ( WalkerIter_t  it,
WalkerIter_t  it_end 
)

◆ initWalkers()

void initWalkers ( WalkerIter_t  it,
WalkerIter_t  it_end 
)
overridevirtual

initialize Walker for walker update

Reimplemented from QMCUpdateBase.

Definition at line 267 of file RMCUpdateAll.cpp.

References RMCUpdateAllWithDrift::advanceWalkersVMC(), QMCHamiltonian::auxHevaluate(), QMCUpdateBase::drift, QMCHamiltonian::evaluate(), TrialWaveFunction::evaluateLog(), ParticleSet::G, TrialWaveFunction::getPhase(), QMCUpdateBase::H, ParticleSet::L, QMCUpdateBase::MassInvP, qmcplusplus::n, Reptile::nbeads, QMCUpdateBase::Psi, ParticleSet::R, MCWalkerConfiguration::reptile, QMCHamiltonian::saveProperty(), qmcplusplus::setScaledDriftPbyPandNodeCorr(), QMCUpdateBase::Tau, ParticleSet::update(), RMCUpdateAllWithDrift::vmcSteps, and QMCUpdateBase::W.

268 {
269  IndexType initsteps = W.reptile->nbeads * 2;
270  vmcSteps = W.reptile->nbeads + 1;
271 
272  for (; it != it_end; ++it)
273  {
274  W.R = (*it)->R;
275  W.update();
276  RealType logpsi(Psi.evaluateLog(W));
277  (*it)->G = W.G;
278  (*it)->L = W.L;
280  RealType ene = H.evaluate(W);
281  H.auxHevaluate(W);
282  (*it)->resetProperty(logpsi, Psi.getPhase(), ene, 0.0, 0.0, nodecorr);
283  (*it)->Weight = 1;
284  H.saveProperty((*it)->getPropertyBase());
285  }
286 
287 
288  for (int n = 0; n < initsteps; n++)
290 }
RealType evaluateLog(ParticleSet &P)
evalaute the log (internally gradients and laplacian) of the trial wavefunction.
ParticleSet::ParticlePos drift
temporary storage for drift
TrialWaveFunction & Psi
trial function
void saveProperty(IT first)
save the values of Hamiltonian elements to the Properties
void update(bool skipSK=false)
update the internal data
ParticleLaplacian L
laplacians of the particles
Definition: ParticleSet.h:85
T setScaledDriftPbyPandNodeCorr(T tau, const ParticleAttrib< TinyVector< T1, D >> &qf, ParticleAttrib< TinyVector< T, D >> &drift)
scale drift
ParticleGradient G
gradients of the particles
Definition: ParticleSet.h:83
RealType Tau
timestep
Definition: QMCUpdateBase.h:73
ParticlePos R
Position.
Definition: ParticleSet.h:79
MCWalkerConfiguration & W
walker ensemble
std::vector< RealType > MassInvP
1/Mass per particle
OHMMS_INDEXTYPE IndexType
define other types
Definition: Configuration.h:65
void auxHevaluate(ParticleSet &P)
QMCTraits::RealType RealType
FullPrecRealType evaluate(ParticleSet &P)
evaluate Local Energy
IndexType nbeads
Definition: Reptile.h:59
QMCHamiltonian & H
Hamiltonian.

◆ operator=()

RMCUpdateAllWithDrift& operator= ( const RMCUpdateAllWithDrift )
privatedelete

Copy operator (disabled).

◆ put()

bool put ( xmlNodePtr  cur)
overridevirtual

process options

Reimplemented from QMCUpdateBase.

Definition at line 58 of file RMCUpdateAll.cpp.

References RMCUpdateAllWithDrift::actionType, ParameterSet::add(), qmcplusplus::app_log(), RMCUpdateAllWithDrift::DMC_ACTION, RMCUpdateAllWithDrift::equilSteps, omp_get_thread_num(), ParameterSet::put(), QMCUpdateBase::put(), and RMCUpdateAllWithDrift::scaleDrift.

59 {
60  QMCUpdateBase::put(cur);
61  ParameterSet m_param;
62  // bool usedrift=false;
63  std::string action = "SLA";
64  std::string usedrift = "no";
65  m_param.add(usedrift, "useScaledDrift");
66  m_param.add(action, "Action");
67  m_param.add(equilSteps, "equilsteps");
68  m_param.add(equilSteps, "equilSteps");
69 
70  // m_param.add(scaleDrift,"scaleDrift");
71  m_param.put(cur);
72 
73  bool driftoption = (usedrift == "yes" || usedrift == "Yes" || usedrift == "True" || usedrift == "true");
74 
75  if (driftoption)
76  {
77  scaleDrift = true;
78  if (omp_get_thread_num() == 0)
79  app_log() << " Using Umrigar scaled drift\n";
80  // H.rejectedMove(W,thisWalker);
81  }
82  else
83  {
84  if (omp_get_thread_num() == 0)
85  app_log() << " Using non-scaled drift\n";
86  }
87 
88  if (action == "DMC")
89  {
91  if (omp_get_thread_num() == 0)
92  app_log() << " Using DMC link-action\n";
93  }
94  else
95  {
96  if (omp_get_thread_num() == 0)
97  app_log() << " Using Symmetrized Link-Action\n";
98  }
99 
100  return true;
101 }
std::ostream & app_log()
Definition: OutputManager.h:65
virtual bool put(xmlNodePtr cur)
process options
bool put(std::istream &is) override
read from std::istream
Definition: ParameterSet.h:42
omp_int_t omp_get_thread_num()
Definition: OpenMP.h:25
class to handle a set of parameters
Definition: ParameterSet.h:27
void add(PDT &aparam, const std::string &aname_in, std::vector< PDT > candidate_values={}, TagStatus status=TagStatus::OPTIONAL)
add a new parameter corresponding to an xmlNode <parameter>

Member Data Documentation

◆ Action

std::vector<int> Action
private

Definition at line 58 of file RMCUpdateAll.h.

Referenced by RMCUpdateAllWithDrift::advanceWalkersVMC().

◆ actionType

◆ equilSteps

◆ equilToDoSteps

◆ scaleDrift

◆ TransProb

std::vector<int> TransProb
private

Definition at line 58 of file RMCUpdateAll.h.

◆ vmcSteps

◆ vmcToDoSteps

◆ qmcplusplus::RMCUpdatePbyPWithDrift

class qmcplusplus::RMCUpdatePbyPWithDrift


Implements the RMC algorithm using all electron moves

Definition at line 24 of file RMCUpdatePbyP.h.

+ Inheritance diagram for RMCUpdatePbyPWithDrift:
+ Collaboration diagram for RMCUpdatePbyPWithDrift:

Public Types

enum  { SYM_ACTION, DMC_ACTION }
 
- Public Types inherited from QMCUpdateBase
using Walker_t = MCWalkerConfiguration::Walker_t
 
using WalkerIter_t = MCWalkerConfiguration::iterator
 
using BranchEngineType = SimpleFixedNodeBranch
 
using mPosType = PosType
 
using mTensorType = TensorType
 
- Public Types inherited from QMCTraits
enum  { DIM = OHMMS_DIM, DIM_VGL = OHMMS_DIM + 2 }
 
using QTBase = QMCTypes< OHMMS_PRECISION, DIM >
 
using QTFull = QMCTypes< OHMMS_PRECISION_FULL, DIM >
 
using RealType = QTBase::RealType
 
using ComplexType = QTBase::ComplexType
 
using ValueType = QTBase::ValueType
 
using PosType = QTBase::PosType
 
using GradType = QTBase::GradType
 
using TensorType = QTBase::TensorType
 
using IndexType = OHMMS_INDEXTYPE
 define other types More...
 
using FullPrecRealType = QTFull::RealType
 
using FullPrecValueType = QTFull::ValueType
 
using PropertySetType = RecordNamedProperty< FullPrecRealType >
 define PropertyList_t More...
 
using PtclGrpIndexes = std::vector< std::pair< int, int > >
 

Public Member Functions

 RMCUpdatePbyPWithDrift (MCWalkerConfiguration &w, TrialWaveFunction &psi, QMCHamiltonian &h, RandomBase< FullPrecRealType > &rg, std::vector< int > act, std::vector< int > tp)
 Constructor. More...
 
 ~RMCUpdatePbyPWithDrift () override
 
void advanceWalkersVMC ()
 
void advanceWalkersRMC ()
 
void advanceWalker (Walker_t &thisWalker, bool recompute) override
 move a walker More...
 
void advanceWalkers (WalkerIter_t it, WalkerIter_t it_end, bool measure) override
 advance walkers executed at each step More...
 
void initWalkersForPbyP (WalkerIter_t it, WalkerIter_t it_end) override
 initialize Walker buffers for PbyP update More...
 
void initWalkers (WalkerIter_t it, WalkerIter_t it_end) override
 initialize Walker for walker update More...
 
void accumulate (WalkerIter_t it, WalkerIter_t it_end)
 
bool put (xmlNodePtr cur) override
 process options More...
 
- Public Member Functions inherited from QMCUpdateBase
 QMCUpdateBase (MCWalkerConfiguration &w, TrialWaveFunction &psi, QMCHamiltonian &h, RandomBase< FullPrecRealType > &rg)
 Constructor. More...
 
 QMCUpdateBase (MCWalkerConfiguration &w, TrialWaveFunction &psi, TrialWaveFunction &guide, QMCHamiltonian &h, RandomBase< FullPrecRealType > &rg)
 Alt Constructor. More...
 
virtual ~QMCUpdateBase ()
 destructor More...
 
RealType acceptRatio () const
 
void resetRun (BranchEngineType *brancher, EstimatorManagerBase *est, TraceManager *traces, const DriftModifierBase *driftmodifer)
 reset the QMCUpdateBase parameters More...
 
void resetRun2 (BranchEngineType *brancher, EstimatorManagerBase *est, TraceManager *traces, WalkerLogCollector *wlog_collector_, const DriftModifierBase *driftmodifer)
 
RealType getTau ()
 
void setTau (RealType t)
 
RealType getSpinMass ()
 
void setSpinMass (RealType m)
 
void getLogs (std::vector< RealType > &logs)
 
void set_step (int step)
 
void startRun (int blocks, bool record)
 start a run More...
 
void stopRun ()
 stop a run More...
 
void stopRun2 ()
 
void startBlock (int steps)
 prepare to start a block More...
 
void stopBlock (bool collectall=true)
 stop a block More...
 
void setMultiplicity (WalkerIter_t it, WalkerIter_t it_end)
 set the multiplicity of the walkers to branch More...
 
void setMultiplicity (Walker_t &awalker) const
 
void accumulate (WalkerIter_t it, WalkerIter_t it_end)
 
virtual RealType advanceWalkerForEE (Walker_t &w1, std::vector< PosType > &dR, std::vector< int > &iats, std::vector< int > &rs, std::vector< RealType > &ratios)
 
int RMC_checkIndex (int N, int NMax)
 
void RMC_checkWalkerBounds (WalkerIter_t &it, WalkerIter_t first, WalkerIter_t last)
 
RealType logBackwardGF (const ParticleSet::ParticlePos &displ)
 

Private Member Functions

 RMCUpdatePbyPWithDrift (const RMCUpdatePbyPWithDrift &)=delete
 Copy Constructor (disabled) More...
 
RMCUpdatePbyPWithDriftoperator= (const RMCUpdatePbyPWithDrift &)=delete
 Copy operator (disabled). More...
 

Private Attributes

std::vector< int > Action
 
std::vector< int > TransProb
 
bool scaleDrift
 
IndexType actionType
 
NewTimeradvance_timer_
 
NewTimermovepbyp_timer_
 
NewTimerupdate_mbo_timer_
 
NewTimerenergy_timer_
 
IndexType vmcSteps
 
IndexType equilSteps
 
IndexType vmcToDoSteps
 
IndexType equilToDoSteps
 

Additional Inherited Members

- Public Attributes inherited from QMCUpdateBase
int nSubSteps
 number of steps per measurement More...
 
DriverDebugChecks debug_checks_ = DriverDebugChecks::ALL_OFF
 determine additional checks for debugging purpose More...
 
std::string debug_checks_str_
 
IndexType MaxAge
 MaxAge>0 indicates branch is done. More...
 
IndexType nAccept
 counter for number of moves accepted More...
 
IndexType nReject
 counter for number of moves rejected More...
 
IndexType nAllRejected
 Total number of the steps when all the particle moves are rejected. More...
 
IndexType nNodeCrossing
 Total number of node crossings per block. More...
 
IndexType NonLocalMoveAccepted
 Total numer of non-local moves accepted. More...
 
RealType Tau
 timestep More...
 
RealType spinMass
 spin mass More...
 
bool UseDrift
 use Drift More...
 
RealType csoffset
 normalization offset for cs type runs. More...
 
TraceManagerTraces
 traces More...
 
WalkerLogCollectorwlog_collector
 
- Protected Member Functions inherited from QMCUpdateBase
RealType getNodeCorrection (const ParticleSet::ParticleGradient &g, ParticleSet::ParticlePos &gscaled)
 evaluate the ratio of scaled velocity and velocity More...
 
 QMCUpdateBase (const QMCUpdateBase &)=delete
 copy constructor (disabled) More...
 
- Static Protected Member Functions inherited from QMCUpdateBase
static void checkLogAndGL (ParticleSet &pset, TrialWaveFunction &twf, const std::string_view location)
 check logpsi and grad and lap against values computed from scratch More...
 
- Protected Attributes inherited from QMCUpdateBase
bool UpdatePbyP
 update particle-by-particle More...
 
IndexType NumPtcl
 number of particles More...
 
RealType m_oneover2tau
 Time-step factor $ 1/(2\tau)$. More...
 
RealType m_sqrttau
 Time-step factor $ \sqrt{\tau}$. More...
 
RealType m_tauovermass
 tau/mass More...
 
RealType m_r2max
 maximum displacement^2 More...
 
MCWalkerConfigurationW
 walker ensemble More...
 
TrialWaveFunctionPsi
 trial function More...
 
TrialWaveFunctionGuide
 guide function More...
 
QMCHamiltonianH
 Hamiltonian. More...
 
RandomBase< FullPrecRealType > & RandomGen
 random number generator More...
 
const BranchEngineTypebranchEngine
 branch engine, stateless reference to the one in QMCDriver More...
 
const DriftModifierBaseDriftModifier
 drift modifer, stateless reference to the one in QMCDriver More...
 
EstimatorManagerBaseEstimators
 estimator More...
 
ParameterSet myParams
 parameters More...
 
std::vector< RealTypeMassInvS
 1/Mass per species More...
 
std::vector< RealTypeMassInvP
 1/Mass per particle More...
 
std::vector< RealTypeSqrtTauOverMass
 sqrt(tau/Mass) per particle More...
 
ParticleSet::ParticlePos drift
 temporary storage for drift More...
 
ParticleSet::ParticlePos deltaR
 temporary storage for random displacement More...
 
ParticleSet::ParticleScalar deltaS
 temporart storage for spin displacement More...
 
ParticleSet::ParticleGradient G
 storage for differential gradients for PbyP update More...
 
ParticleSet::ParticleGradient dG
 
ParticleSet::ParticleLaplacian L
 storage for differential laplacians for PbyP update More...
 
ParticleSet::ParticleLaplacian dL
 

Member Enumeration Documentation

◆ anonymous enum

anonymous enum
Enumerator
SYM_ACTION 
DMC_ACTION 

Definition at line 36 of file RMCUpdatePbyP.h.

Constructor & Destructor Documentation

◆ RMCUpdatePbyPWithDrift() [1/2]

RMCUpdatePbyPWithDrift ( MCWalkerConfiguration w,
TrialWaveFunction psi,
QMCHamiltonian h,
RandomBase< FullPrecRealType > &  rg,
std::vector< int >  act,
std::vector< int >  tp 
)

Constructor.

Definition at line 40 of file RMCUpdatePbyP.cpp.

References RMCUpdatePbyPWithDrift::actionType, RMCUpdatePbyPWithDrift::scaleDrift, and RMCUpdatePbyPWithDrift::SYM_ACTION.

46  : QMCUpdateBase(w, psi, h, rg),
47  Action(act),
48  TransProb(tp),
49  advance_timer_(createGlobalTimer("RMCUpdatePbyP::advance", timer_level_medium)),
50  movepbyp_timer_(createGlobalTimer("RMCUpdatePbyP::movePbyP", timer_level_medium)),
51  update_mbo_timer_(createGlobalTimer("RMCUpdatePbyP::updateMBO", timer_level_medium)),
52  energy_timer_(createGlobalTimer("RMCUpdatePbyP::energy", timer_level_medium))
53 {
54  scaleDrift = false;
56 }
NewTimer & createGlobalTimer(const std::string &myname, timer_levels mylevel)
QMCUpdateBase(MCWalkerConfiguration &w, TrialWaveFunction &psi, QMCHamiltonian &h, RandomBase< FullPrecRealType > &rg)
Constructor.

◆ ~RMCUpdatePbyPWithDrift()

~RMCUpdatePbyPWithDrift ( )
override

Definition at line 58 of file RMCUpdatePbyP.cpp.

58 {}

◆ RMCUpdatePbyPWithDrift() [2/2]

RMCUpdatePbyPWithDrift ( const RMCUpdatePbyPWithDrift )
privatedelete

Copy Constructor (disabled)

Member Function Documentation

◆ accumulate()

void accumulate ( WalkerIter_t  it,
WalkerIter_t  it_end 
)

Definition at line 382 of file RMCUpdatePbyP.cpp.

References EstimatorManagerBase::accumulate(), QMCUpdateBase::Estimators, and QMCUpdateBase::W.

382 { Estimators->accumulate(W, it, it_end); }
void accumulate(MCWalkerConfiguration &W)
accumulate the measurements
EstimatorManagerBase * Estimators
estimator
MCWalkerConfiguration & W
walker ensemble

◆ advanceWalker()

void advanceWalker ( Walker_t thisWalker,
bool  recompute 
)
overridevirtual

move a walker

Implements QMCUpdateBase.

Definition at line 369 of file RMCUpdatePbyP.cpp.

370 {
371  //empty function to
372 }

◆ advanceWalkers()

void advanceWalkers ( WalkerIter_t  it,
WalkerIter_t  it_end,
bool  recompute 
)
overridevirtual

advance walkers executed at each step

Derived classes implement how to move walkers and accept/reject moves.

Reimplemented from QMCUpdateBase.

Definition at line 374 of file RMCUpdatePbyP.cpp.

References RMCUpdatePbyPWithDrift::advanceWalkersRMC(), and RMCUpdatePbyPWithDrift::advanceWalkersVMC().

375 {
376  if (init == true)
378  else
380 }

◆ advanceWalkersRMC()

void advanceWalkersRMC ( )

Definition at line 250 of file RMCUpdatePbyP.cpp.

References ParticleSet::accept_rejectMove(), TrialWaveFunction::acceptMove(), Walker< t_traits, p_traits >::Age, qmcplusplus::app_log(), QMCHamiltonian::auxHevaluate(), QMCUpdateBase::branchEngine, TrialWaveFunction::calcRatioGrad(), TrialWaveFunction::completeUpdates(), TrialWaveFunction::copyFromBuffer(), Walker< t_traits, p_traits >::DataSet, QMCUpdateBase::deltaR, SimpleFixedNodeBranch::DMCLinkAction(), ParticleSet::donePbyP(), qmcplusplus::dot(), QMCUpdateBase::DriftModifier, TrialWaveFunction::evalGrad(), QMCHamiltonian::evaluate(), qmcplusplus::exp(), ParticleSet::first(), Reptile::flip(), ParticleSet::getActivePos(), Reptile::getCenter(), DriftModifierBase::getDrift(), Reptile::getHead(), Reptile::getNewHead(), Reptile::getNext(), TrialWaveFunction::getPhaseDiff(), Walker< t_traits, p_traits >::getPropertyBase(), Reptile::getTail(), ParticleSet::groups(), QMCUpdateBase::H, ParticleSet::last(), ParticleSet::loadWalker(), QMCUpdateBase::m_r2max, qmcplusplus::makeGaussRandomWithEngine(), ParticleSet::makeMoveAndCheck(), QMCUpdateBase::MassInvS, QMCUpdateBase::MaxAge, omptarget::min(), RMCUpdatePbyPWithDrift::movepbyp_timer_, QMCUpdateBase::nAccept, QMCUpdateBase::nNodeCrossing, norm(), QMCUpdateBase::nReject, SimpleFixedNodeBranch::phaseChanged(), Walker< t_traits, p_traits >::Properties, QMCUpdateBase::Psi, ParticleSet::R, Walker< t_traits, p_traits >::R, QMCUpdateBase::RandomGen, QMCHamiltonian::rejectedMove(), TrialWaveFunction::rejectMove(), MCWalkerConfiguration::reptile, QMCHamiltonian::saveProperty(), ParticleSet::saveWalker(), qmcplusplus::sqrt(), TimerType< CLOCK >::start(), TimerType< CLOCK >::stop(), QMCUpdateBase::Tau, ParticleSet::update(), TrialWaveFunction::updateBuffer(), and QMCUpdateBase::W.

Referenced by RMCUpdatePbyPWithDrift::advanceWalkers().

251 {
252  Walker_t& curhead = W.reptile->getHead();
253  Walker_t prophead(curhead);
254  Walker_t::WFBuffer_t& w_buffer(prophead.DataSet);
255  W.loadWalker(prophead, true);
256  Psi.copyFromBuffer(W, w_buffer);
257 
259  int nAcceptTemp(0);
260  //copy the old energy and scale factor of drift
261  RealType eold(prophead.Properties(WP::LOCALENERGY));
262  RealType vqold(prophead.Properties(WP::DRIFTSCALE));
263  RealType rr_proposed = 0.0;
264  RealType rr_accepted = 0.0;
266  for (int ig = 0; ig < W.groups(); ++ig) //loop over species
267  {
268  RealType tauovermass = Tau * MassInvS[ig];
269  RealType oneover2tau = 0.5 / (tauovermass);
270  RealType sqrttau = std::sqrt(tauovermass);
271  for (int iat = W.first(ig); iat < W.last(ig); ++iat)
272  {
273  //get the displacement
274  GradType grad_iat = Psi.evalGrad(W, iat);
275  PosType dr;
276  DriftModifier->getDrift(tauovermass, grad_iat, dr);
277  dr += sqrttau * deltaR[iat];
278  bool is_valid = W.makeMoveAndCheck(iat, dr);
279  RealType rr = tauovermass * dot(deltaR[iat], deltaR[iat]);
280  rr_proposed += rr;
281  if (!is_valid || rr > m_r2max)
282  {
283  W.accept_rejectMove(iat, false);
284  continue;
285  }
286  ValueType ratio = Psi.calcRatioGrad(W, iat, grad_iat);
287  //node is crossed reject the move
289  {
290  ++nNodeCrossing;
291  W.accept_rejectMove(iat, false);
292  Psi.rejectMove(iat);
293  }
294  else
295  {
296  RealType logGf = -0.5 * dot(deltaR[iat], deltaR[iat]);
297  //Use the force of the particle iat
298  DriftModifier->getDrift(tauovermass, grad_iat, dr);
299  dr = W.R[iat] - W.getActivePos() - dr;
300  RealType logGb = -oneover2tau * dot(dr, dr);
301  RealType prob = std::norm(ratio) * std::exp(logGb - logGf);
302  bool is_accepted = false;
303  if (RandomGen() < prob)
304  {
305  is_accepted = true;
306  ++nAcceptTemp;
307  Psi.acceptMove(W, iat, true);
308  rr_accepted += rr;
309  }
310  else
311  {
312  Psi.rejectMove(iat);
313  }
314  W.accept_rejectMove(iat, is_accepted);
315  }
316  }
317  }
320  W.donePbyP();
321  // In the rare case that all proposed moves fail, we bounce.
322  if (nAcceptTemp == 0)
323  {
324  ++nReject;
325  H.rejectedMove(W, prophead);
326  curhead.Age += 1;
327  W.reptile->flip();
328  }
329  prophead.R = W.R;
330  RealType logpsi = Psi.updateBuffer(W, w_buffer, false);
331  W.saveWalker(prophead);
332  Walker_t &lastbead(W.reptile->getTail()), nextlastbead(W.reptile->getNext());
333  RealType eloc = H.evaluate(W);
334  RealType dS = branchEngine->DMCLinkAction(eloc, curhead.Properties(WP::LOCALENERGY)) -
335  branchEngine->DMCLinkAction(lastbead.Properties(WP::LOCALENERGY), nextlastbead.Properties(WP::LOCALENERGY));
336  RealType acceptProb = std::min((RealType)1.0, std::exp(-dS));
337  if ((RandomGen() <= acceptProb) || (prophead.Age >= MaxAge || lastbead.Age >= MaxAge))
338  {
340  if (curhead.Age >= MaxAge || lastbead.Age >= MaxAge)
341  app_log() << "\tForce Acceptance...\n";
342 
343  prophead.Properties(WP::LOCALENERGY) = eloc;
344  prophead.Properties(WP::R2ACCEPTED) = rr_accepted;
345  prophead.Properties(WP::R2PROPOSED) = rr_proposed;
346  H.auxHevaluate(W, prophead, true, false); //evaluate properties? true. collectables? false.
347  H.saveProperty(prophead.getPropertyBase());
348  prophead.Age = 0;
349  overwriteWalker = prophead;
350  ++nAccept;
351  }
352  else
353  {
354  ++nReject;
355  H.rejectedMove(W, prophead);
356  curhead.Properties(WP::R2ACCEPTED) = 0;
357  curhead.Properties(WP::R2PROPOSED) = rr_proposed;
358  curhead.Age += 1;
359  W.reptile->flip();
360  // return;
361  }
362  //Collectables should be evaluated on center bead. Here we go.
363  Walker_t& centerbead = W.reptile->getCenter();
364  W.loadWalker(centerbead, true);
365  W.update(); //Called to recompute S(k) and distance tables.
366  H.auxHevaluate(W, centerbead, false, true); //evaluate properties? false. Collectables? true.
367 }
const BranchEngineType * branchEngine
branch engine, stateless reference to the one in QMCDriver
void rejectMove(int iat)
restore to the original state
void copyFromBuffer(ParticleSet &P, WFBufferType &buf)
copy all the wavefunction components from buffer.
QTBase::GradType GradType
Definition: Configuration.h:62
Walker_t & getTail()
Definition: Reptile.h:98
TrialWaveFunction & Psi
trial function
void acceptMove(ParticleSet &P, int iat, bool safe_to_delay=false)
update the state with the new data
std::ostream & app_log()
Definition: OutputManager.h:65
void saveProperty(IT first)
save the values of Hamiltonian elements to the Properties
bool phaseChanged(RealType psi0) const
RealType DMCLinkAction(RealType enew, RealType eold) const
MCWalkerConfiguration::Walker_t Walker_t
Definition: QMCUpdateBase.h:44
Walker_t & getNewHead()
Definition: Reptile.h:128
int first(int igroup) const
return the first index of a group i
Definition: ParticleSet.h:514
void update(bool skipSK=false)
update the internal data
Walker_t & getCenter()
Definition: Reptile.h:100
ParticleSet::ParticlePos deltaR
temporary storage for random displacement
RealType updateBuffer(ParticleSet &P, WFBufferType &buf, bool fromscratch=false)
update all the wavefunction components in buffer.
T min(T a, T b)
IndexType nNodeCrossing
Total number of node crossings per block.
Definition: QMCUpdateBase.h:69
QMCTraits::PosType PosType
int groups() const
return the number of groups
Definition: ParticleSet.h:511
PooledMemory< FullPrecRealType > WFBuffer_t
Definition: Walker.h:80
const PosType & getActivePos() const
Definition: ParticleSet.h:261
double norm(const zVec &c)
Definition: VectorOps.h:118
QTBase::ValueType ValueType
Definition: Configuration.h:60
void saveWalker(Walker_t &awalker)
save this to awalker
RealType Tau
timestep
Definition: QMCUpdateBase.h:73
void accept_rejectMove(Index_t iat, bool accepted, bool forward_mode=true)
accept or reject a proposed move Two operation modes: The using and updating distance tables via Part...
ParticlePos R
Position.
Definition: ParticleSet.h:79
int last(int igroup) const
return the last index of a group i
Definition: ParticleSet.h:517
MakeReturn< UnaryNode< FnExp, typename CreateLeaf< Vector< T1, C1 > >::Leaf_t > >::Expression_t exp(const Vector< T1, C1 > &l)
Walker_t & getNext()
Definition: Reptile.h:99
MCWalkerConfiguration & W
walker ensemble
void loadWalker(Walker_t &awalker, bool pbyp)
load a Walker_t to the current ParticleSet
WalkerConfigurations::Walker_t Walker_t
void auxHevaluate(ParticleSet &P)
IndexType MaxAge
MaxAge>0 indicates branch is done.
Definition: QMCUpdateBase.h:61
MakeReturn< UnaryNode< FnSqrt, typename CreateLeaf< Vector< T1, C1 > >::Leaf_t > >::Expression_t sqrt(const Vector< T1, C1 > &l)
QMCTraits::RealType RealType
void rejectedMove(ParticleSet &P, Walker_t &ThisWalker)
Looks like a hack see DMCBatched.cpp and DMC.cpp weight is used like temporary flag from DMC...
RandomBase< FullPrecRealType > & RandomGen
random number generator
GradType evalGrad(ParticleSet &P, int iat)
FullPrecRealType evaluate(ParticleSet &P)
evaluate Local Energy
Walker_t & getHead()
Definition: Reptile.h:97
Tensor< typename BinaryReturn< T1, T2, OpMultiply >::Type_t, D > dot(const AntiSymTensor< T1, D > &lhs, const AntiSymTensor< T2, D > &rhs)
bool makeMoveAndCheck(Index_t iat, const SingleParticlePos &displ)
move the iat-th particle to active_pos_
IndexType nAccept
counter for number of moves accepted
Definition: QMCUpdateBase.h:63
IndexType nReject
counter for number of moves rejected
Definition: QMCUpdateBase.h:65
virtual void getDrift(RealType tau, const GradType &qf, PosType &drift) const =0
evaluate a drift with a real force
std::vector< RealType > MassInvS
1/Mass per species
QMCHamiltonian & H
Hamiltonian.
ValueType calcRatioGrad(ParticleSet &P, int iat, GradType &grad_iat)
compute psi(R_new) / psi(R_current) ratio and ln(psi(R_new)) gradients It returns a complex value if...
RealType m_r2max
maximum displacement^2
void donePbyP(bool skipSK=false)
update structure factor and unmark active_ptcl_
void completeUpdates()
complete all the delayed or asynchronous operations before leaving the p-by-p move region...
const DriftModifierBase * DriftModifier
drift modifer, stateless reference to the one in QMCDriver
void makeGaussRandomWithEngine(ParticleAttrib< TinyVector< T, D >> &a, RG &rng)

◆ advanceWalkersVMC()

void advanceWalkersVMC ( )

Definition at line 124 of file RMCUpdatePbyP.cpp.

References ParticleSet::accept_rejectMove(), TrialWaveFunction::acceptMove(), RMCUpdatePbyPWithDrift::advance_timer_, Walker< t_traits, p_traits >::Age, QMCHamiltonian::auxHevaluate(), QMCUpdateBase::branchEngine, TrialWaveFunction::calcRatioGrad(), TrialWaveFunction::completeUpdates(), TrialWaveFunction::copyFromBuffer(), Walker< t_traits, p_traits >::DataSet, QMCUpdateBase::deltaR, ParticleSet::donePbyP(), qmcplusplus::dot(), QMCUpdateBase::DriftModifier, RMCUpdatePbyPWithDrift::energy_timer_, TrialWaveFunction::evalGrad(), QMCHamiltonian::evaluate(), qmcplusplus::exp(), ParticleSet::first(), ParticleSet::getActivePos(), Reptile::getCenter(), DriftModifierBase::getDrift(), Reptile::getHead(), Reptile::getNewHead(), TrialWaveFunction::getPhase(), TrialWaveFunction::getPhaseDiff(), Walker< t_traits, p_traits >::getPropertyBase(), ParticleSet::groups(), QMCUpdateBase::H, ParticleSet::last(), ParticleSet::loadWalker(), QMCUpdateBase::m_r2max, qmcplusplus::makeGaussRandomWithEngine(), ParticleSet::makeMoveAndCheck(), QMCUpdateBase::MassInvS, RMCUpdatePbyPWithDrift::movepbyp_timer_, QMCUpdateBase::nAccept, QMCUpdateBase::nAllRejected, QMCUpdateBase::nNodeCrossing, norm(), QMCUpdateBase::nReject, SimpleFixedNodeBranch::phaseChanged(), Walker< t_traits, p_traits >::Properties, QMCUpdateBase::Psi, ParticleSet::R, Walker< t_traits, p_traits >::R, QMCUpdateBase::RandomGen, QMCHamiltonian::rejectedMove(), TrialWaveFunction::rejectMove(), MCWalkerConfiguration::reptile, Walker< t_traits, p_traits >::resetProperty(), QMCHamiltonian::saveProperty(), ParticleSet::saveWalker(), qmcplusplus::sqrt(), TimerType< CLOCK >::start(), TimerType< CLOCK >::stop(), QMCUpdateBase::Tau, ParticleSet::update(), RMCUpdatePbyPWithDrift::update_mbo_timer_, TrialWaveFunction::updateBuffer(), QMCUpdateBase::W, and Walker< t_traits, p_traits >::Weight.

Referenced by RMCUpdatePbyPWithDrift::advanceWalkers(), and RMCUpdatePbyPWithDrift::initWalkers().

125 {
127  Walker_t& curhead = W.reptile->getHead();
128  Walker_t prophead(curhead);
129  Walker_t::WFBuffer_t& w_buffer(prophead.DataSet);
130  W.loadWalker(prophead, true);
131  Psi.copyFromBuffer(W, w_buffer);
132  //create a 3N-Dimensional Gaussian with variance=1
134  int nAcceptTemp(0);
135  //copy the old energy and scale factor of drift
136  RealType eold(prophead.Properties(WP::LOCALENERGY));
137  RealType vqold(prophead.Properties(WP::DRIFTSCALE));
138  RealType enew(eold);
139  RealType rr_proposed = 0.0;
140  RealType rr_accepted = 0.0;
142  for (int ig = 0; ig < W.groups(); ++ig) //loop over species
143  {
144  RealType tauovermass = Tau * MassInvS[ig];
145  RealType oneover2tau = 0.5 / (tauovermass);
146  RealType sqrttau = std::sqrt(tauovermass);
147  for (int iat = W.first(ig); iat < W.last(ig); ++iat)
148  {
149  //get the displacement
150  GradType grad_iat = Psi.evalGrad(W, iat);
151  PosType dr;
152  DriftModifier->getDrift(tauovermass, grad_iat, dr);
153  dr += sqrttau * deltaR[iat];
154  bool is_valid = W.makeMoveAndCheck(iat, dr);
155  RealType rr = tauovermass * dot(deltaR[iat], deltaR[iat]);
156  rr_proposed += rr;
157  if (!is_valid || rr > m_r2max)
158  {
159  W.accept_rejectMove(iat, false);
160  continue;
161  }
162  ValueType ratio = Psi.calcRatioGrad(W, iat, grad_iat);
163  //node is crossed reject the move
165  {
166  ++nNodeCrossing;
167  W.accept_rejectMove(iat, false);
168  Psi.rejectMove(iat);
169  }
170  else
171  {
172  RealType logGf = -0.5 * dot(deltaR[iat], deltaR[iat]);
173  //Use the force of the particle iat
174  DriftModifier->getDrift(tauovermass, grad_iat, dr);
175  dr = W.R[iat] - W.getActivePos() - dr;
176  RealType logGb = -oneover2tau * dot(dr, dr);
177  RealType prob = std::norm(ratio) * std::exp(logGb - logGf);
178  bool is_accepted = false;
179  if (RandomGen() < prob)
180  {
181  is_accepted = true;
182  ++nAcceptTemp;
183  Psi.acceptMove(W, iat, true);
184  rr_accepted += rr;
185  }
186  else
187  {
188  Psi.rejectMove(iat);
189  }
190  W.accept_rejectMove(iat, is_accepted);
191  }
192  }
193  }
196  W.donePbyP();
197 
198  if (nAcceptTemp > 0)
199  {
200  //need to overwrite the walker properties
203  prophead.Age = 0;
204  prophead.R = W.R;
205  RealType logpsi = Psi.updateBuffer(W, w_buffer, false);
206  W.saveWalker(prophead);
209  enew = H.evaluate(W);
211  prophead.resetProperty(logpsi, Psi.getPhase(), enew, rr_accepted, rr_proposed, 0.0);
212  prophead.Weight = 1.0;
213  H.auxHevaluate(W, prophead, true, false); //evaluate properties but not collectables.
214  H.saveProperty(prophead.getPropertyBase());
215  newhead = prophead;
216  nAccept++;
217  }
218  else
219  {
220  //all moves are rejected: does not happen normally with reasonable wavefunctions
221  curhead.Age++;
222  curhead.Properties(WP::R2ACCEPTED) = 0.0;
223  //weight is set to 0 for traces
224  // consistent w/ no evaluate/auxHevaluate
225  RealType wtmp = prophead.Weight;
226  curhead.Weight = 0.0;
227  H.rejectedMove(W, curhead);
228  curhead.Weight = wtmp;
229  ++nAllRejected;
230  nReject++;
231  }
232  Walker_t& centerbead = W.reptile->getCenter();
233  W.loadWalker(centerbead, true);
234  W.update();
235  H.auxHevaluate(W, centerbead); //evaluate collectables but not properties.
236  // Traces->buffer_sample();
237 }
const BranchEngineType * branchEngine
branch engine, stateless reference to the one in QMCDriver
void rejectMove(int iat)
restore to the original state
void copyFromBuffer(ParticleSet &P, WFBufferType &buf)
copy all the wavefunction components from buffer.
QTBase::GradType GradType
Definition: Configuration.h:62
TrialWaveFunction & Psi
trial function
void acceptMove(ParticleSet &P, int iat, bool safe_to_delay=false)
update the state with the new data
void saveProperty(IT first)
save the values of Hamiltonian elements to the Properties
bool phaseChanged(RealType psi0) const
MCWalkerConfiguration::Walker_t Walker_t
Definition: QMCUpdateBase.h:44
Walker_t & getNewHead()
Definition: Reptile.h:128
int first(int igroup) const
return the first index of a group i
Definition: ParticleSet.h:514
void update(bool skipSK=false)
update the internal data
Walker_t & getCenter()
Definition: Reptile.h:100
ParticleSet::ParticlePos deltaR
temporary storage for random displacement
RealType updateBuffer(ParticleSet &P, WFBufferType &buf, bool fromscratch=false)
update all the wavefunction components in buffer.
IndexType nNodeCrossing
Total number of node crossings per block.
Definition: QMCUpdateBase.h:69
QMCTraits::PosType PosType
int groups() const
return the number of groups
Definition: ParticleSet.h:511
PooledMemory< FullPrecRealType > WFBuffer_t
Definition: Walker.h:80
const PosType & getActivePos() const
Definition: ParticleSet.h:261
double norm(const zVec &c)
Definition: VectorOps.h:118
QTBase::ValueType ValueType
Definition: Configuration.h:60
void saveWalker(Walker_t &awalker)
save this to awalker
RealType Tau
timestep
Definition: QMCUpdateBase.h:73
void accept_rejectMove(Index_t iat, bool accepted, bool forward_mode=true)
accept or reject a proposed move Two operation modes: The using and updating distance tables via Part...
ParticlePos R
Position.
Definition: ParticleSet.h:79
int last(int igroup) const
return the last index of a group i
Definition: ParticleSet.h:517
MakeReturn< UnaryNode< FnExp, typename CreateLeaf< Vector< T1, C1 > >::Leaf_t > >::Expression_t exp(const Vector< T1, C1 > &l)
MCWalkerConfiguration & W
walker ensemble
void loadWalker(Walker_t &awalker, bool pbyp)
load a Walker_t to the current ParticleSet
WalkerConfigurations::Walker_t Walker_t
void auxHevaluate(ParticleSet &P)
MakeReturn< UnaryNode< FnSqrt, typename CreateLeaf< Vector< T1, C1 > >::Leaf_t > >::Expression_t sqrt(const Vector< T1, C1 > &l)
QMCTraits::RealType RealType
void rejectedMove(ParticleSet &P, Walker_t &ThisWalker)
Looks like a hack see DMCBatched.cpp and DMC.cpp weight is used like temporary flag from DMC...
RandomBase< FullPrecRealType > & RandomGen
random number generator
GradType evalGrad(ParticleSet &P, int iat)
FullPrecRealType evaluate(ParticleSet &P)
evaluate Local Energy
Walker_t & getHead()
Definition: Reptile.h:97
Tensor< typename BinaryReturn< T1, T2, OpMultiply >::Type_t, D > dot(const AntiSymTensor< T1, D > &lhs, const AntiSymTensor< T2, D > &rhs)
bool makeMoveAndCheck(Index_t iat, const SingleParticlePos &displ)
move the iat-th particle to active_pos_
IndexType nAccept
counter for number of moves accepted
Definition: QMCUpdateBase.h:63
IndexType nReject
counter for number of moves rejected
Definition: QMCUpdateBase.h:65
virtual void getDrift(RealType tau, const GradType &qf, PosType &drift) const =0
evaluate a drift with a real force
std::vector< RealType > MassInvS
1/Mass per species
QMCHamiltonian & H
Hamiltonian.
ValueType calcRatioGrad(ParticleSet &P, int iat, GradType &grad_iat)
compute psi(R_new) / psi(R_current) ratio and ln(psi(R_new)) gradients It returns a complex value if...
RealType m_r2max
maximum displacement^2
void donePbyP(bool skipSK=false)
update structure factor and unmark active_ptcl_
void completeUpdates()
complete all the delayed or asynchronous operations before leaving the p-by-p move region...
IndexType nAllRejected
Total number of the steps when all the particle moves are rejected.
Definition: QMCUpdateBase.h:67
const DriftModifierBase * DriftModifier
drift modifer, stateless reference to the one in QMCDriver
void makeGaussRandomWithEngine(ParticleAttrib< TinyVector< T, D >> &a, RG &rng)

◆ initWalkers()

void initWalkers ( WalkerIter_t  it,
WalkerIter_t  it_end 
)
overridevirtual

initialize Walker for walker update

Reimplemented from QMCUpdateBase.

Definition at line 240 of file RMCUpdatePbyP.cpp.

References RMCUpdatePbyPWithDrift::advanceWalkersVMC(), qmcplusplus::n, Reptile::nbeads, MCWalkerConfiguration::reptile, RMCUpdatePbyPWithDrift::vmcSteps, and QMCUpdateBase::W.

241 {
242  IndexType initsteps = W.reptile->nbeads * 2;
243 
244  vmcSteps = W.reptile->nbeads + 1;
245 
246  for (int n = 0; n < initsteps; n++)
248 }
MCWalkerConfiguration & W
walker ensemble
OHMMS_INDEXTYPE IndexType
define other types
Definition: Configuration.h:65
IndexType nbeads
Definition: Reptile.h:59

◆ initWalkersForPbyP()

void initWalkersForPbyP ( WalkerIter_t  it,
WalkerIter_t  it_end 
)
overridevirtual

initialize Walker buffers for PbyP update

Reimplemented from QMCUpdateBase.

Definition at line 61 of file RMCUpdatePbyP.cpp.

References PooledMemory< T_scalar, Alloc >::allocate(), PooledMemory< T_scalar, Alloc >::clear(), TrialWaveFunction::copyFromBuffer(), Walker< t_traits, p_traits >::DataSet, ParticleSet::donePbyP(), QMCHamiltonian::evaluate(), TrialWaveFunction::evaluateLog(), ParticleSet::G, TrialWaveFunction::getPhase(), QMCUpdateBase::H, ParticleSet::L, Walker< t_traits, p_traits >::L, QMCUpdateBase::Psi, ParticleSet::R, Walker< t_traits, p_traits >::R, TrialWaveFunction::registerData(), Walker< t_traits, p_traits >::resetProperty(), PooledMemory< T_scalar, Alloc >::rewind(), PooledMemory< T_scalar, Alloc >::size(), ParticleSet::update(), TrialWaveFunction::updateBuffer(), QMCUpdateBase::UpdatePbyP, and QMCUpdateBase::W.

62 {
63  UpdatePbyP = true;
64 
65  for (; it != it_end; ++it)
66  {
67  Walker_t& awalker = **it; //W.reptile->getHead();
68  W.R = awalker.R;
69  W.update(true);
70  W.donePbyP();
71  if (awalker.DataSet.size())
72  awalker.DataSet.clear();
73  awalker.DataSet.rewind();
74  Psi.registerData(W, awalker.DataSet);
75  awalker.DataSet.allocate();
76  Psi.copyFromBuffer(W, awalker.DataSet);
77  Psi.evaluateLog(W);
78  RealType logpsi = Psi.updateBuffer(W, awalker.DataSet, false);
79  awalker.G = W.G;
80  awalker.L = W.L;
81  RealType eloc = H.evaluate(W);
82  awalker.resetProperty(logpsi, Psi.getPhase(), eloc);
83  }
84 }
RealType evaluateLog(ParticleSet &P)
evalaute the log (internally gradients and laplacian) of the trial wavefunction.
void copyFromBuffer(ParticleSet &P, WFBufferType &buf)
copy all the wavefunction components from buffer.
TrialWaveFunction & Psi
trial function
MCWalkerConfiguration::Walker_t Walker_t
Definition: QMCUpdateBase.h:44
void update(bool skipSK=false)
update the internal data
ParticleLaplacian L
laplacians of the particles
Definition: ParticleSet.h:85
RealType updateBuffer(ParticleSet &P, WFBufferType &buf, bool fromscratch=false)
update all the wavefunction components in buffer.
ParticleGradient G
gradients of the particles
Definition: ParticleSet.h:83
void registerData(ParticleSet &P, WFBufferType &buf)
register all the wavefunction components in buffer.
ParticlePos R
Position.
Definition: ParticleSet.h:79
MCWalkerConfiguration & W
walker ensemble
QMCTraits::RealType RealType
FullPrecRealType evaluate(ParticleSet &P)
evaluate Local Energy
QMCHamiltonian & H
Hamiltonian.
void donePbyP(bool skipSK=false)
update structure factor and unmark active_ptcl_
bool UpdatePbyP
update particle-by-particle

◆ operator=()

RMCUpdatePbyPWithDrift& operator= ( const RMCUpdatePbyPWithDrift )
privatedelete

Copy operator (disabled).

◆ put()

bool put ( xmlNodePtr  cur)
overridevirtual

process options

Reimplemented from QMCUpdateBase.

Definition at line 86 of file RMCUpdatePbyP.cpp.

References RMCUpdatePbyPWithDrift::actionType, ParameterSet::add(), qmcplusplus::app_log(), RMCUpdatePbyPWithDrift::DMC_ACTION, RMCUpdatePbyPWithDrift::equilSteps, omp_get_thread_num(), ParameterSet::put(), and QMCUpdateBase::put().

87 {
88  QMCUpdateBase::put(cur);
89 
90  ParameterSet m_param;
91  bool usedrift = true;
92  std::string action = "SLA";
93  m_param.add(usedrift, "useDrift");
94  m_param.add(action, "Action");
95  m_param.add(equilSteps, "equilsteps");
96  m_param.add(equilSteps, "equilSteps");
97  m_param.put(cur);
98 
99  if (usedrift == true)
100  {
101  if (omp_get_thread_num() == 0)
102  app_log() << " Using Umrigar scaled drift\n";
103  }
104  else
105  {
106  if (omp_get_thread_num() == 0)
107  app_log() << " Using non-scaled drift\n";
108  }
109 
110  if (action == "DMC")
111  {
113  if (omp_get_thread_num() == 0)
114  app_log() << " Using DMC link-action\n";
115  }
116  else
117  {
118  if (omp_get_thread_num() == 0)
119  app_log() << " Using Symmetrized Link-Action\n";
120  }
121 
122  return true;
123 }
std::ostream & app_log()
Definition: OutputManager.h:65
virtual bool put(xmlNodePtr cur)
process options
bool put(std::istream &is) override
read from std::istream
Definition: ParameterSet.h:42
omp_int_t omp_get_thread_num()
Definition: OpenMP.h:25
class to handle a set of parameters
Definition: ParameterSet.h:27
void add(PDT &aparam, const std::string &aname_in, std::vector< PDT > candidate_values={}, TagStatus status=TagStatus::OPTIONAL)
add a new parameter corresponding to an xmlNode <parameter>

Member Data Documentation

◆ Action

std::vector<int> Action
private

Definition at line 58 of file RMCUpdatePbyP.h.

◆ actionType

IndexType actionType
private

◆ advance_timer_

NewTimer& advance_timer_
private

Definition at line 62 of file RMCUpdatePbyP.h.

Referenced by RMCUpdatePbyPWithDrift::advanceWalkersVMC().

◆ energy_timer_

NewTimer& energy_timer_
private

Definition at line 65 of file RMCUpdatePbyP.h.

Referenced by RMCUpdatePbyPWithDrift::advanceWalkersVMC().

◆ equilSteps

IndexType equilSteps
private

Definition at line 68 of file RMCUpdatePbyP.h.

Referenced by RMCUpdatePbyPWithDrift::put().

◆ equilToDoSteps

IndexType equilToDoSteps
private

Definition at line 70 of file RMCUpdatePbyP.h.

◆ movepbyp_timer_

NewTimer& movepbyp_timer_
private

◆ scaleDrift

bool scaleDrift
private

Definition at line 59 of file RMCUpdatePbyP.h.

Referenced by RMCUpdatePbyPWithDrift::RMCUpdatePbyPWithDrift().

◆ TransProb

std::vector<int> TransProb
private

Definition at line 58 of file RMCUpdatePbyP.h.

◆ update_mbo_timer_

NewTimer& update_mbo_timer_
private

Definition at line 64 of file RMCUpdatePbyP.h.

Referenced by RMCUpdatePbyPWithDrift::advanceWalkersVMC().

◆ vmcSteps

IndexType vmcSteps
private

Definition at line 67 of file RMCUpdatePbyP.h.

Referenced by RMCUpdatePbyPWithDrift::initWalkers().

◆ vmcToDoSteps

IndexType vmcToDoSteps
private

Definition at line 69 of file RMCUpdatePbyP.h.

◆ qmcplusplus::SOVMCUpdateAll

class qmcplusplus::SOVMCUpdateAll


Implements the Spin VMC algorithm using particle-by-particle move.

Definition at line 19 of file SOVMCUpdateAll.h.

+ Inheritance diagram for SOVMCUpdateAll:
+ Collaboration diagram for SOVMCUpdateAll:

Public Member Functions

 SOVMCUpdateAll (MCWalkerConfiguration &w, TrialWaveFunction &psi, QMCHamiltonian &h, RandomBase< FullPrecRealType > &rg)
 Constructor. More...
 
 ~SOVMCUpdateAll () override
 
void advanceWalker (Walker_t &thisWalker, bool recompute) override
 move a walker More...
 
- Public Member Functions inherited from QMCUpdateBase
 QMCUpdateBase (MCWalkerConfiguration &w, TrialWaveFunction &psi, QMCHamiltonian &h, RandomBase< FullPrecRealType > &rg)
 Constructor. More...
 
 QMCUpdateBase (MCWalkerConfiguration &w, TrialWaveFunction &psi, TrialWaveFunction &guide, QMCHamiltonian &h, RandomBase< FullPrecRealType > &rg)
 Alt Constructor. More...
 
virtual ~QMCUpdateBase ()
 destructor More...
 
RealType acceptRatio () const
 
void resetRun (BranchEngineType *brancher, EstimatorManagerBase *est, TraceManager *traces, const DriftModifierBase *driftmodifer)
 reset the QMCUpdateBase parameters More...
 
void resetRun2 (BranchEngineType *brancher, EstimatorManagerBase *est, TraceManager *traces, WalkerLogCollector *wlog_collector_, const DriftModifierBase *driftmodifer)
 
RealType getTau ()
 
void setTau (RealType t)
 
RealType getSpinMass ()
 
void setSpinMass (RealType m)
 
void getLogs (std::vector< RealType > &logs)
 
void set_step (int step)
 
void startRun (int blocks, bool record)
 start a run More...
 
void stopRun ()
 stop a run More...
 
void stopRun2 ()
 
void startBlock (int steps)
 prepare to start a block More...
 
void stopBlock (bool collectall=true)
 stop a block More...
 
void setMultiplicity (WalkerIter_t it, WalkerIter_t it_end)
 set the multiplicity of the walkers to branch More...
 
void setMultiplicity (Walker_t &awalker) const
 
virtual void initWalkersForPbyP (WalkerIter_t it, WalkerIter_t it_end)
 initialize Walker buffers for PbyP update More...
 
virtual void initWalkers (WalkerIter_t it, WalkerIter_t it_end)
 initialize Walker for walker update More...
 
virtual bool put (xmlNodePtr cur)
 process options More...
 
void accumulate (WalkerIter_t it, WalkerIter_t it_end)
 
virtual void advanceWalkers (WalkerIter_t it, WalkerIter_t it_end, bool recompute)
 advance walkers executed at each step More...
 
virtual RealType advanceWalkerForEE (Walker_t &w1, std::vector< PosType > &dR, std::vector< int > &iats, std::vector< int > &rs, std::vector< RealType > &ratios)
 
int RMC_checkIndex (int N, int NMax)
 
void RMC_checkWalkerBounds (WalkerIter_t &it, WalkerIter_t first, WalkerIter_t last)
 
RealType logBackwardGF (const ParticleSet::ParticlePos &displ)
 

Private Member Functions

 SOVMCUpdateAll (const SOVMCUpdateAll &)=delete
 Copy Constructor (disabled) More...
 
SOVMCUpdateAlloperator= (const SOVMCUpdateAll &)=delete
 Copy operator (disabled). More...
 

Additional Inherited Members

- Public Types inherited from QMCUpdateBase
using Walker_t = MCWalkerConfiguration::Walker_t
 
using WalkerIter_t = MCWalkerConfiguration::iterator
 
using BranchEngineType = SimpleFixedNodeBranch
 
using mPosType = PosType
 
using mTensorType = TensorType
 
- Public Types inherited from QMCTraits
enum  { DIM = OHMMS_DIM, DIM_VGL = OHMMS_DIM + 2 }
 
using QTBase = QMCTypes< OHMMS_PRECISION, DIM >
 
using QTFull = QMCTypes< OHMMS_PRECISION_FULL, DIM >
 
using RealType = QTBase::RealType
 
using ComplexType = QTBase::ComplexType
 
using ValueType = QTBase::ValueType
 
using PosType = QTBase::PosType
 
using GradType = QTBase::GradType
 
using TensorType = QTBase::TensorType
 
using IndexType = OHMMS_INDEXTYPE
 define other types More...
 
using FullPrecRealType = QTFull::RealType
 
using FullPrecValueType = QTFull::ValueType
 
using PropertySetType = RecordNamedProperty< FullPrecRealType >
 define PropertyList_t More...
 
using PtclGrpIndexes = std::vector< std::pair< int, int > >
 
- Public Attributes inherited from QMCUpdateBase
int nSubSteps
 number of steps per measurement More...
 
DriverDebugChecks debug_checks_ = DriverDebugChecks::ALL_OFF
 determine additional checks for debugging purpose More...
 
std::string debug_checks_str_
 
IndexType MaxAge
 MaxAge>0 indicates branch is done. More...
 
IndexType nAccept
 counter for number of moves accepted More...
 
IndexType nReject
 counter for number of moves rejected More...
 
IndexType nAllRejected
 Total number of the steps when all the particle moves are rejected. More...
 
IndexType nNodeCrossing
 Total number of node crossings per block. More...
 
IndexType NonLocalMoveAccepted
 Total numer of non-local moves accepted. More...
 
RealType Tau
 timestep More...
 
RealType spinMass
 spin mass More...
 
bool UseDrift
 use Drift More...
 
RealType csoffset
 normalization offset for cs type runs. More...
 
TraceManagerTraces
 traces More...
 
WalkerLogCollectorwlog_collector
 
- Protected Member Functions inherited from QMCUpdateBase
RealType getNodeCorrection (const ParticleSet::ParticleGradient &g, ParticleSet::ParticlePos &gscaled)
 evaluate the ratio of scaled velocity and velocity More...
 
 QMCUpdateBase (const QMCUpdateBase &)=delete
 copy constructor (disabled) More...
 
- Static Protected Member Functions inherited from QMCUpdateBase
static void checkLogAndGL (ParticleSet &pset, TrialWaveFunction &twf, const std::string_view location)
 check logpsi and grad and lap against values computed from scratch More...
 
- Protected Attributes inherited from QMCUpdateBase
bool UpdatePbyP
 update particle-by-particle More...
 
IndexType NumPtcl
 number of particles More...
 
RealType m_oneover2tau
 Time-step factor $ 1/(2\tau)$. More...
 
RealType m_sqrttau
 Time-step factor $ \sqrt{\tau}$. More...
 
RealType m_tauovermass
 tau/mass More...
 
RealType m_r2max
 maximum displacement^2 More...
 
MCWalkerConfigurationW
 walker ensemble More...
 
TrialWaveFunctionPsi
 trial function More...
 
TrialWaveFunctionGuide
 guide function More...
 
QMCHamiltonianH
 Hamiltonian. More...
 
RandomBase< FullPrecRealType > & RandomGen
 random number generator More...
 
const BranchEngineTypebranchEngine
 branch engine, stateless reference to the one in QMCDriver More...
 
const DriftModifierBaseDriftModifier
 drift modifer, stateless reference to the one in QMCDriver More...
 
EstimatorManagerBaseEstimators
 estimator More...
 
ParameterSet myParams
 parameters More...
 
std::vector< RealTypeMassInvS
 1/Mass per species More...
 
std::vector< RealTypeMassInvP
 1/Mass per particle More...
 
std::vector< RealTypeSqrtTauOverMass
 sqrt(tau/Mass) per particle More...
 
ParticleSet::ParticlePos drift
 temporary storage for drift More...
 
ParticleSet::ParticlePos deltaR
 temporary storage for random displacement More...
 
ParticleSet::ParticleScalar deltaS
 temporart storage for spin displacement More...
 
ParticleSet::ParticleGradient G
 storage for differential gradients for PbyP update More...
 
ParticleSet::ParticleGradient dG
 
ParticleSet::ParticleLaplacian L
 storage for differential laplacians for PbyP update More...
 
ParticleSet::ParticleLaplacian dL
 

Constructor & Destructor Documentation

◆ SOVMCUpdateAll() [1/2]

Constructor.

Definition at line 24 of file SOVMCUpdateAll.cpp.

References QMCUpdateBase::UpdatePbyP.

28  : QMCUpdateBase(w, psi, h, rg)
29 {
30  UpdatePbyP = false;
31 }
QMCUpdateBase(MCWalkerConfiguration &w, TrialWaveFunction &psi, QMCHamiltonian &h, RandomBase< FullPrecRealType > &rg)
Constructor.
bool UpdatePbyP
update particle-by-particle

◆ ~SOVMCUpdateAll()

~SOVMCUpdateAll ( )
override

Definition at line 33 of file SOVMCUpdateAll.cpp.

33 {}

◆ SOVMCUpdateAll() [2/2]

SOVMCUpdateAll ( const SOVMCUpdateAll )
privatedelete

Copy Constructor (disabled)

Member Function Documentation

◆ advanceWalker()

void advanceWalker ( Walker_t thisWalker,
bool  recompute 
)
overridevirtual

move a walker

Implements QMCUpdateBase.

Definition at line 35 of file SOVMCUpdateAll.cpp.

References Walker< t_traits, p_traits >::Age, APP_ABORT, QMCHamiltonian::auxHevaluate(), QMCUpdateBase::deltaR, QMCUpdateBase::deltaS, QMCHamiltonian::evaluate(), TrialWaveFunction::evaluateLog(), qmcplusplus::exp(), TrialWaveFunction::getPhase(), Walker< t_traits, p_traits >::getPropertyBase(), QMCUpdateBase::H, ParticleSet::loadWalker(), qmcplusplus::makeGaussRandomWithEngine(), ParticleSet::makeMoveAllParticles(), QMCUpdateBase::nAccept, QMCUpdateBase::nReject, QMCUpdateBase::nSubSteps, Walker< t_traits, p_traits >::Properties, QMCUpdateBase::Psi, ParticleSet::R, Walker< t_traits, p_traits >::R, QMCUpdateBase::RandomGen, Walker< t_traits, p_traits >::resetProperty(), QMCHamiltonian::saveProperty(), ParticleSet::saveWalker(), QMCUpdateBase::spinMass, ParticleSet::spins, Walker< t_traits, p_traits >::spins, qmcplusplus::sqrt(), QMCUpdateBase::SqrtTauOverMass, ParticleSet::update(), QMCUpdateBase::UseDrift, and QMCUpdateBase::W.

36 {
37  /* thisWalker.R will track the last accepted configuration
38  * W.R will track the proposed configuration
39  *
40  * upon Call:
41  * thisWalker.R,G,L,Properties must be consistent
42  * recompute flag is for pbyp driver and is not used here
43  *
44  * upon Return:
45  * thisWalker.R,G,L,Properties must be kept consistent
46  * */
47  bool updated = false;
48  W.loadWalker(
49  thisWalker,
50  false); // W.R,G,L = thisWalker.R,G,L; false indicates W.DistTables & SK are not updated in this call. W.DistTables,SK are now stale.
51  RealType logpsi_old = thisWalker.Properties(WP::LOGPSI);
52 
53  RealType invSqrtSpinMass = 1.0 / std::sqrt(spinMass);
54 
55  for (int iter = 0; iter < nSubSteps; ++iter)
56  { // make a few Monte-Carlo steps to decorrelate samples without calculating observables
59  updated = false;
60  if (UseDrift)
61  {
62  APP_ABORT("All-electron spin moves with drift are not implemented\n");
63  }
64  else
65  {
66  if (W.makeMoveAllParticles(thisWalker, deltaR, SqrtTauOverMass))
67  {
68  //Assume that since the spatial move is fine, the spin move will be.
69  //Compute that now.
70  for (int iat = 0; iat < deltaR.size(); ++iat)
71  W.spins[iat] = thisWalker.spins[iat] + invSqrtSpinMass * SqrtTauOverMass[iat] * deltaS[iat];
72 
73  // W.R += dR*dt; W.DistTables,SK are updated; W.G,L are now stale
74  RealType logpsi = Psi.evaluateLog(W); // update W.G,L at changed W.R; update Psi.log_real_,PhaseValue
75  RealType g = std::exp(2.0 * (logpsi - logpsi_old));
76  if (RandomGen() <= g)
77  { // move is accepted; logpsi_old and R_old are stale
78  logpsi_old = logpsi; // update logpsi_old
79  thisWalker.R = W.R; // update R_old; side effect: thisWalker.G,L,DistTables,SK,Properties are now stale
80  thisWalker.spins =
81  W.spins; // update R_old; side effect: thisWalker.G,L,DistTables,SK,Properties are now stale
82  ++nAccept;
83  updated = true;
84  }
85  }
86  }
87 
88  if (!updated)
89  { // W.R,G,L,DistTables,SK are not updated. i.e. they are still consistent
90  thisWalker.Age++;
91  ++nReject;
92  }
93  }
94 
95  if (!updated)
96  { // W.G and W.L have to be computed because the last move was rejected
97  W.loadWalker(thisWalker, false); // move W back to last accepted configuration
98  W.update(); // update W.DistTables and SK
99  logpsi_old = Psi.evaluateLog(W); // update W.G,L
100  } // W and logpsi_old are up-to-date at this point
101 
102  RealType eloc = H.evaluate(
103  W); // calculate local energy; W.SK must be up-to-date if Coulomb interaction is used with periodic boundary. W.SK is used to calculate the long-range part of the Coulomb potential.
104  W.saveWalker(thisWalker);
105  thisWalker.resetProperty(logpsi_old, Psi.getPhase(),
106  eloc); // update thisWalker::Properties[WP::LOGPSI,WP::SIGN,WP::LOCALENERGY]
107  H.auxHevaluate(W, thisWalker); // update auxiliary observables, i.e. fill H::Observables
108  H.saveProperty(thisWalker.getPropertyBase()); // copy H::Observables to thisWalker::Properties
109 }
RealType evaluateLog(ParticleSet &P)
evalaute the log (internally gradients and laplacian) of the trial wavefunction.
ParticleScalar spins
internal spin variables for dynamical spin calculations
Definition: ParticleSet.h:81
TrialWaveFunction & Psi
trial function
RealType spinMass
spin mass
Definition: QMCUpdateBase.h:75
ParticleSet::ParticleScalar deltaS
temporart storage for spin displacement
void saveProperty(IT first)
save the values of Hamiltonian elements to the Properties
void update(bool skipSK=false)
update the internal data
ParticleSet::ParticlePos deltaR
temporary storage for random displacement
std::vector< RealType > SqrtTauOverMass
sqrt(tau/Mass) per particle
void saveWalker(Walker_t &awalker)
save this to awalker
ParticlePos R
Position.
Definition: ParticleSet.h:79
#define APP_ABORT(msg)
Widely used but deprecated fatal error macros from legacy code.
Definition: AppAbort.h:27
MakeReturn< UnaryNode< FnExp, typename CreateLeaf< Vector< T1, C1 > >::Leaf_t > >::Expression_t exp(const Vector< T1, C1 > &l)
MCWalkerConfiguration & W
walker ensemble
void loadWalker(Walker_t &awalker, bool pbyp)
load a Walker_t to the current ParticleSet
void auxHevaluate(ParticleSet &P)
int nSubSteps
number of steps per measurement
Definition: QMCUpdateBase.h:56
MakeReturn< UnaryNode< FnSqrt, typename CreateLeaf< Vector< T1, C1 > >::Leaf_t > >::Expression_t sqrt(const Vector< T1, C1 > &l)
QMCTraits::RealType RealType
RandomBase< FullPrecRealType > & RandomGen
random number generator
FullPrecRealType evaluate(ParticleSet &P)
evaluate Local Energy
IndexType nAccept
counter for number of moves accepted
Definition: QMCUpdateBase.h:63
IndexType nReject
counter for number of moves rejected
Definition: QMCUpdateBase.h:65
bool makeMoveAllParticles(const Walker_t &awalker, const ParticlePos &deltaR, RealType dt)
move all the particles of a walker
QMCHamiltonian & H
Hamiltonian.
void makeGaussRandomWithEngine(ParticleAttrib< TinyVector< T, D >> &a, RG &rng)

◆ operator=()

SOVMCUpdateAll& operator= ( const SOVMCUpdateAll )
privatedelete

Copy operator (disabled).

◆ qmcplusplus::SOVMCUpdatePbyP

class qmcplusplus::SOVMCUpdatePbyP


Implements the VMC algorithm using particle-by-particle move, including spin-moves

Definition at line 22 of file SOVMCUpdatePbyP.h.

+ Inheritance diagram for SOVMCUpdatePbyP:
+ Collaboration diagram for SOVMCUpdatePbyP:

Public Member Functions

 SOVMCUpdatePbyP (MCWalkerConfiguration &w, TrialWaveFunction &psi, QMCHamiltonian &h, RandomBase< FullPrecRealType > &rg)
 Constructor. More...
 
 ~SOVMCUpdatePbyP () override
 
void advanceWalker (Walker_t &thisWalker, bool recompute) override
 move a walker More...
 
- Public Member Functions inherited from QMCUpdateBase
 QMCUpdateBase (MCWalkerConfiguration &w, TrialWaveFunction &psi, QMCHamiltonian &h, RandomBase< FullPrecRealType > &rg)
 Constructor. More...
 
 QMCUpdateBase (MCWalkerConfiguration &w, TrialWaveFunction &psi, TrialWaveFunction &guide, QMCHamiltonian &h, RandomBase< FullPrecRealType > &rg)
 Alt Constructor. More...
 
virtual ~QMCUpdateBase ()
 destructor More...
 
RealType acceptRatio () const
 
void resetRun (BranchEngineType *brancher, EstimatorManagerBase *est, TraceManager *traces, const DriftModifierBase *driftmodifer)
 reset the QMCUpdateBase parameters More...
 
void resetRun2 (BranchEngineType *brancher, EstimatorManagerBase *est, TraceManager *traces, WalkerLogCollector *wlog_collector_, const DriftModifierBase *driftmodifer)
 
RealType getTau ()
 
void setTau (RealType t)
 
RealType getSpinMass ()
 
void setSpinMass (RealType m)
 
void getLogs (std::vector< RealType > &logs)
 
void set_step (int step)
 
void startRun (int blocks, bool record)
 start a run More...
 
void stopRun ()
 stop a run More...
 
void stopRun2 ()
 
void startBlock (int steps)
 prepare to start a block More...
 
void stopBlock (bool collectall=true)
 stop a block More...
 
void setMultiplicity (WalkerIter_t it, WalkerIter_t it_end)
 set the multiplicity of the walkers to branch More...
 
void setMultiplicity (Walker_t &awalker) const
 
virtual void initWalkersForPbyP (WalkerIter_t it, WalkerIter_t it_end)
 initialize Walker buffers for PbyP update More...
 
virtual void initWalkers (WalkerIter_t it, WalkerIter_t it_end)
 initialize Walker for walker update More...
 
virtual bool put (xmlNodePtr cur)
 process options More...
 
void accumulate (WalkerIter_t it, WalkerIter_t it_end)
 
virtual void advanceWalkers (WalkerIter_t it, WalkerIter_t it_end, bool recompute)
 advance walkers executed at each step More...
 
virtual RealType advanceWalkerForEE (Walker_t &w1, std::vector< PosType > &dR, std::vector< int > &iats, std::vector< int > &rs, std::vector< RealType > &ratios)
 
int RMC_checkIndex (int N, int NMax)
 
void RMC_checkWalkerBounds (WalkerIter_t &it, WalkerIter_t first, WalkerIter_t last)
 
RealType logBackwardGF (const ParticleSet::ParticlePos &displ)
 

Private Attributes

NewTimerbuffer_timer_
 
NewTimermovepbyp_timer_
 
NewTimerhamiltonian_timer_
 
NewTimercollectables_timer_
 

Additional Inherited Members

- Public Types inherited from QMCUpdateBase
using Walker_t = MCWalkerConfiguration::Walker_t
 
using WalkerIter_t = MCWalkerConfiguration::iterator
 
using BranchEngineType = SimpleFixedNodeBranch
 
using mPosType = PosType
 
using mTensorType = TensorType
 
- Public Types inherited from QMCTraits
enum  { DIM = OHMMS_DIM, DIM_VGL = OHMMS_DIM + 2 }
 
using QTBase = QMCTypes< OHMMS_PRECISION, DIM >
 
using QTFull = QMCTypes< OHMMS_PRECISION_FULL, DIM >
 
using RealType = QTBase::RealType
 
using ComplexType = QTBase::ComplexType
 
using ValueType = QTBase::ValueType
 
using PosType = QTBase::PosType
 
using GradType = QTBase::GradType
 
using TensorType = QTBase::TensorType
 
using IndexType = OHMMS_INDEXTYPE
 define other types More...
 
using FullPrecRealType = QTFull::RealType
 
using FullPrecValueType = QTFull::ValueType
 
using PropertySetType = RecordNamedProperty< FullPrecRealType >
 define PropertyList_t More...
 
using PtclGrpIndexes = std::vector< std::pair< int, int > >
 
- Public Attributes inherited from QMCUpdateBase
int nSubSteps
 number of steps per measurement More...
 
DriverDebugChecks debug_checks_ = DriverDebugChecks::ALL_OFF
 determine additional checks for debugging purpose More...
 
std::string debug_checks_str_
 
IndexType MaxAge
 MaxAge>0 indicates branch is done. More...
 
IndexType nAccept
 counter for number of moves accepted More...
 
IndexType nReject
 counter for number of moves rejected More...
 
IndexType nAllRejected
 Total number of the steps when all the particle moves are rejected. More...
 
IndexType nNodeCrossing
 Total number of node crossings per block. More...
 
IndexType NonLocalMoveAccepted
 Total numer of non-local moves accepted. More...
 
RealType Tau
 timestep More...
 
RealType spinMass
 spin mass More...
 
bool UseDrift
 use Drift More...
 
RealType csoffset
 normalization offset for cs type runs. More...
 
TraceManagerTraces
 traces More...
 
WalkerLogCollectorwlog_collector
 
- Protected Member Functions inherited from QMCUpdateBase
RealType getNodeCorrection (const ParticleSet::ParticleGradient &g, ParticleSet::ParticlePos &gscaled)
 evaluate the ratio of scaled velocity and velocity More...
 
 QMCUpdateBase (const QMCUpdateBase &)=delete
 copy constructor (disabled) More...
 
- Static Protected Member Functions inherited from QMCUpdateBase
static void checkLogAndGL (ParticleSet &pset, TrialWaveFunction &twf, const std::string_view location)
 check logpsi and grad and lap against values computed from scratch More...
 
- Protected Attributes inherited from QMCUpdateBase
bool UpdatePbyP
 update particle-by-particle More...
 
IndexType NumPtcl
 number of particles More...
 
RealType m_oneover2tau
 Time-step factor $ 1/(2\tau)$. More...
 
RealType m_sqrttau
 Time-step factor $ \sqrt{\tau}$. More...
 
RealType m_tauovermass
 tau/mass More...
 
RealType m_r2max
 maximum displacement^2 More...
 
MCWalkerConfigurationW
 walker ensemble More...
 
TrialWaveFunctionPsi
 trial function More...
 
TrialWaveFunctionGuide
 guide function More...
 
QMCHamiltonianH
 Hamiltonian. More...
 
RandomBase< FullPrecRealType > & RandomGen
 random number generator More...
 
const BranchEngineTypebranchEngine
 branch engine, stateless reference to the one in QMCDriver More...
 
const DriftModifierBaseDriftModifier
 drift modifer, stateless reference to the one in QMCDriver More...
 
EstimatorManagerBaseEstimators
 estimator More...
 
ParameterSet myParams
 parameters More...
 
std::vector< RealTypeMassInvS
 1/Mass per species More...
 
std::vector< RealTypeMassInvP
 1/Mass per particle More...
 
std::vector< RealTypeSqrtTauOverMass
 sqrt(tau/Mass) per particle More...
 
ParticleSet::ParticlePos drift
 temporary storage for drift More...
 
ParticleSet::ParticlePos deltaR
 temporary storage for random displacement More...
 
ParticleSet::ParticleScalar deltaS
 temporart storage for spin displacement More...
 
ParticleSet::ParticleGradient G
 storage for differential gradients for PbyP update More...
 
ParticleSet::ParticleGradient dG
 
ParticleSet::ParticleLaplacian L
 storage for differential laplacians for PbyP update More...
 
ParticleSet::ParticleLaplacian dL
 

Constructor & Destructor Documentation

◆ SOVMCUpdatePbyP()

Constructor.

Definition at line 26 of file SOVMCUpdatePbyP.cpp.

30  : QMCUpdateBase(w, psi, h, rg),
31  buffer_timer_(createGlobalTimer("SOVMCUpdatePbyP::Buffer", timer_level_medium)),
32  movepbyp_timer_(createGlobalTimer("SOVMCUpdatePbyP::MovePbyP", timer_level_medium)),
33  hamiltonian_timer_(createGlobalTimer("SOVMCUpdatePbyP::Hamiltonian", timer_level_medium)),
34  collectables_timer_(createGlobalTimer("SOVMCUpdatePbyP::Collectables", timer_level_medium))
35 {}
NewTimer & createGlobalTimer(const std::string &myname, timer_levels mylevel)
QMCUpdateBase(MCWalkerConfiguration &w, TrialWaveFunction &psi, QMCHamiltonian &h, RandomBase< FullPrecRealType > &rg)
Constructor.

◆ ~SOVMCUpdatePbyP()

~SOVMCUpdatePbyP ( )
override

Definition at line 37 of file SOVMCUpdatePbyP.cpp.

37 {}

Member Function Documentation

◆ advanceWalker()

void advanceWalker ( Walker_t thisWalker,
bool  recompute 
)
overridevirtual

move a walker

Implements QMCUpdateBase.

Definition at line 39 of file SOVMCUpdatePbyP.cpp.

References ParticleSet::accept_rejectMove(), TrialWaveFunction::acceptMove(), QMCHamiltonian::auxHevaluate(), TraceManager::buffer_sample(), SOVMCUpdatePbyP::buffer_timer_, TrialWaveFunction::calcRatio(), TrialWaveFunction::calcRatioGradWithSpin(), qmcplusplus::CHECKGL_AFTER_MOVES, QMCUpdateBase::checkLogAndGL(), SOVMCUpdatePbyP::collectables_timer_, TrialWaveFunction::completeUpdates(), TrialWaveFunction::copyFromBuffer(), ParticleSet::current_step, Walker< t_traits, p_traits >::DataSet, QMCUpdateBase::debug_checks_, QMCUpdateBase::deltaR, QMCUpdateBase::deltaS, ParticleSet::donePbyP(), qmcplusplus::dot(), QMCUpdateBase::DriftModifier, TrialWaveFunction::evalGradWithSpin(), QMCHamiltonian::evaluate(), qmcplusplus::exp(), ParticleSet::first(), ParticleSet::getActivePos(), ParticleSet::getActiveSpinVal(), DriftModifierBase::getDrift(), TrialWaveFunction::getPhase(), Walker< t_traits, p_traits >::getPropertyBase(), ParticleSet::groups(), QMCUpdateBase::H, SOVMCUpdatePbyP::hamiltonian_timer_, ParticleSet::last(), ParticleSet::loadWalker(), qmcplusplus::makeGaussRandomWithEngine(), ParticleSet::makeMoveAndCheckWithSpin(), QMCUpdateBase::MassInvS, SOVMCUpdatePbyP::movepbyp_timer_, QMCUpdateBase::nAccept, QMCUpdateBase::nAllRejected, norm(), QMCUpdateBase::nReject, QMCUpdateBase::nSubSteps, TrialWaveFunction::prepareGroup(), QMCUpdateBase::Psi, ParticleSet::R, QMCUpdateBase::RandomGen, TrialWaveFunction::rejectMove(), Walker< t_traits, p_traits >::resetProperty(), QMCHamiltonian::saveProperty(), ParticleSet::saveWalker(), QMCUpdateBase::spinMass, ParticleSet::spins, qmcplusplus::sqrt(), TimerType< CLOCK >::start(), TimerType< CLOCK >::stop(), QMCUpdateBase::Tau, QMCUpdateBase::Traces, TrialWaveFunction::updateBuffer(), QMCUpdateBase::UseDrift, and QMCUpdateBase::W.

40 {
42  W.loadWalker(thisWalker, true);
43  Walker_t::WFBuffer_t& w_buffer(thisWalker.DataSet);
44  Psi.copyFromBuffer(W, w_buffer);
46 
47  // start PbyP moves
49  bool moved = false;
50  constexpr RealType mhalf(-0.5);
51  for (int iter = 0; iter < nSubSteps; ++iter)
52  {
53  //create a 3N-Dimensional Gaussian with variance=1
56  moved = false;
57  for (int ig = 0; ig < W.groups(); ++ig) //loop over species
58  {
59  RealType tauovermass = Tau * MassInvS[ig];
60  RealType oneover2tau = 0.5 / (tauovermass);
61  RealType sqrttau = std::sqrt(tauovermass);
62  Psi.prepareGroup(W, ig);
63  for (int iat = W.first(ig); iat < W.last(ig); ++iat)
64  {
65  PosType dr;
67  if (UseDrift)
68  {
69  ComplexType spingrad_now;
70  GradType grad_now = Psi.evalGradWithSpin(W, iat, spingrad_now);
71  DriftModifier->getDrift(tauovermass, grad_now, dr);
72  DriftModifier->getDrift(tauovermass / spinMass, spingrad_now, ds);
73  dr += sqrttau * deltaR[iat];
74  ds += std::sqrt(tauovermass / spinMass) * deltaS[iat];
75  }
76  else
77  {
78  dr = sqrttau * deltaR[iat];
79  ds = std::sqrt(tauovermass / spinMass) * deltaS[iat];
80  }
81  if (!W.makeMoveAndCheckWithSpin(iat, dr, ds))
82  {
83  ++nReject;
84  W.accept_rejectMove(iat, false);
85  continue;
86  }
87  RealType prob(0);
88  if (UseDrift)
89  {
90  GradType grad_new;
91  ComplexType spingrad_new;
92  prob = std::norm(Psi.calcRatioGradWithSpin(W, iat, grad_new, spingrad_new));
93  DriftModifier->getDrift(tauovermass, grad_new, dr);
94  dr = W.R[iat] - W.getActivePos() - dr;
95  RealType logGb = -oneover2tau * dot(dr, dr);
96  RealType logGf = mhalf * dot(deltaR[iat], deltaR[iat]);
97 
98  DriftModifier->getDrift(tauovermass / spinMass, spingrad_new, ds);
99  ds = W.spins[iat] - W.getActiveSpinVal() - ds;
100  logGb += -spinMass * oneover2tau * ds * ds;
101  logGf += mhalf * deltaS[iat] * deltaS[iat];
102 
103  prob *= std::exp(logGb - logGf);
104  }
105  else
106  {
107  prob = std::norm(Psi.calcRatio(W, iat));
108  }
109 
110  bool is_accepted = false;
111  if (prob >= std::numeric_limits<RealType>::epsilon() && RandomGen() < prob)
112  {
113  is_accepted = true;
114  moved = true;
115  ++nAccept;
116  Psi.acceptMove(W, iat, true);
117  }
118  else
119  {
120  ++nReject;
121  Psi.rejectMove(iat);
122  }
123  W.accept_rejectMove(iat, is_accepted);
124  }
125  }
127  }
128  W.donePbyP();
131  RealType logpsi = Psi.updateBuffer(W, w_buffer, recompute);
133  checkLogAndGL(W, Psi, "checkGL_after_moves");
134  W.saveWalker(thisWalker);
136  // end PbyP moves
138  FullPrecRealType eloc = H.evaluate(W);
139  thisWalker.resetProperty(logpsi, Psi.getPhase(), eloc);
142  H.auxHevaluate(W, thisWalker);
143  H.saveProperty(thisWalker.getPropertyBase());
145 #if !defined(REMOVE_TRACEMANAGER)
147 #endif
148  if (!moved)
149  ++nAllRejected;
150 }
TraceManager * Traces
traces
void rejectMove(int iat)
restore to the original state
ValueType calcRatio(ParticleSet &P, int iat, ComputeType ct=ComputeType::ALL)
compute psi(R_new) / psi(R_current) ratio It returns a complex value if the wavefunction is complex...
void copyFromBuffer(ParticleSet &P, WFBufferType &buf)
copy all the wavefunction components from buffer.
QTBase::GradType GradType
Definition: Configuration.h:62
Scalar_t getActiveSpinVal() const
Definition: ParticleSet.h:262
ParticleScalar spins
internal spin variables for dynamical spin calculations
Definition: ParticleSet.h:81
TrialWaveFunction & Psi
trial function
RealType spinMass
spin mass
Definition: QMCUpdateBase.h:75
void acceptMove(ParticleSet &P, int iat, bool safe_to_delay=false)
update the state with the new data
ParticleSet::ParticleScalar deltaS
temporart storage for spin displacement
void saveProperty(IT first)
save the values of Hamiltonian elements to the Properties
void buffer_sample(int current_step)
QTBase::ComplexType ComplexType
Definition: Configuration.h:59
int first(int igroup) const
return the first index of a group i
Definition: ParticleSet.h:514
int current_step
current MC step
Definition: ParticleSet.h:134
ParticleSet::ParticlePos deltaR
temporary storage for random displacement
RealType updateBuffer(ParticleSet &P, WFBufferType &buf, bool fromscratch=false)
update all the wavefunction components in buffer.
DriverDebugChecks debug_checks_
determine additional checks for debugging purpose
Definition: QMCUpdateBase.h:58
QMCTraits::PosType PosType
int groups() const
return the number of groups
Definition: ParticleSet.h:511
PooledMemory< FullPrecRealType > WFBuffer_t
Definition: Walker.h:80
const PosType & getActivePos() const
Definition: ParticleSet.h:261
GradType evalGradWithSpin(ParticleSet &P, int iat, ComplexType &spingrad)
compute d/ds ln(psi) spin gradient at current particle position for iat electron
double norm(const zVec &c)
Definition: VectorOps.h:118
bool makeMoveAndCheckWithSpin(Index_t iat, const SingleParticlePos &displ, const Scalar_t &sdispl)
makeMoveAndCheck, but now includes an update to the spin variable
void saveWalker(Walker_t &awalker)
save this to awalker
RealType Tau
timestep
Definition: QMCUpdateBase.h:73
void accept_rejectMove(Index_t iat, bool accepted, bool forward_mode=true)
accept or reject a proposed move Two operation modes: The using and updating distance tables via Part...
ParticlePos R
Position.
Definition: ParticleSet.h:79
int last(int igroup) const
return the last index of a group i
Definition: ParticleSet.h:517
MakeReturn< UnaryNode< FnExp, typename CreateLeaf< Vector< T1, C1 > >::Leaf_t > >::Expression_t exp(const Vector< T1, C1 > &l)
MCWalkerConfiguration & W
walker ensemble
static void checkLogAndGL(ParticleSet &pset, TrialWaveFunction &twf, const std::string_view location)
check logpsi and grad and lap against values computed from scratch
void loadWalker(Walker_t &awalker, bool pbyp)
load a Walker_t to the current ParticleSet
void auxHevaluate(ParticleSet &P)
int nSubSteps
number of steps per measurement
Definition: QMCUpdateBase.h:56
MakeReturn< UnaryNode< FnSqrt, typename CreateLeaf< Vector< T1, C1 > >::Leaf_t > >::Expression_t sqrt(const Vector< T1, C1 > &l)
QMCTraits::RealType RealType
RandomBase< FullPrecRealType > & RandomGen
random number generator
FullPrecRealType evaluate(ParticleSet &P)
evaluate Local Energy
Tensor< typename BinaryReturn< T1, T2, OpMultiply >::Type_t, D > dot(const AntiSymTensor< T1, D > &lhs, const AntiSymTensor< T2, D > &rhs)
ValueType calcRatioGradWithSpin(ParticleSet &P, int iat, GradType &grad_iat, ComplexType &spingrad_iat)
compute psi(R_new) / psi(R_current) ratio and d/ds ln(psi(R_new)) spin gradient It returns a complex ...
QTFull::RealType FullPrecRealType
Definition: Configuration.h:66
IndexType nAccept
counter for number of moves accepted
Definition: QMCUpdateBase.h:63
IndexType nReject
counter for number of moves rejected
Definition: QMCUpdateBase.h:65
virtual void getDrift(RealType tau, const GradType &qf, PosType &drift) const =0
evaluate a drift with a real force
void prepareGroup(ParticleSet &P, int ig)
Prepare internal data for updating WFC correspond to a particle group Particle groups usually corresp...
std::vector< RealType > MassInvS
1/Mass per species
QMCHamiltonian & H
Hamiltonian.
void donePbyP(bool skipSK=false)
update structure factor and unmark active_ptcl_
void completeUpdates()
complete all the delayed or asynchronous operations before leaving the p-by-p move region...
IndexType nAllRejected
Total number of the steps when all the particle moves are rejected.
Definition: QMCUpdateBase.h:67
const DriftModifierBase * DriftModifier
drift modifer, stateless reference to the one in QMCDriver
void makeGaussRandomWithEngine(ParticleAttrib< TinyVector< T, D >> &a, RG &rng)

Member Data Documentation

◆ buffer_timer_

NewTimer& buffer_timer_
private

Definition at line 36 of file SOVMCUpdatePbyP.h.

Referenced by SOVMCUpdatePbyP::advanceWalker().

◆ collectables_timer_

NewTimer& collectables_timer_
private

Definition at line 39 of file SOVMCUpdatePbyP.h.

Referenced by SOVMCUpdatePbyP::advanceWalker().

◆ hamiltonian_timer_

NewTimer& hamiltonian_timer_
private

Definition at line 38 of file SOVMCUpdatePbyP.h.

Referenced by SOVMCUpdatePbyP::advanceWalker().

◆ movepbyp_timer_

NewTimer& movepbyp_timer_
private

Definition at line 37 of file SOVMCUpdatePbyP.h.

Referenced by SOVMCUpdatePbyP::advanceWalker().

◆ qmcplusplus::VMC

class qmcplusplus::VMC


Implements a VMC using particle-by-particle move.

Threaded execution.

Definition at line 24 of file VMC.h.

+ Inheritance diagram for VMC:
+ Collaboration diagram for VMC:

Public Member Functions

 VMC (const ProjectData &project_data_, MCWalkerConfiguration &w, TrialWaveFunction &psi, QMCHamiltonian &h, UPtrVector< RandomBase< QMCTraits::FullPrecRealType >> &rngs, Communicate *comm, bool enable_profiling)
 Constructor. More...
 
bool run () override
 
bool put (xmlNodePtr cur) override
 
QMCRunType getRunType () override
 
- Public Member Functions inherited from QMCDriver
 QMCDriver (const ProjectData &project_data, MCWalkerConfiguration &w, TrialWaveFunction &psi, QMCHamiltonian &h, Communicate *comm, const std::string &QMC_driver_type, bool enable_profiling=false)
 Constructor. More...
 
 ~QMCDriver () override
 
int current () const
 return current step More...
 
void setUpdateMode (bool pbyp) override
 set the update mode More...
 
void setStatus (const std::string &aname, const std::string &h5name, bool append) override
 Set the status of the QMCDriver. More...
 
void add_H_and_Psi (QMCHamiltonian *h, TrialWaveFunction *psi) override
 add QMCHamiltonian/TrialWaveFunction pair for multiple More...
 
void process (xmlNodePtr cur) override
 initialize with xmlNode More...
 
xmlNodePtr getQMCNode ()
 return a xmlnode with update More...
 
void putWalkers (std::vector< xmlNodePtr > &wset) override
 Read walker configurations from *.config.h5 files. More...
 
void putTraces (xmlNodePtr txml) override
 
void requestTraces (bool traces) override
 
void putWalkerLogs (xmlNodePtr wlxml) override
 
void requestWalkerLogs (bool allow_walker_logs_) override
 
std::string getEngineName () override
 
template<class PDT >
void setValue (const std::string &aname, PDT x)
 
void setBranchEngine (std::unique_ptr< BranchEngineType > &&be) override
 set the BranchEngineType More...
 
std::unique_ptr< BranchEngineTypegetBranchEngine () override
 return BranchEngineType* More...
 
int addObservable (const std::string &aname)
 
RealType getObservable (int i)
 
void setTau (RealType i)
 
void setWalkerOffsets ()
 set global offsets of the walkers More...
 
RefVector< RandomBase< FullPrecRealType > > getRngRefs () const
 return the random generators More...
 
RandomBase< FullPrecRealType > & getRng (int i) override
 return the i-th random generator More...
 
unsigned long getDriverMode () override
 
- Public Member Functions inherited from QMCDriverInterface
virtual ~QMCDriverInterface ()
 
virtual void setBranchEngine (std::unique_ptr< BranchEngineType > &&be)
 
- Public Member Functions inherited from MPIObjectBase
 MPIObjectBase (Communicate *c)
 constructor with communicator More...
 
int rank () const
 return the rank of the communicator More...
 
int getGroupID () const
 return the group id of the communicator More...
 
CommunicategetCommunicator () const
 return myComm More...
 
CommunicategetCommRef () const
 return a TEMPORARY reference to Communicate More...
 
mpi_comm_type getMPI () const
 return MPI communicator if one wants to use MPI directly More...
 
bool is_manager () const
 return true if the rank == 0 More...
 
const std::string & getName () const
 return the name More...
 
void setName (const std::string &aname)
 
- Public Member Functions inherited from CloneManager
 CloneManager ()
 Constructor. More...
 
virtual ~CloneManager ()
 virtual destructor More...
 
void makeClones (MCWalkerConfiguration &w, TrialWaveFunction &psi, QMCHamiltonian &ham)
 
void makeClones (MCWalkerConfiguration &w, std::vector< TrialWaveFunction *> &psi, std::vector< QMCHamiltonian *> &ham)
 
void makeClones (MCWalkerConfiguration &wg, TrialWaveFunction &guide)
 
void makeClones (TrialWaveFunction &guide)
 
RealType acceptRatio () const
 

Private Member Functions

void resetRun ()
 check the run-time environments More...
 
 VMC (const VMC &)=delete
 copy constructor More...
 
VMCoperator= (const VMC &)=delete
 Copy operator (disabled). More...
 

Private Attributes

int prevSteps
 
int prevStepsBetweenSamples
 
std::string UseDrift
 option to enable/disable drift equation or RN for VMC More...
 
UPtrVector< RandomBase< QMCTraits::FullPrecRealType > > & rngs_
 

Additional Inherited Members

- Public Types inherited from QMCDriver
enum  { QMC_UPDATE_MODE, QMC_MULTIPLE, QMC_OPTIMIZE, QMC_WARMUP }
 enumeration coupled with QMCMode More...
 
using Walker_t = MCWalkerConfiguration::Walker_t
 
using Buffer_t = Walker_t::Buffer_t
 
using FullPrecRealType = QMCTraits::FullPrecRealType
 
- Public Types inherited from QMCDriverInterface
using BranchEngineType = SimpleFixedNodeBranch
 
using FullPrecRealType = QMCTraits::FullPrecRealType
 
- Public Types inherited from QMCTraits
enum  { DIM = OHMMS_DIM, DIM_VGL = OHMMS_DIM + 2 }
 
using QTBase = QMCTypes< OHMMS_PRECISION, DIM >
 
using QTFull = QMCTypes< OHMMS_PRECISION_FULL, DIM >
 
using RealType = QTBase::RealType
 
using ComplexType = QTBase::ComplexType
 
using ValueType = QTBase::ValueType
 
using PosType = QTBase::PosType
 
using GradType = QTBase::GradType
 
using TensorType = QTBase::TensorType
 
using IndexType = OHMMS_INDEXTYPE
 define other types More...
 
using FullPrecRealType = QTFull::RealType
 
using FullPrecValueType = QTFull::ValueType
 
using PropertySetType = RecordNamedProperty< FullPrecRealType >
 define PropertyList_t More...
 
using PtclGrpIndexes = std::vector< std::pair< int, int > >
 
- Public Types inherited from MPIObjectBase
using mpi_comm_type = Communicate::mpi_comm_type
 
- Static Public Member Functions inherited from CloneManager
static void clearClones ()
 
- Public Attributes inherited from QMCDriver
std::bitset< QMC_MODE_MAXqmc_driver_mode
 bits to classify QMCDriver More...
 
bool allow_traces
 whether to allow traces More...
 
xmlNodePtr traces_xml
 traces xml More...
 
bool allow_walker_logs
 whether to allow traces More...
 
xmlNodePtr walker_logs_xml
 traces xml More...
 
EstimatorManagerBaseEstimators
 Observables manager. More...
 
std::unique_ptr< TraceManagerTraces
 Traces manager. More...
 
std::unique_ptr< WalkerLogManagerwlog_manager_
 Traces manager. More...
 
- Protected Member Functions inherited from QMCDriver
bool putQMCInfo (xmlNodePtr cur)
 Parses the xml input file for parameter definitions for a single qmc simulation. More...
 
void addWalkers (int nwalkers)
 Add walkers to the end of the ensemble of walkers. More...
 
void recordBlock (int block) override
 record the state of the block More...
 
bool finalize (int block, bool dumpwalkers=true)
 finalize a qmc section More...
 
std::string getRotationName (std::string RootName)
 
std::string getLastRotationName (std::string RootName)
 
const std::string & get_root_name () const override
 
- Protected Member Functions inherited from CloneManager
RefVector< WalkerLogCollectorgetWalkerLogCollectorRefs ()
 
- Protected Attributes inherited from QMCDriver
const ProjectDataproject_data_
 top-level project data information More...
 
std::unique_ptr< BranchEngineTypebranchEngine
 branch engine More...
 
DriftModifierBaseDriftModifier
 drift modifer More...
 
bool ResetRandom
 randomize it More...
 
bool AppendRun
 flag to append or restart the run More...
 
bool DumpConfig
 flag to turn off dumping configurations More...
 
bool IsQMCDriver
 true, if it is a real QMC engine More...
 
int MyCounter
 the number of times this QMCDriver is executed More...
 
int kDelay
 the number to delay updates by More...
 
int Period4CheckPoint
 period of dumping walker configurations and everything else for restart More...
 
int Period4CheckProperties
 period of dumping walker positions and IDs for Forward Walking More...
 
int Period4WalkerDump
 period of recording walker configurations More...
 
int Period4ConfigDump
 period of recording walker positions and IDs for forward walking afterwards More...
 
IndexType CurrentStep
 current step More...
 
IndexType nBlocks
 maximum number of blocks More...
 
IndexType nSteps
 maximum number of steps More...
 
IndexType nSubSteps
 number of steps between a step: VMCs do not evaluate energies More...
 
IndexType nWarmupSteps
 number of warmup steps More...
 
IndexType nAccept
 counter for number of moves accepted More...
 
IndexType nReject
 counter for number of moves /rejected More...
 
IndexType nBlocksBetweenRecompute
 the number of blocks between recomptePsi More...
 
IndexType nTargetWalkers
 the number of walkers More...
 
IndexType nTargetSamples
 the number of saved samples More...
 
IndexType nStepsBetweenSamples
 alternate method of setting QMC run parameters More...
 
RealType nSamplesPerThread
 samples per thread More...
 
RealType nTargetPopulation
 target population More...
 
RealType Tau
 timestep More...
 
int MaxCPUSecs
 maximum cpu in secs More...
 
RealType m_oneover2tau
 Time-step factor $ 1/(2\tau)$. More...
 
RealType m_sqrttau
 Time-step factor $ \sqrt{\tau}$. More...
 
xmlNodePtr qmcNode
 pointer to qmc node in xml file More...
 
const std::string QMCType
 type of QMC driver More...
 
std::string h5FileRoot
 the root of h5File More...
 
std::string RootName
 root of all the output files More...
 
ParameterSet m_param
 store any parameter that has to be read from a file More...
 
MCWalkerConfigurationW
 walker ensemble More...
 
TrialWaveFunctionPsi
 trial function More...
 
QMCHamiltonianH
 Hamiltonian. More...
 
std::unique_ptr< HDFWalkerOutputwOut
 record engine for walkers More...
 
std::vector< TrialWaveFunction * > Psi1
 a list of TrialWaveFunctions for multiple method More...
 
std::vector< QMCHamiltonian * > H1
 a list of QMCHamiltonians for multiple method More...
 
UPtrVector< RandomBase< FullPrecRealType > > Rng
 Random number generators. More...
 
std::vector< xmlNodePtr > mcwalkerNodePtr
 a list of mcwalkerset element More...
 
ParticleSet::ParticlePos drift
 temporary storage for drift More...
 
ParticleSet::ParticlePos deltaR
 temporary storage for random displacement More...
 
RealType SpinMass
 spin mass for spinor calcs More...
 
int rotation
 
- Protected Attributes inherited from MPIObjectBase
CommunicatemyComm
 pointer to Communicate More...
 
std::string ClassName
 class Name More...
 
std::string myName
 name of the object More...
 
- Protected Attributes inherited from CloneManager
const IndexType NumThreads
 number of threads More...
 
std::vector< QMCUpdateBase * > Movers
 update engines More...
 
std::vector< EstimatorManagerBase * > estimatorClones
 estimator managers More...
 
std::vector< TraceManager * > traceClones
 trace managers More...
 
UPtrVector< WalkerLogCollectorwlog_collectors
 trace collectors More...
 
UPtrVector< CSUpdateBaseCSMovers
 
std::vector< int > wPerRank
 Walkers per MPI rank. More...
 
- Static Protected Attributes inherited from CloneManager
static UPtrVector< MCWalkerConfigurationwClones_uptr
 walkers More...
 
static std::vector< MCWalkerConfiguration * > wClones
 
static UPtrVector< MCWalkerConfigurationwgClones
 
static UPtrVector< TrialWaveFunctionpsiClones_uptr
 trial wavefunctions More...
 
static std::vector< TrialWaveFunction * > psiClones
 
static UPtrVector< TrialWaveFunctionguideClones_uptr
 guide wavefunctions More...
 
static std::vector< TrialWaveFunction * > guideClones
 
static UPtrVector< QMCHamiltonianhClones_uptr
 Hamiltonians. More...
 
static std::vector< QMCHamiltonian * > hClones
 
static std::vector< UPtrVector< MCWalkerConfiguration > > WPoolClones_uptr
 
static std::vector< std::vector< MCWalkerConfiguration * > > WPoolClones
 
static std::vector< UPtrVector< TrialWaveFunction > > PsiPoolClones_uptr
 
static std::vector< std::vector< TrialWaveFunction * > > PsiPoolClones
 
static std::vector< UPtrVector< QMCHamiltonian > > HPoolClones_uptr
 
static std::vector< std::vector< QMCHamiltonian * > > HPoolClones
 

Constructor & Destructor Documentation

◆ VMC() [1/2]

VMC ( const ProjectData project_data_,
MCWalkerConfiguration w,
TrialWaveFunction psi,
QMCHamiltonian h,
UPtrVector< RandomBase< QMCTraits::FullPrecRealType >> &  rngs,
Communicate comm,
bool  enable_profiling 
)

Constructor.

Definition at line 40 of file VMC.cpp.

References ParameterSet::add(), QMCDriver::m_param, QMCDriver::nSteps, QMCDriver::nStepsBetweenSamples, VMC::prevSteps, VMC::prevStepsBetweenSamples, QMCDriver::qmc_driver_mode, QMCDriver::QMC_UPDATE_MODE, QMCDriver::QMC_WARMUP, QMCDriver::RootName, and VMC::UseDrift.

47  : QMCDriver(project_data, w, psi, h, comm, "VMC", enable_profiling), UseDrift("yes"), rngs_(rngs)
48 {
49  RootName = "vmc";
52  m_param.add(UseDrift, "useDrift");
53  m_param.add(UseDrift, "usedrift");
54  m_param.add(UseDrift, "use_drift");
55 
56  prevSteps = nSteps;
58 }
QMCDriver(const ProjectData &project_data, MCWalkerConfiguration &w, TrialWaveFunction &psi, QMCHamiltonian &h, Communicate *comm, const std::string &QMC_driver_type, bool enable_profiling=false)
Constructor.
Definition: QMCDriver.cpp:44
int prevSteps
Definition: VMC.h:40
std::string RootName
root of all the output files
Definition: QMCDriver.h:317
int prevStepsBetweenSamples
Definition: VMC.h:41
UPtrVector< RandomBase< QMCTraits::FullPrecRealType > > & rngs_
Definition: VMC.h:46
ParameterSet m_param
store any parameter that has to be read from a file
Definition: QMCDriver.h:320
IndexType nSteps
maximum number of steps
Definition: QMCDriver.h:269
std::bitset< QMC_MODE_MAX > qmc_driver_mode
bits to classify QMCDriver
Definition: QMCDriver.h:93
void add(PDT &aparam, const std::string &aname_in, std::vector< PDT > candidate_values={}, TagStatus status=TagStatus::OPTIONAL)
add a new parameter corresponding to an xmlNode <parameter>
IndexType nStepsBetweenSamples
alternate method of setting QMC run parameters
Definition: QMCDriver.h:291
std::string UseDrift
option to enable/disable drift equation or RN for VMC
Definition: VMC.h:44

◆ VMC() [2/2]

VMC ( const VMC )
privatedelete

copy constructor

Member Function Documentation

◆ getRunType()

QMCRunType getRunType ( )
inlineoverridevirtual

Implements QMCDriverInterface.

Definition at line 37 of file VMC.h.

References qmcplusplus::VMC.

37 { return QMCRunType::VMC; }
VMC type: vmc, vmc-ptcl, vmc-multiple, vmc-ptcl-multiple.

◆ operator=()

VMC& operator= ( const VMC )
privatedelete

Copy operator (disabled).

◆ put()

bool put ( xmlNodePtr  cur)
overridevirtual

Implements QMCDriverInterface.

Definition at line 298 of file VMC.cpp.

References ParameterSet::add(), qmcplusplus::app_log(), qmcplusplus::ceil(), QMCDriver::CurrentStep, QMCDriver::DumpConfig, ParameterSet::get(), WalkerConfigurations::getActiveWalkers(), QMCDriver::m_param, MPIObjectBase::myComm, QMCDriver::MyCounter, QMCDriver::nBlocks, QMCDriver::nSamplesPerThread, QMCDriver::nSteps, QMCDriver::nStepsBetweenSamples, QMCDriver::nSubSteps, QMCDriver::nTargetPopulation, QMCDriver::nTargetSamples, omp_get_max_threads(), QMCDriver::Period4CheckPoint, QMCDriver::Period4WalkerDump, VMC::prevSteps, VMC::prevStepsBetweenSamples, ParameterSet::put(), qmcplusplus::qmc_common, QMCState::qmc_counter, Communicate::size(), QMCDriver::Tau, and QMCDriver::W.

299 {
300  //grep minimumTargetWalker
301  int target_min = -1;
302  ParameterSet p;
303  p.add(target_min, "minimumtargetwalkers"); //p.add(target_min,"minimumTargetWalkers");
304  p.add(target_min, "minimumsamples"); //p.add(target_min,"minimumSamples");
305  p.put(q);
306 
307  app_log() << "\n<vmc function=\"put\">"
308  << "\n qmc_counter=" << qmc_common.qmc_counter << " my_counter=" << MyCounter << std::endl;
309 
310 
312  {
313  nSteps = prevSteps;
315  }
316  else
317  {
318  int nw = W.getActiveWalkers();
319  //compute samples and overwrite steps for the given samples
320  int Nthreads = omp_get_max_threads();
321  int Nprocs = myComm->size();
322 
323 
324  //target samples set by samples or samplesperthread/dmcwalkersperthread
325  nTargetPopulation = std::max(nTargetPopulation, nSamplesPerThread * Nprocs * Nthreads);
326  nTargetSamples = static_cast<int>(std::ceil(nTargetPopulation));
327 
328  if (nTargetSamples)
329  {
330  int nwtot = nw * Nprocs; //total number of walkers used by this qmcsection
331  nTargetSamples = std::max(nwtot, nTargetSamples);
332  if (target_min > 0)
333  {
334  nTargetSamples = std::max(nTargetSamples, target_min);
335  nTargetPopulation = std::max(nTargetPopulation, static_cast<RealType>(target_min));
336  }
337  nTargetSamples = ((nTargetSamples + nwtot - 1) / nwtot) *
338  nwtot; // nTargetSamples are always multiples of total number of walkers
339  nSamplesPerThread = nTargetSamples / Nprocs / Nthreads;
340  int ns_target = nTargetSamples * nStepsBetweenSamples; //total samples to generate
341  int ns_per_step = Nprocs * nw; //total samples per step
342  nSteps = std::max(nSteps, (ns_target / ns_per_step + nBlocks - 1) / nBlocks);
344  }
345  else
346  {
347  Period4WalkerDump = nStepsBetweenSamples = (nBlocks + 1) * nSteps; //some positive number, not used
348  nSamplesPerThread = 0;
349  }
350  }
351  prevSteps = nSteps;
353 
354  app_log() << " time step = " << Tau << std::endl;
355  app_log() << " blocks = " << nBlocks << std::endl;
356  app_log() << " steps = " << nSteps << std::endl;
357  app_log() << " substeps = " << nSubSteps << std::endl;
358  app_log() << " current = " << CurrentStep << std::endl;
359  app_log() << " target samples = " << nTargetPopulation << std::endl;
360  app_log() << " walkers/mpi = " << W.getActiveWalkers() << std::endl << std::endl;
361  app_log() << " stepsbetweensamples = " << nStepsBetweenSamples << std::endl;
362 
363  m_param.get(app_log());
364 
365  if (DumpConfig)
366  {
367  app_log() << " DumpConfig==true Configurations are dumped to config.h5 with a period of " << Period4CheckPoint
368  << " blocks" << std::endl;
369  }
370  else
371  {
372  app_log() << " DumpConfig==false Nothing (configurations, state) will be saved." << std::endl;
373  }
374 
375  if (Period4WalkerDump > 0)
376  app_log() << " Walker Samples are dumped every " << Period4WalkerDump << " steps." << std::endl;
377 
378  app_log() << "</vmc>" << std::endl;
379  app_log().flush();
380 
381  return true;
382 }
size_t getActiveWalkers() const
return the number of active walkers
int prevSteps
Definition: VMC.h:40
bool DumpConfig
flag to turn off dumping configurations
Definition: QMCDriver.h:226
std::ostream & app_log()
Definition: OutputManager.h:65
RealType nSamplesPerThread
samples per thread
Definition: QMCDriver.h:293
int prevStepsBetweenSamples
Definition: VMC.h:41
IndexType CurrentStep
current step
Definition: QMCDriver.h:263
int size() const
return the number of tasks
Definition: Communicate.h:118
bool put(std::istream &is) override
read from std::istream
Definition: ParameterSet.h:42
ParameterSet m_param
store any parameter that has to be read from a file
Definition: QMCDriver.h:320
IndexType nSubSteps
number of steps between a step: VMCs do not evaluate energies
Definition: QMCDriver.h:272
IndexType nSteps
maximum number of steps
Definition: QMCDriver.h:269
class to handle a set of parameters
Definition: ParameterSet.h:27
MakeReturn< UnaryNode< FnCeil, typename CreateLeaf< Vector< T1, C1 > >::Leaf_t > >::Expression_t ceil(const Vector< T1, C1 > &l)
omp_int_t omp_get_max_threads()
Definition: OpenMP.h:26
Communicate * myComm
pointer to Communicate
Definition: MPIObjectBase.h:62
bool get(std::ostream &os) const override
write to a std::ostream
Definition: ParameterSet.h:35
int qmc_counter
init for <qmc> section
Definition: qmc_common.h:31
MCWalkerConfiguration & W
walker ensemble
Definition: QMCDriver.h:323
void add(PDT &aparam, const std::string &aname_in, std::vector< PDT > candidate_values={}, TagStatus status=TagStatus::OPTIONAL)
add a new parameter corresponding to an xmlNode <parameter>
IndexType nTargetSamples
the number of saved samples
Definition: QMCDriver.h:289
int Period4CheckPoint
period of dumping walker configurations and everything else for restart
Definition: QMCDriver.h:242
RealType nTargetPopulation
target population
Definition: QMCDriver.h:295
RealType Tau
timestep
Definition: QMCDriver.h:299
IndexType nStepsBetweenSamples
alternate method of setting QMC run parameters
Definition: QMCDriver.h:291
IndexType nBlocks
maximum number of blocks
Definition: QMCDriver.h:266
int Period4WalkerDump
period of recording walker configurations
Definition: QMCDriver.h:255
QMCState qmc_common
a unique QMCState during a run
Definition: qmc_common.cpp:111
int MyCounter
the number of times this QMCDriver is executed
Definition: QMCDriver.h:235

◆ resetRun()

void resetRun ( )
private

check the run-time environments

Definition at line 153 of file VMC.cpp.

References qmcplusplus::app_log(), SimpleFixedNodeBranch::B_TARGETWALKERS, WalkerConfigurations::begin(), QMCDriver::branchEngine, qmcplusplus::ceil(), copy(), QMCDriver::DriftModifier, CloneManager::estimatorClones, QMCDriver::Estimators, FairDivideLow(), WalkerConfigurations::getActiveWalkers(), QMCDriver::H, CloneManager::hClones, ParticleSet::isSpinor(), CloneManager::makeClones(), QMCState::memory_allocated, CloneManager::Movers, QMCDriver::nSamplesPerThread, QMCDriver::nSubSteps, QMCDriver::nTargetPopulation, QMCDriver::nTargetSamples, CloneManager::NumThreads, QMCDriver::nWarmupSteps, QMCState::print_memory_change(), QMCDriver::Psi, CloneManager::psiClones, qmcplusplus::qmc_common, QMCDriver::qmc_driver_mode, QMCDriver::QMC_UPDATE_MODE, QMCDriver::qmcNode, QMCDriver::Rng, VMC::rngs_, QMCDriver::SpinMass, CloneManager::traceClones, QMCDriver::Traces, VMC::UseDrift, QMCDriver::W, CloneManager::wClones, CloneManager::wlog_collectors, QMCDriver::wlog_manager_, and CloneManager::wPerRank.

Referenced by VMC::run().

154 {
155  ////only VMC can overwrite this
156  if (nTargetPopulation > 0)
158  makeClones(W, Psi, H);
160  app_log() << " Initial partition of walkers ";
161  copy(wPerRank.begin(), wPerRank.end(), std::ostream_iterator<int>(app_log(), " "));
162  app_log() << std::endl;
163 
164  bool movers_created = false;
165  bool spinors = false;
166  if (Movers.empty())
167  {
168  movers_created = true;
169  Movers.resize(NumThreads, nullptr);
170  estimatorClones.resize(NumThreads, nullptr);
171  traceClones.resize(NumThreads, nullptr);
172  wlog_collectors.resize(NumThreads);
173  Rng.resize(NumThreads);
174 
175  // hdf_archive::hdf_archive() is not thread-safe
176  for (int ip = 0; ip < NumThreads; ++ip)
177  estimatorClones[ip] = new EstimatorManagerBase(*Estimators);
178 
179 #pragma omp parallel for
180  for (int ip = 0; ip < NumThreads; ++ip)
181  {
182  std::ostringstream os;
183  estimatorClones[ip]->resetTargetParticleSet(*wClones[ip]);
184  estimatorClones[ip]->setCollectionMode(false);
185 #if !defined(REMOVE_TRACEMANAGER)
186  traceClones[ip] = Traces->makeClone();
187 #endif
188  wlog_collectors[ip] = wlog_manager_->makeCollector();
189  Rng[ip] = rngs_[ip]->makeClone();
190  hClones[ip]->setRandomGenerator(Rng[ip].get());
191  if (W.isSpinor())
192  {
193  spinors = true;
195  {
196  Movers[ip] = new SOVMCUpdatePbyP(*wClones[ip], *psiClones[ip], *hClones[ip], *Rng[ip]);
197  }
198  else
199  {
200  Movers[ip] = new SOVMCUpdateAll(*wClones[ip], *psiClones[ip], *hClones[ip], *Rng[ip]);
201  }
202  }
203  else
204  {
206  {
207  Movers[ip] = new VMCUpdatePbyP(*wClones[ip], *psiClones[ip], *hClones[ip], *Rng[ip]);
208  }
209  else
210  {
211  Movers[ip] = new VMCUpdateAll(*wClones[ip], *psiClones[ip], *hClones[ip], *Rng[ip]);
212  }
213  }
214  Movers[ip]->nSubSteps = nSubSteps;
215  if (ip == 0)
216  app_log() << os.str() << std::endl;
217  }
218  }
219 #if !defined(REMOVE_TRACEMANAGER)
220  else
221  {
222 #pragma omp parallel for
223  for (int ip = 0; ip < NumThreads; ++ip)
224  traceClones[ip]->transfer_state_from(*Traces);
225  }
226 #endif
228  {
229  app_log() << " Using Particle by Particle moves" << std::endl;
230  }
231  else
232  {
233  app_log() << " Using All Particle moves" << std::endl;
234  }
235 
236  if (UseDrift == "yes")
237  {
238  app_log() << " Walker moves with drift" << std::endl;
239  for (int i = 0; i < Movers.size(); i++)
240  Movers[i]->UseDrift = true;
241  }
242  else
243  {
244  app_log() << " Walker moves without drift" << std::endl;
245  for (int i = 0; i < Movers.size(); i++)
246  Movers[i]->UseDrift = false;
247  }
248 
249  if (spinors)
250  {
251  app_log() << " Spins treated as dynamic variable with SpinMass: " << SpinMass << std::endl;
252  for (int i = 0; i < Movers.size(); i++)
253  Movers[i]->setSpinMass(SpinMass);
254  }
255 
256  app_log() << " Total Sample Size =" << nTargetSamples << std::endl;
257  app_log() << " Walker distribution on root = ";
258  copy(wPerRank.begin(), wPerRank.end(), std::ostream_iterator<int>(app_log(), " "));
259  app_log() << std::endl;
260  //app_log() << " Sample Size per node=" << samples_this_node << std::endl;
261  //for (int ip=0; ip<NumThreads; ++ip)
262  // app_log() << " Sample size for thread " <<ip<<" = " << samples_th[ip] << std::endl;
263  app_log().flush();
264 #pragma omp parallel for
265  for (int ip = 0; ip < NumThreads; ++ip)
266  {
267  //int ip=omp_get_thread_num();
268  Movers[ip]->put(qmcNode);
269  //Movers[ip]->resetRun(branchEngine.get(), estimatorClones[ip], traceClones[ip], DriftModifier);
270  Movers[ip]->resetRun2(branchEngine.get(), estimatorClones[ip], traceClones[ip], wlog_collectors[ip].get(), DriftModifier);
272  Movers[ip]->initWalkersForPbyP(W.begin() + wPerRank[ip], W.begin() + wPerRank[ip + 1]);
273  else
274  Movers[ip]->initWalkers(W.begin() + wPerRank[ip], W.begin() + wPerRank[ip + 1]);
275  // if (UseDrift != "rn")
276  // {
277  for (int prestep = 0; prestep < nWarmupSteps; ++prestep)
278  Movers[ip]->advanceWalkers(W.begin() + wPerRank[ip], W.begin() + wPerRank[ip + 1], false);
279  // }
280  }
281 
282  if (movers_created)
283  {
284  size_t before = qmc_common.memory_allocated;
285  app_log() << " Anonymous Buffer size per walker : " << W[0]->DataSet.byteSize() << " Bytes." << std::endl;
286  qmc_common.memory_allocated += W.getActiveWalkers() * W[0]->DataSet.byteSize();
287  qmc_common.print_memory_change("VMC::resetRun", before);
288  }
289 
290  for (int ip = 0; ip < NumThreads; ++ip)
291  wClones[ip]->clearEnsemble();
292  if (nSamplesPerThread)
293  for (int ip = 0; ip < NumThreads; ++ip)
294  wClones[ip]->setNumSamples(nSamplesPerThread);
295  nWarmupSteps = 0;
296 }
UPtrVector< WalkerLogCollector > wlog_collectors
trace collectors
Definition: CloneManager.h:79
static std::vector< TrialWaveFunction * > psiClones
Definition: CloneManager.h:65
std::vector< int > wPerRank
Walkers per MPI rank.
Definition: CloneManager.h:91
size_t getActiveWalkers() const
return the number of active walkers
static std::vector< MCWalkerConfiguration * > wClones
Definition: CloneManager.h:61
std::ostream & app_log()
Definition: OutputManager.h:65
RealType nSamplesPerThread
samples per thread
Definition: QMCDriver.h:293
xmlNodePtr qmcNode
pointer to qmc node in xml file
Definition: QMCDriver.h:310
std::vector< QMCUpdateBase * > Movers
update engines
Definition: CloneManager.h:73
RealType SpinMass
spin mass for spinor calcs
Definition: QMCDriver.h:353
UPtrVector< RandomBase< QMCTraits::FullPrecRealType > > & rngs_
Definition: VMC.h:46
std::unique_ptr< TraceManager > Traces
Traces manager.
Definition: QMCDriver.h:195
void FairDivideLow(int ntot, int npart, IV &adist)
partition ntot elements among npart
Definition: FairDivide.h:114
IndexType nSubSteps
number of steps between a step: VMCs do not evaluate energies
Definition: QMCDriver.h:272
void copy(const Array< T1, 3 > &src, Array< T2, 3 > &dest)
Definition: Blitz.h:639
MakeReturn< UnaryNode< FnCeil, typename CreateLeaf< Vector< T1, C1 > >::Leaf_t > >::Expression_t ceil(const Vector< T1, C1 > &l)
std::bitset< QMC_MODE_MAX > qmc_driver_mode
bits to classify QMCDriver
Definition: QMCDriver.h:93
std::unique_ptr< BranchEngineType > branchEngine
branch engine
Definition: QMCDriver.h:218
std::vector< EstimatorManagerBase * > estimatorClones
estimator managers
Definition: CloneManager.h:75
const IndexType NumThreads
number of threads
Definition: CloneManager.h:54
QMCHamiltonian & H
Hamiltonian.
Definition: QMCDriver.h:329
DriftModifierBase * DriftModifier
drift modifer
Definition: QMCDriver.h:220
void makeClones(MCWalkerConfiguration &w, TrialWaveFunction &psi, QMCHamiltonian &ham)
MCWalkerConfiguration & W
walker ensemble
Definition: QMCDriver.h:323
static std::vector< QMCHamiltonian * > hClones
Definition: CloneManager.h:71
IndexType nTargetSamples
the number of saved samples
Definition: QMCDriver.h:289
EstimatorManagerBase * Estimators
Observables manager.
Definition: QMCDriver.h:192
RealType nTargetPopulation
target population
Definition: QMCDriver.h:295
TrialWaveFunction & Psi
trial function
Definition: QMCDriver.h:326
size_t memory_allocated
size of memory allocated in byte per MPI
Definition: qmc_common.h:29
void print_memory_change(const std::string &who, size_t before)
print memory increase
Definition: qmc_common.cpp:93
std::vector< TraceManager * > traceClones
trace managers
Definition: CloneManager.h:77
QMCState qmc_common
a unique QMCState during a run
Definition: qmc_common.cpp:111
IndexType nWarmupSteps
number of warmup steps
Definition: QMCDriver.h:275
UPtrVector< RandomBase< FullPrecRealType > > Rng
Random number generators.
Definition: QMCDriver.h:341
std::unique_ptr< WalkerLogManager > wlog_manager_
Traces manager.
Definition: QMCDriver.h:198
target total number of walkers per mpi group
std::string UseDrift
option to enable/disable drift equation or RN for VMC
Definition: VMC.h:44
iterator begin()
return the first iterator

◆ run()

bool run ( )
overridevirtual

write samples to a file

Implements QMCDriverInterface.

Definition at line 60 of file VMC.cpp.

References qmcplusplus::app_log(), Communicate::bcast(), WalkerConfigurations::begin(), ParticleSet::Collectables, QMCDriver::CurrentStep, QMCDriver::DumpConfig, MCWalkerConfiguration::dumpEnsemble(), CloneManager::estimatorClones, QMCDriver::Estimators, QMCDriver::finalize(), Communicate::getName(), CloneManager::getWalkerLogCollectorRefs(), QMCDriver::MaxCPUSecs, CloneManager::Movers, MPIObjectBase::myComm, QMCDriver::nBlocks, QMCDriver::nBlocksBetweenRecompute, QMCDriver::nSteps, CloneManager::NumThreads, omp_get_thread_num(), QMCDriver::Period4CheckProperties, QMCDriver::Period4WalkerDump, QMCDriver::qmc_driver_mode, QMCDriver::QMC_UPDATE_MODE, Communicate::rank(), QMCDriver::recordBlock(), VMC::resetRun(), QMCDriver::Rng, VMC::rngs_, qmcplusplus::run_time_manager, PooledData< T >::size(), Communicate::size(), LoopTimer< CLOCK >::start(), EstimatorManagerBase::start(), LoopTimer< CLOCK >::stop(), EstimatorManagerBase::stop(), EstimatorManagerBase::stopBlock(), CloneManager::traceClones, QMCDriver::Traces, QMCDriver::W, CloneManager::wClones, QMCDriver::wlog_manager_, QMCDriver::wOut, and CloneManager::wPerRank.

Referenced by qmcplusplus::TEST_CASE().

61 {
62  resetRun();
63  //start the main estimator
65  for (int ip = 0; ip < NumThreads; ++ip)
66  Movers[ip]->startRun(nBlocks, false);
67 #if !defined(REMOVE_TRACEMANAGER)
68  Traces->startRun(nBlocks, traceClones);
69 #endif
71 
72  LoopTimer<> vmc_loop;
73  RunTimeControl<> runtimeControl(run_time_manager, MaxCPUSecs, myComm->getName(), myComm->rank() == 0);
74 
75  const bool has_collectables = W.Collectables.size();
76  for (int block = 0; block < nBlocks; ++block)
77  {
78  vmc_loop.start();
79 #pragma omp parallel
80  {
81  int ip = omp_get_thread_num();
82  //IndexType updatePeriod=(qmc_driver_mode[QMC_UPDATE_MODE])?Period4CheckProperties:(nBlocks+1)*nSteps;
84  //assign the iterators and resuse them
85  MCWalkerConfiguration::iterator wit(W.begin() + wPerRank[ip]), wit_end(W.begin() + wPerRank[ip + 1]);
86  Movers[ip]->startBlock(nSteps);
87  int now_loc = CurrentStep;
88  RealType cnorm = 1.0 / static_cast<RealType>(wPerRank[ip + 1] - wPerRank[ip]);
89  for (int step = 0; step < nSteps; ++step)
90  {
91  Movers[ip]->set_step(now_loc);
92  //collectables are reset, it is accumulated while advancing walkers
93  wClones[ip]->resetCollectables();
94  bool recompute = (nBlocksBetweenRecompute && (step + 1) == nSteps &&
96  Movers[ip]->advanceWalkers(wit, wit_end, recompute);
97  if (has_collectables)
98  wClones[ip]->Collectables *= cnorm;
99  Movers[ip]->accumulate(wit, wit_end);
100  ++now_loc;
101  if (Period4WalkerDump && now_loc % Period4WalkerDump == 0)
102  wClones[ip]->saveEnsemble(wit, wit_end);
103  // if(storeConfigs && (now_loc%storeConfigs == 0))
104  // ForwardWalkingHistory.storeConfigsForForwardWalking(*wClones[ip]);
105  }
106  Movers[ip]->stopBlock(false);
107  } //end-of-parallel for
108  //Estimators->accumulateCollectables(wClones,nSteps);
109  CurrentStep += nSteps;
111 #if !defined(REMOVE_TRACEMANAGER)
112  Traces->write_buffers(traceClones, block);
113 #endif
114  wlog_manager_->writeBuffers();
115  recordBlock(block);
116  vmc_loop.stop();
117 
118  bool stop_requested = false;
119  // Rank 0 decides whether the time limit was reached
120  if (!myComm->rank())
121  stop_requested = runtimeControl.checkStop(vmc_loop);
122  myComm->bcast(stop_requested);
123  if (stop_requested)
124  {
125  if (!myComm->rank())
126  app_log() << runtimeControl.generateStopMessage("VMC", block);
127  run_time_manager.markStop();
128  break;
129  }
130  } //block
132  for (int ip = 0; ip < NumThreads; ++ip)
133  Movers[ip]->stopRun2();
134 #if !defined(REMOVE_TRACEMANAGER)
135  Traces->stopRun();
136 #endif
137  wlog_manager_->stopRun();
138  //copy back the random states
139  for (int ip = 0; ip < NumThreads; ++ip)
140  rngs_[ip] = Rng[ip]->makeClone();
141  ///write samples to a file
142  bool wrotesamples = DumpConfig;
143  if (DumpConfig)
144  {
146  if (wrotesamples)
147  app_log() << " samples are written to the config.h5" << std::endl;
148  }
149  //finalize a qmc section
150  return finalize(nBlocks, !wrotesamples);
151 }
size_type size() const
return the size of the data
Definition: PooledData.h:48
int MaxCPUSecs
maximum cpu in secs
Definition: QMCDriver.h:302
std::vector< int > wPerRank
Walkers per MPI rank.
Definition: CloneManager.h:91
int rank() const
return the rank
Definition: Communicate.h:116
void recordBlock(int block) override
record the state of the block
Definition: QMCDriver.cpp:307
bool DumpConfig
flag to turn off dumping configurations
Definition: QMCDriver.h:226
static std::vector< MCWalkerConfiguration * > wClones
Definition: CloneManager.h:61
std::ostream & app_log()
Definition: OutputManager.h:65
RunTimeManager< ChronoClock > run_time_manager
IndexType CurrentStep
current step
Definition: QMCDriver.h:263
std::vector< QMCUpdateBase * > Movers
update engines
Definition: CloneManager.h:73
int size() const
return the number of tasks
Definition: Communicate.h:118
UPtrVector< RandomBase< QMCTraits::FullPrecRealType > > & rngs_
Definition: VMC.h:46
std::unique_ptr< TraceManager > Traces
Traces manager.
Definition: QMCDriver.h:195
omp_int_t omp_get_thread_num()
Definition: OpenMP.h:25
IndexType nSteps
maximum number of steps
Definition: QMCDriver.h:269
std::unique_ptr< HDFWalkerOutput > wOut
record engine for walkers
Definition: QMCDriver.h:332
bool finalize(int block, bool dumpwalkers=true)
finalize a qmc section
Definition: QMCDriver.cpp:318
const std::string & getName() const
Definition: Communicate.h:131
WalkerList_t::iterator iterator
FIX: a type alias of iterator for an object should not be for just one of many objects it holds...
std::bitset< QMC_MODE_MAX > qmc_driver_mode
bits to classify QMCDriver
Definition: QMCDriver.h:93
Communicate * myComm
pointer to Communicate
Definition: MPIObjectBase.h:62
std::vector< EstimatorManagerBase * > estimatorClones
estimator managers
Definition: CloneManager.h:75
const IndexType NumThreads
number of threads
Definition: CloneManager.h:54
MCWalkerConfiguration & W
walker ensemble
Definition: QMCDriver.h:323
OHMMS_INDEXTYPE IndexType
define other types
Definition: Configuration.h:65
Buffer_t Collectables
observables in addition to those registered in Properties/PropertyList
Definition: ParticleSet.h:126
static bool dumpEnsemble(std::vector< MCWalkerConfiguration *> &others, HDFWalkerOutput &out, int np, int nBlock)
dump Samples to a file
void resetRun()
check the run-time environments
Definition: VMC.cpp:153
QMCTraits::RealType RealType
EstimatorManagerBase * Estimators
Observables manager.
Definition: QMCDriver.h:192
void stopBlock(RealType accept, bool collectall=true)
stop a block
void bcast(T &)
IndexType nBlocks
maximum number of blocks
Definition: QMCDriver.h:266
int Period4WalkerDump
period of recording walker configurations
Definition: QMCDriver.h:255
std::vector< TraceManager * > traceClones
trace managers
Definition: CloneManager.h:77
int Period4CheckProperties
period of dumping walker positions and IDs for Forward Walking
Definition: QMCDriver.h:249
RefVector< WalkerLogCollector > getWalkerLogCollectorRefs()
UPtrVector< RandomBase< FullPrecRealType > > Rng
Random number generators.
Definition: QMCDriver.h:341
std::unique_ptr< WalkerLogManager > wlog_manager_
Traces manager.
Definition: QMCDriver.h:198
IndexType nBlocksBetweenRecompute
the number of blocks between recomptePsi
Definition: QMCDriver.h:284
void start(int blocks, bool record=true)
start a run
iterator begin()
return the first iterator

Member Data Documentation

◆ prevSteps

int prevSteps
private

Definition at line 40 of file VMC.h.

Referenced by VMC::put(), and VMC::VMC().

◆ prevStepsBetweenSamples

int prevStepsBetweenSamples
private

Definition at line 41 of file VMC.h.

Referenced by VMC::put(), and VMC::VMC().

◆ rngs_

Definition at line 46 of file VMC.h.

Referenced by VMC::resetRun(), and VMC::run().

◆ UseDrift

std::string UseDrift
private

option to enable/disable drift equation or RN for VMC

Definition at line 44 of file VMC.h.

Referenced by VMC::resetRun(), and VMC::VMC().

◆ qmcplusplus::VMCBatched

class qmcplusplus::VMCBatched


Implements a VMC using particle-by-particle move.

Threaded execution.

Definition at line 34 of file VMCBatched.h.

+ Inheritance diagram for VMCBatched:
+ Collaboration diagram for VMCBatched:

Public Types

using Base = QMCDriverNew
 
using FullPrecRealType = QMCTraits::FullPrecRealType
 
using PosType = QMCTraits::PosType
 
using ParticlePositions = PtclOnLatticeTraits::ParticlePos
 
- Public Types inherited from QMCDriverNew
enum  { QMC_UPDATE_MODE, QMC_MULTIPLE, QMC_OPTIMIZE, QMC_WARMUP }
 separate but similar to QMCModeEnum More...
 
using RealType = QMCTraits::RealType
 
using IndexType = QMCTraits::IndexType
 
using FullPrecRealType = QMCTraits::FullPrecRealType
 
using MCPWalker = MCPopulation::MCPWalker
 
using WFBuffer = MCPopulation::WFBuffer
 
using SetNonLocalMoveHandler = std::function< void(QMCHamiltonian &)>
 
- Public Types inherited from QMCDriverInterface
using BranchEngineType = SimpleFixedNodeBranch
 
using FullPrecRealType = QMCTraits::FullPrecRealType
 
- Public Types inherited from MPIObjectBase
using mpi_comm_type = Communicate::mpi_comm_type
 

Public Member Functions

 VMCBatched (const ProjectData &project_data, QMCDriverInput &&qmcdriver_input, const std::optional< EstimatorManagerInput > &global_emi, VMCDriverInput &&input, WalkerConfigurations &wc, MCPopulation &&pop, SampleStack &samples_, Communicate *comm)
 Constructor. More...
 
void process (xmlNodePtr node) override
 QMCDriverNew driver second (3rd, 4th...) stage of constructing a valid driver. More...
 
bool run () override
 Runs the actual VMC section. More...
 
auto getCDLW ()
 transitional interface on the way to better walker count adjustment handling. More...
 
void enable_sample_collection ()
 Enable collecting samples during the VMC run. More...
 
- Public Member Functions inherited from QMCDriverNew
 QMCDriverNew (const ProjectData &project_data, QMCDriverInput &&input, const std::optional< EstimatorManagerInput > &global_emi, WalkerConfigurations &wc, MCPopulation &&population, const std::string timer_prefix, Communicate *comm, const std::string &QMC_driver_type)
 Constructor. More...
 
 QMCDriverNew (QMCDriverNew &&)=default
 Move Constructor. More...
 
 QMCDriverNew (const QMCDriverNew &)=delete
 Copy Constructor (disabled). More...
 
QMCDriverNewoperator= (const QMCDriverNew &)=delete
 Copy operator (disabled). More...
 
 ~QMCDriverNew () override
 
bool putQMCInfo (xmlNodePtr cur)
 
void makeLocalWalkers (int nwalkers, RealType reserve)
 Adjust populations local walkers to this number. More...
 
DriftModifierBaseget_drift_modifier () const
 
void recordBlock (int block) override
 record the state of the block More...
 
bool finalize (int block, bool dumpwalkers=true)
 finalize a qmc section More...
 
IndexType current () const
 return current step More...
 
void setStatus (const std::string &aname, const std::string &h5name, bool append) override
 Set the status of the QMCDriver. More...
 
void add_H_and_Psi (QMCHamiltonian *h, TrialWaveFunction *psi) override
 
void createRngsStepContexts (int num_crowds)
 Creates Random Number generators for crowds and step contexts. More...
 
void putWalkers (std::vector< xmlNodePtr > &wset) override
 Read walker configurations from *.config.h5 files. More...
 
RefVector< RandomBase< FullPrecRealType > > getRngRefs () const
 
RandomBase< FullPrecRealType > & getRng (int i) override
 return the i-th random generator More...
 
std::string getEngineName () override
 intended for logging output and debugging you should base behavior on type preferably at compile time or if necessary at runtime using and protected by dynamic cast. More...
 
unsigned long getDriverMode () override
 
IndexType get_num_living_walkers () const
 
IndexType get_num_dead_walkers () const
 
const QMCDriverInputgetQMCDriverInput () const
 
bool put (xmlNodePtr cur) override
 
More...
 
void setUpdateMode (bool pbyp) override
 should be set in input don't see a reason to set individually More...
 
void putTraces (xmlNodePtr txml) override
 
void requestTraces (bool allow_traces) override
 
void putWalkerLogs (xmlNodePtr wlxml) override
 
void requestWalkerLogs (bool allow_walker_logs_) override
 
- Public Member Functions inherited from QMCDriverInterface
virtual ~QMCDriverInterface ()
 
virtual void setBranchEngine (std::unique_ptr< BranchEngineType > &&be)
 
virtual std::unique_ptr< BranchEngineTypegetBranchEngine ()
 
- Public Member Functions inherited from MPIObjectBase
 MPIObjectBase (Communicate *c)
 constructor with communicator More...
 
int rank () const
 return the rank of the communicator More...
 
int getGroupID () const
 return the group id of the communicator More...
 
CommunicategetCommunicator () const
 return myComm More...
 
CommunicategetCommRef () const
 return a TEMPORARY reference to Communicate More...
 
mpi_comm_type getMPI () const
 return MPI communicator if one wants to use MPI directly More...
 
bool is_manager () const
 return true if the rank == 0 More...
 
const std::string & getName () const
 return the name More...
 
void setName (const std::string &aname)
 

Static Public Member Functions

template<CoordsType CT>
static void advanceWalkers (const StateForThread &sft, Crowd &crowd, DriverTimers &timers, ContextForSteps &move_context, bool recompute, bool accumulate_this_step)
 Refactor of VMCUpdatePbyP in crowd context. More...
 
static void runVMCStep (int crowd_id, const StateForThread &sft, DriverTimers &timers, UPtrVector< ContextForSteps > &context_for_steps, UPtrVector< Crowd > &crowds)
 Thread body for VMC step. More...
 
- Static Public Member Functions inherited from QMCDriverNew
static void initialLogEvaluation (int crowd_id, UPtrVector< Crowd > &crowds, UPtrVector< ContextForSteps > &step_context)
 
template<typename RT , CoordsType CT>
static void scaleBySqrtTau (const TauParams< RT, CT > &taus, MCCoords< CT > &coords)
 
template<typename RT , CoordsType CT>
static void computeLogGreensFunction (const MCCoords< CT > &coords, const TauParams< RT, CT > &taus, std::vector< QMCTraits::RealType > &log_gb)
 calculates Green Function from displacements stored in MCCoords [param, out] log_g More...
 

Private Member Functions

QMCRunType getRunType () override
 
 VMCBatched (const VMCBatched &)=delete
 Copy constructor. More...
 
VMCBatchedoperator= (const VMCBatched &)=delete
 Copy operator (disabled). More...
 

Static Private Member Functions

static size_t compute_samples_per_rank (const size_t num_blocks, const size_t samples_per_block, const size_t local_walkers)
 function to calculate samples per MPI rank More...
 

Private Attributes

int prevSteps
 
int prevStepsBetweenSamples
 
VMCDriverInput vmcdriver_input_
 
SampleStacksamples_
 Storage for samples (later used in optimizer) More...
 
bool collect_samples_
 Sample collection flag. More...
 

Friends

class qmcplusplus::testing::VMCBatchedTest
 

Additional Inherited Members

- Public Attributes inherited from QMCDriverNew
std::bitset< QMC_MODE_MAXqmc_driver_mode_
 bits to classify QMCDriver More...
 
bool allow_walker_logs
 whether to allow walker logs More...
 
WalkerLogInput walker_logs_input
 walker logs input More...
 
- Protected Member Functions inherited from QMCDriverNew
void initializeQMC (const AdjustedWalkerCounts &awc)
 Do common section starting tasks for VMC and DMC. More...
 
void measureImbalance (const std::string &tag) const
 inject additional barrier and measure load imbalance. More...
 
void endBlock ()
 end of a block operations. Aggregates statistics across all MPI ranks and write to disk. More...
 
const std::string & get_root_name () const override
 
- Static Protected Member Functions inherited from QMCDriverNew
static QMCDriverNew::AdjustedWalkerCounts adjustGlobalWalkerCount (Communicate &comm, const IndexType current_configs, const IndexType requested_total_walkers, const IndexType requested_walkers_per_rank, const RealType reserve_walkers, int num_crowds)
 }@ More...
 
static size_t determineStepsPerBlock (IndexType global_walkers, IndexType requested_samples, IndexType requested_steps, IndexType blocks)
 pure function calculating the actual number of steps per block More...
 
static void checkNumCrowdsLTNumThreads (const int num_crowds)
 
static void checkLogAndGL (Crowd &crowd, const std::string_view location)
 check logpsi and grad and lap against values computed from scratch More...
 
static void setWalkerOffsets (WalkerConfigurations &, Communicate *comm)
 update the global offsets of walker configurations after active walkers being touched. More...
 
- Protected Attributes inherited from QMCDriverNew
QMCDriverInput qmcdriver_input_
 
RealType max_disp_sq_
 
they should be limited to values that can be changed from input or are live state. More...
 
IndexType target_samples_
 the number of saved samples More...
 
IndexType nBlocksBetweenRecompute
 the number of blocks between recomptePsi More...
 
UPtrVector< Crowdcrowds_
 }@ More...
 
std::string h5_file_root_
 
std::unique_ptr< DriftModifierBasedrift_modifier_
 drift modifer More...
 
int k_delay
 the number to delay updates by More...
 
int walker_dump_period
 period of recording walker configurations More...
 
IndexType current_step_
 
size_t steps_per_block_ = 0
 actual number of steps per block More...
 
IndexType nAccept
 counter for number of moves accepted More...
 
IndexType nReject
 counter for number of moves /rejected More...
 
RealType m_oneover2tau
 Time-step factor $ 1/(2\tau)$. More...
 
RealType m_sqrttau
 Time-step factor $ \sqrt{\tau}$. More...
 
const std::string QMCType
 type of qmc: assigned by subclasses More...
 
MCPopulation population_
 the entire (on node) walker population it serves VMCBatch and DMCBatch right now but will be polymorphic More...
 
struct DriverWalkerResourceCollection golden_resource_
 the golden multi walker shared resource serves ParticleSet TrialWaveFunction right now but actually should be based on MCPopulation. More...
 
const MultiWalkerDispatchers dispatchers_
 multi walker dispatchers More...
 
std::unique_ptr< EstimatorManagerNewestimator_manager_
 Observables manager Has very problematic owner ship and life cycle. More...
 
std::unique_ptr< HDFWalkerOutputwOut
 record engine for walkers More...
 
UPtrVector< ContextForStepsstep_contexts_
 Per crowd move contexts, this is where the DistanceTables etc. More...
 
UPtrVector< RandomBase< FullPrecRealType > > Rng
 Random number generators. More...
 
std::vector< xmlNodePtr > mcwalkerNodePtr
 a list of mcwalkerset element More...
 
DriverTimers timers_
 period of dumping walker configurations and everything else for restart More...
 
ScopedProfiler driver_scope_profiler_
 profile the driver lifetime More...
 
const ProjectDataproject_data_
 project info for accessing global fileroot and series id More...
 
WalkerConfigurationswalker_configs_ref_
 
- Protected Attributes inherited from MPIObjectBase
CommunicatemyComm
 pointer to Communicate More...
 
std::string ClassName
 class Name More...
 
std::string myName
 name of the object More...
 

Member Typedef Documentation

◆ Base

using Base = QMCDriverNew

Definition at line 37 of file VMCBatched.h.

◆ FullPrecRealType

Definition at line 38 of file VMCBatched.h.

◆ ParticlePositions

◆ PosType

Definition at line 39 of file VMCBatched.h.

Constructor & Destructor Documentation

◆ VMCBatched() [1/2]

VMCBatched ( const ProjectData project_data,
QMCDriverInput &&  qmcdriver_input,
const std::optional< EstimatorManagerInput > &  global_emi,
VMCDriverInput &&  input,
WalkerConfigurations wc,
MCPopulation &&  pop,
SampleStack samples_,
Communicate comm 
)

Constructor.

Constructor maintains proper ownership of input parameters.

Definition at line 30 of file VMCBatched.cpp.

38  : QMCDriverNew(project_data,
39  std::move(qmcdriver_input),
40  global_emi,
41  wc,
42  std::move(pop),
43  "VMCBatched::",
44  comm,
45  "VMCBatched"),
47  samples_(samples),
48  collect_samples_(false)
49 {}
QMCDriverNew(const ProjectData &project_data, QMCDriverInput &&input, const std::optional< EstimatorManagerInput > &global_emi, WalkerConfigurations &wc, MCPopulation &&population, const std::string timer_prefix, Communicate *comm, const std::string &QMC_driver_type)
Constructor.
bool collect_samples_
Sample collection flag.
Definition: VMCBatched.h:135
SampleStack & samples_
Storage for samples (later used in optimizer)
Definition: VMCBatched.h:133
VMCDriverInput vmcdriver_input_
Definition: VMCBatched.h:124
testing::ValidSpinDensityInput input

◆ VMCBatched() [2/2]

VMCBatched ( const VMCBatched )
privatedelete

Copy constructor.

Member Function Documentation

◆ advanceWalkers()

void advanceWalkers ( const StateForThread sft,
Crowd crowd,
QMCDriverNew::DriverTimers timers,
ContextForSteps move_context,
bool  recompute,
bool  accumulate_this_step 
)
static

Refactor of VMCUpdatePbyP in crowd context.

MCWalkerConfiguration layer removed. Obfuscation of state changes via buffer and MCWalkerconfiguration require this be tested well

Definition at line 52 of file VMCBatched.cpp.

References QMCHamiltonian::auxHevaluate(), QMCDriverNew::DriverTimers::buffer_timer, qmcplusplus::CHECKGL_AFTER_LOAD, qmcplusplus::CHECKGL_AFTER_MOVES, QMCDriverNew::checkLogAndGL(), QMCDriverNew::DriverTimers::collectables_timer, QMCDriverNew::computeLogGreensFunction(), qmcplusplus::crowd, VMCBatched::StateForThread::drift_modifier, QMCDriverNew::DriverTimers::estimators_timer, qmcplusplus::exp(), QMCDriverInput::get_debug_checks(), MCPopulation::get_ptclgrp_inv_mass(), ContextForSteps::get_random_gen(), QMCDriverInput::get_spin_mass(), QMCDriverInput::get_sub_steps(), QMCDriverInput::get_tau(), VMCDriverInput::get_use_drift(), DriftModifierBase::getDrifts(), VMCBatched::StateForThread::global_step, qmcplusplus::ham, QMCDriverNew::DriverTimers::hamiltonian_timer, qmcplusplus::makeGaussRandomWithEngine(), QMCDriverNew::DriverTimers::movepbyp_timer, norm(), qmcplusplus::hdf::num_walkers, VMCBatched::StateForThread::population, qmcplusplus::pset, VMCBatched::StateForThread::qmcdrv_input, QMCDriverNew::DriverTimers::resource_timer, QMCHamiltonian::saveProperty(), QMCDriverNew::scaleBySqrtTau(), TimerType< CLOCK >::start(), TimerType< CLOCK >::stop(), qmcplusplus::twf, VMCBatched::StateForThread::vmcdrv_input, qmcplusplus::walker, and qmcplusplus::hdf::walkers.

58 {
59  if (crowd.size() == 0)
60  return;
61  auto& ps_dispatcher = crowd.dispatchers_.ps_dispatcher_;
62  auto& twf_dispatcher = crowd.dispatchers_.twf_dispatcher_;
63  auto& ham_dispatcher = crowd.dispatchers_.ham_dispatcher_;
64  auto& walkers = crowd.get_walkers();
65  const RefVectorWithLeader<ParticleSet> walker_elecs(crowd.get_walker_elecs()[0], crowd.get_walker_elecs());
66  const RefVectorWithLeader<TrialWaveFunction> walker_twfs(crowd.get_walker_twfs()[0], crowd.get_walker_twfs());
67 
68  // This is really a waste the resources can be acquired outside of the run steps loop in VMCD!
69  // I don't see an easy way to measure the release without putting the weight of tons of timer_manager calls in
70  // ResourceCollectionTeamLock's constructor.
71  timers.resource_timer.start();
72  ResourceCollectionTeamLock<ParticleSet> pset_res_lock(crowd.getSharedResource().pset_res, walker_elecs);
73  ResourceCollectionTeamLock<TrialWaveFunction> twfs_res_lock(crowd.getSharedResource().twf_res, walker_twfs);
74  timers.resource_timer.stop();
75  if (sft.qmcdrv_input.get_debug_checks() & DriverDebugChecks::CHECKGL_AFTER_LOAD)
76  checkLogAndGL(crowd, "checkGL_after_load");
77 
78  {
79  ScopedTimer pbyp_local_timer(timers.movepbyp_timer);
80  const int num_walkers = crowd.size();
81  auto& walker_leader = walker_elecs.getLeader();
82  const int num_particles = walker_leader.getTotalNum();
83  // Note std::vector<bool> is not like the rest of stl.
84  std::vector<bool> moved(num_walkers, false);
85  constexpr RealType mhalf(-0.5);
86  const bool use_drift = sft.vmcdrv_input.get_use_drift();
87 
88  std::vector<TrialWaveFunction::PsiValue> ratios(num_walkers);
89  std::vector<RealType> log_gf(num_walkers);
90  std::vector<RealType> log_gb(num_walkers);
91  std::vector<RealType> prob(num_walkers);
92 
93  // local list to handle accept/reject
94  std::vector<bool> isAccepted;
95  std::vector<std::reference_wrapper<TrialWaveFunction>> twf_accept_list, twf_reject_list;
96  isAccepted.reserve(num_walkers);
97 
98  MCCoords<CT> drifts(num_walkers), drifts_reverse(num_walkers);
99  MCCoords<CT> walker_deltas(num_walkers * num_particles), deltas(num_walkers);
100  TWFGrads<CT> grads_now(num_walkers), grads_new(num_walkers);
101 
102  for (int sub_step = 0; sub_step < sft.qmcdrv_input.get_sub_steps(); sub_step++)
103  {
104  //This generates an entire steps worth of deltas.
105  makeGaussRandomWithEngine(walker_deltas, step_context.get_random_gen());
106 
107  // up and down electrons are "species" within qmpack
108  for (int ig = 0; ig < walker_leader.groups(); ++ig) //loop over species
109  {
110  TauParams<RealType, CT> taus(sft.qmcdrv_input.get_tau(), sft.population.get_ptclgrp_inv_mass()[ig],
111  sft.qmcdrv_input.get_spin_mass());
112 
113  twf_dispatcher.flex_prepareGroup(walker_twfs, walker_elecs, ig);
114 
115  for (int iat = walker_leader.first(ig); iat < walker_leader.last(ig); ++iat)
116  {
117  //get deltas for this particle (iat) for all walkers
118  walker_deltas.getSubset(iat * num_walkers, num_walkers, deltas);
119  scaleBySqrtTau(taus, deltas);
120 
121  if (use_drift)
122  {
123  twf_dispatcher.flex_evalGrad(walker_twfs, walker_elecs, iat, grads_now);
124  sft.drift_modifier.getDrifts(taus, grads_now, drifts);
125  drifts += deltas;
126  }
127  else
128  drifts = deltas;
129 
130  ps_dispatcher.flex_makeMove(walker_elecs, iat, drifts);
131 
132  // This is inelegant
133  if (use_drift)
134  {
135  twf_dispatcher.flex_calcRatioGrad(walker_twfs, walker_elecs, iat, ratios, grads_new);
136 
137  computeLogGreensFunction(deltas, taus, log_gf);
138 
139  sft.drift_modifier.getDrifts(taus, grads_new, drifts_reverse);
140 
141  drifts_reverse += drifts;
142 
143  computeLogGreensFunction(drifts_reverse, taus, log_gb);
144  }
145  else
146  twf_dispatcher.flex_calcRatio(walker_twfs, walker_elecs, iat, ratios);
147 
148  std::transform(ratios.begin(), ratios.end(), prob.begin(), [](auto ratio) { return std::norm(ratio); });
149 
150  isAccepted.clear();
151 
152  for (int i_accept = 0; i_accept < num_walkers; ++i_accept)
153  if (prob[i_accept] >= std::numeric_limits<RealType>::epsilon() &&
154  step_context.get_random_gen()() < prob[i_accept] * std::exp(log_gb[i_accept] - log_gf[i_accept]))
155  {
156  crowd.incAccept();
157  isAccepted.push_back(true);
158  }
159  else
160  {
161  crowd.incReject();
162  isAccepted.push_back(false);
163  }
164 
165  twf_dispatcher.flex_accept_rejectMove(walker_twfs, walker_elecs, iat, isAccepted, true);
166 
167  ps_dispatcher.flex_accept_rejectMove<CT>(walker_elecs, iat, isAccepted);
168  }
169  }
170  twf_dispatcher.flex_completeUpdates(walker_twfs);
171  }
172 
173  ps_dispatcher.flex_donePbyP(walker_elecs);
174  }
175 
176  {
177  ScopedTimer buffer_local_timer(timers.buffer_timer);
178  twf_dispatcher.flex_evaluateGL(walker_twfs, walker_elecs, recompute);
179  if (sft.qmcdrv_input.get_debug_checks() & DriverDebugChecks::CHECKGL_AFTER_MOVES)
180  checkLogAndGL(crowd, "checkGL_after_moves");
181  }
182 
183  const RefVectorWithLeader<QMCHamiltonian> walker_hamiltonians(crowd.get_walker_hamiltonians()[0],
184  crowd.get_walker_hamiltonians());
185  {
186  ScopedTimer hamiltonian_local_timer(timers.hamiltonian_timer);
187  ResourceCollectionTeamLock<QMCHamiltonian> hams_res_lock(crowd.getSharedResource().ham_res, walker_hamiltonians);
188  std::vector<QMCHamiltonian::FullPrecRealType> local_energies(
189  ham_dispatcher.flex_evaluate(walker_hamiltonians, walker_twfs, walker_elecs));
190 
191  auto resetSigNLocalEnergy = [](MCPWalker& walker, TrialWaveFunction& twf, auto& local_energy) {
192  walker.resetProperty(twf.getLogPsi(), twf.getPhase(), local_energy);
193  };
194  for (int iw = 0; iw < crowd.size(); ++iw)
195  resetSigNLocalEnergy(walkers[iw], walker_twfs[iw], local_energies[iw]);
196  }
197 
198  {
199  ScopedTimer collectables_local_timer(timers.collectables_timer);
200  auto evaluateNonPhysicalHamiltonianElements = [](QMCHamiltonian& ham, ParticleSet& pset, MCPWalker& walker) {
202  };
203  for (int iw = 0; iw < crowd.size(); ++iw)
204  evaluateNonPhysicalHamiltonianElements(walker_hamiltonians[iw], walker_elecs[iw], walkers[iw]);
205 
206  auto savePropertiesIntoWalker = [](QMCHamiltonian& ham, MCPWalker& walker) {
207  ham.saveProperty(walker.getPropertyBase());
208  };
209  for (int iw = 0; iw < crowd.size(); ++iw)
210  savePropertiesIntoWalker(walker_hamiltonians[iw], walkers[iw]);
211  }
212 
213  if (accumulate_this_step)
214  {
215  ScopedTimer est_timer(timers.estimators_timer);
216  crowd.accumulate(step_context.get_random_gen());
217  }
218 
219  // collect walker logs
220  crowd.collectStepWalkerLog(sft.global_step);
221 
222  // TODO:
223  // check if all moves failed
224 }
void saveProperty(IT first)
save the values of Hamiltonian elements to the Properties
const char num_walkers[]
Definition: HDFVersion.h:37
static void scaleBySqrtTau(const TauParams< RT, CT > &taus, MCCoords< CT > &coords)
Definition: QMCDriverNew.h:257
ScopeGuard< NewTimer > ScopedTimer
Definition: NewTimer.h:257
MCPopulation::MCPWalker MCPWalker
Definition: QMCDriverNew.h:93
const char walkers[]
Definition: HDFVersion.h:36
double norm(const zVec &c)
Definition: VectorOps.h:118
static void computeLogGreensFunction(const MCCoords< CT > &coords, const TauParams< RT, CT > &taus, std::vector< QMCTraits::RealType > &log_gb)
calculates Green Function from displacements stored in MCCoords [param, out] log_g ...
Definition: QMCDriverNew.h:270
MakeReturn< UnaryNode< FnExp, typename CreateLeaf< Vector< T1, C1 > >::Leaf_t > >::Expression_t exp(const Vector< T1, C1 > &l)
static void checkLogAndGL(Crowd &crowd, const std::string_view location)
check logpsi and grad and lap against values computed from scratch
void auxHevaluate(ParticleSet &P)
QMCTraits::RealType RealType
void makeGaussRandomWithEngine(ParticleAttrib< TinyVector< T, D >> &a, RG &rng)

◆ compute_samples_per_rank()

size_t compute_samples_per_rank ( const size_t  num_blocks,
const size_t  samples_per_block,
const size_t  local_walkers 
)
staticprivate

function to calculate samples per MPI rank

Definition at line 287 of file VMCBatched.cpp.

References qmcplusplus::hdf::num_blocks.

Referenced by VMCBatched::enable_sample_collection().

290 {
291  return num_blocks * samples_per_block * local_walkers;
292 }
const char num_blocks[]
Definition: HDFVersion.h:44

◆ enable_sample_collection()

void enable_sample_collection ( )

Enable collecting samples during the VMC run.

strong assumption that VMCBatched driver has passed through process phase of initialization. A side effect of VMCBatched::process is that MCPopulation has created local walkers.

Definition at line 463 of file VMCBatched.cpp.

References qmcplusplus::app_log(), VMCBatched::collect_samples_, VMCBatched::compute_samples_per_rank(), QMCDriverInput::get_max_blocks(), MCPopulation::get_num_local_walkers(), MCPopulation::get_num_ranks(), QMCDriverNew::population_, QMCDriverNew::qmcdriver_input_, VMCBatched::samples_, SampleStack::setMaxSamples(), and QMCDriverNew::steps_per_block_.

464 {
465  assert(steps_per_block_ > 0 && "VMCBatched::enable_sample_collection steps_per_block_ must be positive!");
469  collect_samples_ = true;
470 
471  auto total_samples = samples * population_.get_num_ranks();
472  app_log() << "VMCBatched Driver collecting samples, samples per rank = " << samples << std::endl
473  << " total samples = " << total_samples << std::endl
474  << std::endl;
475 }
size_t steps_per_block_
actual number of steps per block
Definition: QMCDriverNew.h:407
MCPopulation population_
the entire (on node) walker population it serves VMCBatch and DMCBatch right now but will be polymorp...
Definition: QMCDriverNew.h:426
std::ostream & app_log()
Definition: OutputManager.h:65
int get_num_ranks() const
The number of cases in which this and get_num_local_walkers is so few that I strongly suspect it is a...
Definition: MCPopulation.h:166
bool collect_samples_
Sample collection flag.
Definition: VMCBatched.h:135
void setMaxSamples(size_t n, size_t number_of_ranks=1)
set the number of max samples per rank.
Definition: SampleStack.cpp:23
SampleStack & samples_
Storage for samples (later used in optimizer)
Definition: VMCBatched.h:133
IndexType get_max_blocks() const
QMCDriverInput qmcdriver_input_
Definition: QMCDriverNew.h:372
IndexType get_num_local_walkers() const
Definition: MCPopulation.h:169
static size_t compute_samples_per_rank(const size_t num_blocks, const size_t samples_per_block, const size_t local_walkers)
function to calculate samples per MPI rank
Definition: VMCBatched.cpp:287

◆ getCDLW()

auto getCDLW ( )

transitional interface on the way to better walker count adjustment handling.

returns a closure taking walkers per rank and accomplishing what calc_default_local_walkers does.

◆ getRunType()

QMCRunType getRunType ( )
inlineoverrideprivatevirtual

Implements QMCDriverInterface.

Definition at line 125 of file VMCBatched.h.

References qmcplusplus::VMC_BATCH.

◆ operator=()

VMCBatched& operator= ( const VMCBatched )
privatedelete

Copy operator (disabled).

◆ process()

void process ( xmlNodePtr  cur)
overridevirtual

QMCDriverNew driver second (3rd, 4th...) stage of constructing a valid driver.

This is the shared entry point with legacy, from QMCMain so the API cannot be updated yet

Todo:
remove cur, the driver and all its child nodes should be completely processed before this stage of driver initialization is hit.

Implements QMCDriverNew.

Definition at line 265 of file VMCBatched.cpp.

References QMCDriverNew::adjustGlobalWalkerCount(), qmcplusplus::app_log(), Communicate::barrier_and_abort(), QMCDriverNew::determineStepsPerBlock(), QMCDriverInput::get_max_blocks(), QMCDriverInput::get_num_crowds(), QMCDriverInput::get_requested_samples(), QMCDriverInput::get_requested_steps(), QMCDriverInput::get_total_walkers(), QMCDriverInput::get_walkers_per_rank(), WalkerConfigurations::getActiveWalkers(), QMCDriverNew::AdjustedWalkerCounts::global_walkers, QMCDriverNew::initializeQMC(), MPIObjectBase::myComm, qmcplusplus::print_mem(), QMCDriverNew::qmcdriver_input_, QMCDriverNew::steps_per_block_, and QMCDriverNew::walker_configs_ref_.

266 {
267  print_mem("VMCBatched before initialization", app_log());
268  // \todo get total walkers should be coming from VMCDriverInpu
269  try
270  {
271  QMCDriverNew::AdjustedWalkerCounts awc =
274 
278 
279  Base::initializeQMC(awc);
280  }
281  catch (const UniformCommunicateError& ue)
282  {
283  myComm->barrier_and_abort(ue.what());
284  }
285 }
size_t steps_per_block_
actual number of steps per block
Definition: QMCDriverNew.h:407
size_t getActiveWalkers() const
return the number of active walkers
IndexType get_requested_steps() const
std::ostream & app_log()
Definition: OutputManager.h:65
void print_mem(const std::string &title, std::ostream &log)
Definition: MemoryUsage.cpp:30
IndexType get_num_crowds() const
static size_t determineStepsPerBlock(IndexType global_walkers, IndexType requested_samples, IndexType requested_steps, IndexType blocks)
pure function calculating the actual number of steps per block
IndexType get_total_walkers() const
IndexType get_walkers_per_rank() const
WalkerConfigurations & walker_configs_ref_
Definition: QMCDriverNew.h:481
Communicate * myComm
pointer to Communicate
Definition: MPIObjectBase.h:62
static QMCDriverNew::AdjustedWalkerCounts adjustGlobalWalkerCount(Communicate &comm, const IndexType current_configs, const IndexType requested_total_walkers, const IndexType requested_walkers_per_rank, const RealType reserve_walkers, int num_crowds)
}@
IndexType get_max_blocks() const
void barrier_and_abort(const std::string &msg) const
QMCDriverInput qmcdriver_input_
Definition: QMCDriverNew.h:372
IndexType get_requested_samples() const
void initializeQMC(const AdjustedWalkerCounts &awc)
Do common section starting tasks for VMC and DMC.

◆ run()

bool run ( )
overridevirtual

Runs the actual VMC section.

Dependent on base class state machine Assumes state already updated from the following calls:

  1. QMCDriverNew::setStatus
  2. QMCDriverNew::putWalkers
  3. QMCDriverNew::process

At the moment I don't care about 1st touch, prove it matters If does consider giving more to the thread by value that should end up thread local. (I think)

Implements QMCDriverInterface.

Definition at line 307 of file VMCBatched.cpp.

References QMCDriverNew::allow_walker_logs, qmcplusplus::app_debug_stream(), qmcplusplus::app_log(), qmcplusplus::app_summary(), SampleStack::appendSample(), Communicate::barrier(), Communicate::bcast(), VMCBatched::collect_samples_, qmcplusplus::crowd, QMCDriverNew::crowds_, QMCDriverNew::drift_modifier_, Timer::elapsed(), QMCDriverNew::endBlock(), QMCDriverNew::estimator_manager_, QMCDriverNew::finalize(), QMCDriverInput::get_blocks_between_recompute(), MCPopulation::get_elec_particle_sets(), QMCDriverInput::get_max_blocks(), QMCDriverInput::get_measure_imbalance(), QMCDriverInput::get_recalculate_properties_period(), QMCDriverNew::get_root_name(), QMCDriverInput::get_tau(), QMCDriverInput::get_warmup_steps(), ProjectData::getMaxCPUSeconds(), ProjectData::getSeriesIndex(), ProjectData::getTitle(), Crowd::getWalkerLogCollectorRefs(), VMCBatched::StateForThread::global_step, QMCDriverNew::DriverTimers::init_walkers_timer, QMCDriverNew::initialLogEvaluation(), VMCBatched::StateForThread::is_recomputing_block, WalkerLogManager::makeCollector(), QMCDriverNew::measureImbalance(), MPIObjectBase::myComm, qmcplusplus::hdf::num_blocks, QMCDriverNew::population_, qmcplusplus::print_mem(), QMCDriverNew::DriverTimers::production_timer, QMCDriverNew::project_data_, QMCDriverNew::qmc_driver_mode_, QMCDriverNew::QMC_UPDATE_MODE, QMCDriverNew::qmcdriver_input_, Communicate::rank(), VMCBatched::StateForThread::recalculate_properties_period, QMCDriverNew::recordBlock(), QMCDriverNew::DriverTimers::run_steps_timer, qmcplusplus::run_time_manager, VMCBatched::runVMCStep(), VMCBatched::samples_, WalkerLogManager::startRun(), VMCBatched::StateForThread::step, QMCDriverNew::step_contexts_, QMCDriverNew::steps_per_block_, WalkerLogManager::stopRun(), QMCDriverNew::timers_, VMCBatched::vmcdriver_input_, qmcplusplus::walker, QMCDriverNew::walker_logs_input, and WalkerLogManager::writeBuffers().

308 {
310  //start the main estimator
311  estimator_manager_->startDriverRun();
312 
313  //initialize WalkerLogManager and collectors
314  WalkerLogManager wlog_manager(walker_logs_input, allow_walker_logs, get_root_name(), myComm);
315  for (auto& crowd : crowds_)
316  crowd->setWalkerLogCollector(wlog_manager.makeCollector());
317  //register walker log collectors into the manager
318  wlog_manager.startRun(Crowd::getWalkerLogCollectorRefs(crowds_));
319 
321 
322  LoopTimer<> vmc_loop;
323  RunTimeControl<> runtimeControl(run_time_manager, project_data_.getMaxCPUSeconds(), project_data_.getTitle(),
324  myComm->rank() == 0);
325 
326  { // walker initialization
328  ParallelExecutor<> section_start_task;
329  section_start_task(crowds_.size(), initialLogEvaluation, std::ref(crowds_), std::ref(step_contexts_));
330  print_mem("VMCBatched after initialLogEvaluation", app_summary());
332  measureImbalance("InitialLogEvaluation");
333  }
334 
335  ScopedTimer local_timer(timers_.production_timer);
336  ParallelExecutor<> crowd_task;
337 
339  {
340  // Run warm-up steps
341  Timer warmup_timer;
342  auto runWarmupStep = [](int crowd_id, StateForThread& sft, DriverTimers& timers,
343  UPtrVector<ContextForSteps>& context_for_steps, UPtrVector<Crowd>& crowds) {
344  Crowd& crowd = *(crowds[crowd_id]);
345  const bool recompute = false;
346  const bool accumulate_this_step = false;
347  const bool spin_move = sft.population.get_golden_electrons().isSpinor();
348  if (spin_move)
349  advanceWalkers<CoordsType::POS_SPIN>(sft, crowd, timers, *context_for_steps[crowd_id], recompute,
350  accumulate_this_step);
351  else
352  advanceWalkers<CoordsType::POS>(sft, crowd, timers, *context_for_steps[crowd_id], recompute,
353  accumulate_this_step);
354  };
355 
356  for (int step = 0; step < qmcdriver_input_.get_warmup_steps(); ++step)
357  {
358  ScopedTimer local_timer(timers_.run_steps_timer);
359  crowd_task(crowds_.size(), runWarmupStep, vmc_state, std::ref(timers_), std::ref(step_contexts_),
360  std::ref(crowds_));
361  }
362 
363  app_log() << "VMC Warmup completed in " << std::setprecision(4) << warmup_timer.elapsed() << " secs" << std::endl;
364  print_mem("VMCBatched after Warmup", app_log());
366  measureImbalance("Warmup");
367  }
368 
369  // this barrier fences all previous load imbalance. Avoid block 0 timing pollution.
370  myComm->barrier();
371 
372  int global_step = 0;
373  for (int block = 0; block < num_blocks; ++block)
374  {
375  {
376  ScopeGuard<LoopTimer<>> vmc_local_timer(vmc_loop);
377  vmc_state.recalculate_properties_period =
379  vmc_state.is_recomputing_block = qmcdriver_input_.get_blocks_between_recompute()
380  ? (1 + block) % qmcdriver_input_.get_blocks_between_recompute() == 0
381  : false;
382 
384 
385  for (auto& crowd : crowds_)
386  crowd->startBlock(steps_per_block_);
387 
388  for (int step = 0; step < steps_per_block_; ++step, ++global_step)
389  {
390  ScopedTimer local_timer(timers_.run_steps_timer);
391  vmc_state.step = step;
392  vmc_state.global_step = global_step;
393  crowd_task(crowds_.size(), runVMCStep, vmc_state, timers_, std::ref(step_contexts_), std::ref(crowds_));
394 
395  if (collect_samples_)
396  {
397  const auto& elec_psets = population_.get_elec_particle_sets();
398  for (const auto& walker : elec_psets)
399  {
400  samples_.appendSample(MCSample(*walker));
401  }
402  }
403  }
404 
405  print_mem("VMCBatched after a block", app_debug_stream());
407  measureImbalance("Block " + std::to_string(block));
408  endBlock();
409  wlog_manager.writeBuffers();
410  recordBlock(block);
411  }
412 
413  bool stop_requested = false;
414  // Rank 0 decides whether the time limit was reached
415  if (!myComm->rank())
416  stop_requested = runtimeControl.checkStop(vmc_loop);
417  myComm->bcast(stop_requested);
418  // Progress messages before possibly stopping
419  if (!myComm->rank())
420  app_log() << runtimeControl.generateProgressMessage("VMCBatched", block, num_blocks);
421  if (stop_requested)
422  {
423  if (!myComm->rank())
424  app_log() << runtimeControl.generateStopMessage("VMCBatched", block);
425  run_time_manager.markStop();
426  break;
427  }
428  }
429  // This is confusing logic from VMC.cpp want this functionality write documentation of this
430  // and clean it up
431  // bool wrotesamples = qmcdriver_input_.get_dump_config();
432  // if (qmcdriver_input_.get_dump_config())
433  // {
434  //wrotesamples = W.dumpEnsemble(wClones, wOut, myComm->size(), nBlocks);
435  //if (wrotesamples)
436  // app_log() << " samples are written to the config.h5" << std::endl;
437  // }
438 
439  // second argument was !wrotesample so if W.dumpEnsemble returns false or
440  // dump_config is false from input then dump_walkers
441  {
442  std::ostringstream o;
443  FullPrecRealType ene, var;
444  estimator_manager_->getApproximateEnergyVariance(ene, var);
445  o << "====================================================";
446  o << "\n End of a VMC section";
447  o << "\n QMC counter = " << project_data_.getSeriesIndex();
448  o << "\n time step = " << qmcdriver_input_.get_tau();
449  o << "\n reference energy = " << ene;
450  o << "\n reference variance = " << var;
451  o << "\n====================================================";
452  app_log() << o.str() << std::endl;
453  }
454 
455  print_mem("VMCBatched ends", app_log());
456 
457  wlog_manager.stopRun();
458  estimator_manager_->stopDriverRun();
459 
460  return finalize(num_blocks, true);
461 }
const std::string & getTitle() const noexcept
returns the title of the project <project id="det_qmc_short_sdbatch_vmcbatch_mwalkers" series="0"> tr...
size_t steps_per_block_
actual number of steps per block
Definition: QMCDriverNew.h:407
void barrier() const
MCPopulation population_
the entire (on node) walker population it serves VMCBatch and DMCBatch right now but will be polymorp...
Definition: QMCDriverNew.h:426
int rank() const
return the rank
Definition: Communicate.h:116
void recordBlock(int block) override
record the state of the block
WalkerLogInput walker_logs_input
walker logs input
Definition: QMCDriverNew.h:108
std::ostream & app_log()
Definition: OutputManager.h:65
std::ostream & app_summary()
Definition: OutputManager.h:63
RunTimeManager< ChronoClock > run_time_manager
const char num_blocks[]
Definition: HDFVersion.h:44
ScopeGuard< NewTimer > ScopedTimer
Definition: NewTimer.h:257
std::unique_ptr< EstimatorManagerNew > estimator_manager_
Observables manager Has very problematic owner ship and life cycle.
Definition: QMCDriverNew.h:443
void print_mem(const std::string &title, std::ostream &log)
Definition: MemoryUsage.cpp:30
std::bitset< QMC_MODE_MAX > qmc_driver_mode_
bits to classify QMCDriver
Definition: QMCDriverNew.h:103
bool collect_samples_
Sample collection flag.
Definition: VMCBatched.h:135
bool finalize(int block, bool dumpwalkers=true)
finalize a qmc section
int getMaxCPUSeconds() const noexcept
const std::string & get_root_name() const override
Definition: QMCDriverNew.h:331
static RefVector< WalkerLogCollector > getWalkerLogCollectorRefs(const UPtrVector< Crowd > &crowds)
get refereces of active walker log collectors. If walker logging is disabled, the RefVector size can ...
Definition: Crowd.cpp:106
static void initialLogEvaluation(int crowd_id, UPtrVector< Crowd > &crowds, UPtrVector< ContextForSteps > &step_context)
Communicate * myComm
pointer to Communicate
Definition: MPIObjectBase.h:62
QMCTraits::FullPrecRealType FullPrecRealType
Definition: VMCBatched.h:38
QMCTraits::IndexType IndexType
Definition: QMCDriverNew.h:79
UPtrVector< ContextForSteps > step_contexts_
Per crowd move contexts, this is where the DistanceTables etc.
Definition: QMCDriverNew.h:450
std::unique_ptr< DriftModifierBase > drift_modifier_
drift modifer
Definition: QMCDriverNew.h:394
static void runVMCStep(int crowd_id, const StateForThread &sft, DriverTimers &timers, UPtrVector< ContextForSteps > &context_for_steps, UPtrVector< Crowd > &crowds)
Thread body for VMC step.
Definition: VMCBatched.cpp:243
bool allow_walker_logs
whether to allow walker logs
Definition: QMCDriverNew.h:106
SampleStack & samples_
Storage for samples (later used in optimizer)
Definition: VMCBatched.h:133
void appendSample(MCSample &&sample)
Definition: SampleStack.cpp:33
IndexType get_warmup_steps() const
IndexType get_max_blocks() const
const ProjectData & project_data_
project info for accessing global fileroot and series id
Definition: QMCDriverNew.h:478
void bcast(T &)
int getSeriesIndex() const noexcept
VMCDriverInput vmcdriver_input_
Definition: VMCBatched.h:124
IndexType get_blocks_between_recompute() const
UPtrVector< Crowd > crowds_
}@
Definition: QMCDriverNew.h:389
QMCDriverInput qmcdriver_input_
Definition: QMCDriverNew.h:372
void measureImbalance(const std::string &tag) const
inject additional barrier and measure load imbalance.
DriverTimers timers_
period of dumping walker configurations and everything else for restart
Definition: QMCDriverNew.h:472
UPtrVector< ParticleSet > & get_elec_particle_sets()
Definition: MCPopulation.h:198
std::ostream & app_debug_stream()
Definition: OutputManager.h:71
void endBlock()
end of a block operations. Aggregates statistics across all MPI ranks and write to disk...
int get_recalculate_properties_period() const

◆ runVMCStep()

void runVMCStep ( int  crowd_id,
const StateForThread sft,
DriverTimers timers,
UPtrVector< ContextForSteps > &  context_for_steps,
UPtrVector< Crowd > &  crowds 
)
static

Thread body for VMC step.

Definition at line 243 of file VMCBatched.cpp.

References qmcplusplus::crowd, MCPopulation::get_golden_electrons(), VMCBatched::StateForThread::is_recomputing_block, ParticleSet::isSpinor(), VMCBatched::StateForThread::population, VMCBatched::StateForThread::step, and VMCBatched::StateForThread::steps_per_block.

Referenced by VMCBatched::run().

248 {
249  Crowd& crowd = *(crowds[crowd_id]);
250  crowd.setRNGForHamiltonian(context_for_steps[crowd_id]->get_random_gen());
251  const IndexType step = sft.step;
252  // Are we entering the the last step of a block to recompute at?
253  const bool recompute_this_step = (sft.is_recomputing_block && (step + 1) == sft.steps_per_block);
254  // For VMC we don't call this method for warmup steps.
255  const bool accumulate_this_step = true;
256  const bool spin_move = sft.population.get_golden_electrons().isSpinor();
257  if (spin_move)
258  advanceWalkers<CoordsType::POS_SPIN>(sft, crowd, timers, *context_for_steps[crowd_id], recompute_this_step,
259  accumulate_this_step);
260  else
261  advanceWalkers<CoordsType::POS>(sft, crowd, timers, *context_for_steps[crowd_id], recompute_this_step,
262  accumulate_this_step);
263 }
QMCTraits::IndexType IndexType
Definition: QMCDriverNew.h:79

Friends And Related Function Documentation

◆ qmcplusplus::testing::VMCBatchedTest

Definition at line 142 of file VMCBatched.h.

Member Data Documentation

◆ collect_samples_

bool collect_samples_
private

Sample collection flag.

Definition at line 135 of file VMCBatched.h.

Referenced by VMCBatched::enable_sample_collection(), and VMCBatched::run().

◆ prevSteps

int prevSteps
private

Definition at line 122 of file VMCBatched.h.

◆ prevStepsBetweenSamples

int prevStepsBetweenSamples
private

Definition at line 123 of file VMCBatched.h.

◆ samples_

SampleStack& samples_
private

Storage for samples (later used in optimizer)

Definition at line 133 of file VMCBatched.h.

Referenced by VMCBatched::enable_sample_collection(), and VMCBatched::run().

◆ vmcdriver_input_

VMCDriverInput vmcdriver_input_
private

Definition at line 124 of file VMCBatched.h.

Referenced by VMCBatched::run().

◆ qmcplusplus::VMCUpdateAll

class qmcplusplus::VMCUpdateAll


Implements the VMC algorithm using particle-by-particle move.

Definition at line 24 of file VMCUpdateAll.h.

+ Inheritance diagram for VMCUpdateAll:
+ Collaboration diagram for VMCUpdateAll:

Public Member Functions

 VMCUpdateAll (MCWalkerConfiguration &w, TrialWaveFunction &psi, QMCHamiltonian &h, RandomBase< FullPrecRealType > &rg)
 Constructor. More...
 
 ~VMCUpdateAll () override
 
void advanceWalker (Walker_t &thisWalker, bool recompute) override
 move a walker More...
 
- Public Member Functions inherited from QMCUpdateBase
 QMCUpdateBase (MCWalkerConfiguration &w, TrialWaveFunction &psi, QMCHamiltonian &h, RandomBase< FullPrecRealType > &rg)
 Constructor. More...
 
 QMCUpdateBase (MCWalkerConfiguration &w, TrialWaveFunction &psi, TrialWaveFunction &guide, QMCHamiltonian &h, RandomBase< FullPrecRealType > &rg)
 Alt Constructor. More...
 
virtual ~QMCUpdateBase ()
 destructor More...
 
RealType acceptRatio () const
 
void resetRun (BranchEngineType *brancher, EstimatorManagerBase *est, TraceManager *traces, const DriftModifierBase *driftmodifer)
 reset the QMCUpdateBase parameters More...
 
void resetRun2 (BranchEngineType *brancher, EstimatorManagerBase *est, TraceManager *traces, WalkerLogCollector *wlog_collector_, const DriftModifierBase *driftmodifer)
 
RealType getTau ()
 
void setTau (RealType t)
 
RealType getSpinMass ()
 
void setSpinMass (RealType m)
 
void getLogs (std::vector< RealType > &logs)
 
void set_step (int step)
 
void startRun (int blocks, bool record)
 start a run More...
 
void stopRun ()
 stop a run More...
 
void stopRun2 ()
 
void startBlock (int steps)
 prepare to start a block More...
 
void stopBlock (bool collectall=true)
 stop a block More...
 
void setMultiplicity (WalkerIter_t it, WalkerIter_t it_end)
 set the multiplicity of the walkers to branch More...
 
void setMultiplicity (Walker_t &awalker) const
 
virtual void initWalkersForPbyP (WalkerIter_t it, WalkerIter_t it_end)
 initialize Walker buffers for PbyP update More...
 
virtual void initWalkers (WalkerIter_t it, WalkerIter_t it_end)
 initialize Walker for walker update More...
 
virtual bool put (xmlNodePtr cur)
 process options More...
 
void accumulate (WalkerIter_t it, WalkerIter_t it_end)
 
virtual void advanceWalkers (WalkerIter_t it, WalkerIter_t it_end, bool recompute)
 advance walkers executed at each step More...
 
virtual RealType advanceWalkerForEE (Walker_t &w1, std::vector< PosType > &dR, std::vector< int > &iats, std::vector< int > &rs, std::vector< RealType > &ratios)
 
int RMC_checkIndex (int N, int NMax)
 
void RMC_checkWalkerBounds (WalkerIter_t &it, WalkerIter_t first, WalkerIter_t last)
 
RealType logBackwardGF (const ParticleSet::ParticlePos &displ)
 

Private Member Functions

 VMCUpdateAll (const VMCUpdateAll &)=delete
 Copy Constructor (disabled) More...
 
VMCUpdateAlloperator= (const VMCUpdateAll &)=delete
 Copy operator (disabled). More...
 

Additional Inherited Members

- Public Types inherited from QMCUpdateBase
using Walker_t = MCWalkerConfiguration::Walker_t
 
using WalkerIter_t = MCWalkerConfiguration::iterator
 
using BranchEngineType = SimpleFixedNodeBranch
 
using mPosType = PosType
 
using mTensorType = TensorType
 
- Public Types inherited from QMCTraits
enum  { DIM = OHMMS_DIM, DIM_VGL = OHMMS_DIM + 2 }
 
using QTBase = QMCTypes< OHMMS_PRECISION, DIM >
 
using QTFull = QMCTypes< OHMMS_PRECISION_FULL, DIM >
 
using RealType = QTBase::RealType
 
using ComplexType = QTBase::ComplexType
 
using ValueType = QTBase::ValueType
 
using PosType = QTBase::PosType
 
using GradType = QTBase::GradType
 
using TensorType = QTBase::TensorType
 
using IndexType = OHMMS_INDEXTYPE
 define other types More...
 
using FullPrecRealType = QTFull::RealType
 
using FullPrecValueType = QTFull::ValueType
 
using PropertySetType = RecordNamedProperty< FullPrecRealType >
 define PropertyList_t More...
 
using PtclGrpIndexes = std::vector< std::pair< int, int > >
 
- Public Attributes inherited from QMCUpdateBase
int nSubSteps
 number of steps per measurement More...
 
DriverDebugChecks debug_checks_ = DriverDebugChecks::ALL_OFF
 determine additional checks for debugging purpose More...
 
std::string debug_checks_str_
 
IndexType MaxAge
 MaxAge>0 indicates branch is done. More...
 
IndexType nAccept
 counter for number of moves accepted More...
 
IndexType nReject
 counter for number of moves rejected More...
 
IndexType nAllRejected
 Total number of the steps when all the particle moves are rejected. More...
 
IndexType nNodeCrossing
 Total number of node crossings per block. More...
 
IndexType NonLocalMoveAccepted
 Total numer of non-local moves accepted. More...
 
RealType Tau
 timestep More...
 
RealType spinMass
 spin mass More...
 
bool UseDrift
 use Drift More...
 
RealType csoffset
 normalization offset for cs type runs. More...
 
TraceManagerTraces
 traces More...
 
WalkerLogCollectorwlog_collector
 
- Protected Member Functions inherited from QMCUpdateBase
RealType getNodeCorrection (const ParticleSet::ParticleGradient &g, ParticleSet::ParticlePos &gscaled)
 evaluate the ratio of scaled velocity and velocity More...
 
 QMCUpdateBase (const QMCUpdateBase &)=delete
 copy constructor (disabled) More...
 
- Static Protected Member Functions inherited from QMCUpdateBase
static void checkLogAndGL (ParticleSet &pset, TrialWaveFunction &twf, const std::string_view location)
 check logpsi and grad and lap against values computed from scratch More...
 
- Protected Attributes inherited from QMCUpdateBase
bool UpdatePbyP
 update particle-by-particle More...
 
IndexType NumPtcl
 number of particles More...
 
RealType m_oneover2tau
 Time-step factor $ 1/(2\tau)$. More...
 
RealType m_sqrttau
 Time-step factor $ \sqrt{\tau}$. More...
 
RealType m_tauovermass
 tau/mass More...
 
RealType m_r2max
 maximum displacement^2 More...
 
MCWalkerConfigurationW
 walker ensemble More...
 
TrialWaveFunctionPsi
 trial function More...
 
TrialWaveFunctionGuide
 guide function More...
 
QMCHamiltonianH
 Hamiltonian. More...
 
RandomBase< FullPrecRealType > & RandomGen
 random number generator More...
 
const BranchEngineTypebranchEngine
 branch engine, stateless reference to the one in QMCDriver More...
 
const DriftModifierBaseDriftModifier
 drift modifer, stateless reference to the one in QMCDriver More...
 
EstimatorManagerBaseEstimators
 estimator More...
 
ParameterSet myParams
 parameters More...
 
std::vector< RealTypeMassInvS
 1/Mass per species More...
 
std::vector< RealTypeMassInvP
 1/Mass per particle More...
 
std::vector< RealTypeSqrtTauOverMass
 sqrt(tau/Mass) per particle More...
 
ParticleSet::ParticlePos drift
 temporary storage for drift More...
 
ParticleSet::ParticlePos deltaR
 temporary storage for random displacement More...
 
ParticleSet::ParticleScalar deltaS
 temporart storage for spin displacement More...
 
ParticleSet::ParticleGradient G
 storage for differential gradients for PbyP update More...
 
ParticleSet::ParticleGradient dG
 
ParticleSet::ParticleLaplacian L
 storage for differential laplacians for PbyP update More...
 
ParticleSet::ParticleLaplacian dL
 

Constructor & Destructor Documentation

◆ VMCUpdateAll() [1/2]

Constructor.

Definition at line 24 of file VMCUpdateAll.cpp.

References QMCUpdateBase::UpdatePbyP.

28  : QMCUpdateBase(w, psi, h, rg)
29 {
30  UpdatePbyP = false;
31 }
QMCUpdateBase(MCWalkerConfiguration &w, TrialWaveFunction &psi, QMCHamiltonian &h, RandomBase< FullPrecRealType > &rg)
Constructor.
bool UpdatePbyP
update particle-by-particle

◆ ~VMCUpdateAll()

~VMCUpdateAll ( )
override

Definition at line 33 of file VMCUpdateAll.cpp.

33 {}

◆ VMCUpdateAll() [2/2]

VMCUpdateAll ( const VMCUpdateAll )
privatedelete

Copy Constructor (disabled)

Member Function Documentation

◆ advanceWalker()

void advanceWalker ( Walker_t thisWalker,
bool  recompute 
)
overridevirtual

move a walker

Implements QMCUpdateBase.

Definition at line 35 of file VMCUpdateAll.cpp.

References Walker< t_traits, p_traits >::Age, qmcplusplus::assignDrift(), QMCHamiltonian::auxHevaluate(), QMCUpdateBase::deltaR, qmcplusplus::Dot(), QMCUpdateBase::drift, QMCHamiltonian::evaluate(), TrialWaveFunction::evaluateLog(), qmcplusplus::exp(), ParticleSet::G, TrialWaveFunction::getPhase(), Walker< t_traits, p_traits >::getPropertyBase(), QMCUpdateBase::H, ParticleSet::loadWalker(), QMCUpdateBase::logBackwardGF(), qmcplusplus::makeGaussRandomWithEngine(), ParticleSet::makeMoveAllParticles(), ParticleSet::makeMoveAllParticlesWithDrift(), QMCUpdateBase::MassInvP, QMCUpdateBase::nAccept, QMCUpdateBase::nReject, QMCUpdateBase::nSubSteps, Walker< t_traits, p_traits >::Properties, QMCUpdateBase::Psi, ParticleSet::R, Walker< t_traits, p_traits >::R, QMCUpdateBase::RandomGen, Walker< t_traits, p_traits >::resetProperty(), QMCHamiltonian::saveProperty(), ParticleSet::saveWalker(), QMCUpdateBase::SqrtTauOverMass, QMCUpdateBase::Tau, ParticleSet::update(), QMCUpdateBase::UseDrift, and QMCUpdateBase::W.

36 {
37  /* thisWalker.R will track the last accepted configuration
38  * W.R will track the proposed configuration
39  *
40  * upon Call:
41  * thisWalker.R,G,L,Properties must be consistent
42  * recompute flag is for pbyp driver and is not used here
43  *
44  * upon Return:
45  * thisWalker.R,G,L,Properties must be kept consistent
46  * */
47  bool updated = false;
48  W.loadWalker(
49  thisWalker,
50  false); // W.R,G,L = thisWalker.R,G,L; false indicates W.DistTables & SK are not updated in this call. W.DistTables,SK are now stale.
51  RealType logpsi_old = thisWalker.Properties(WP::LOGPSI);
52  for (int iter = 0; iter < nSubSteps; ++iter)
53  { // make a few Monte-Carlo steps to decorrelate samples without calculating observables
55  updated = false;
56  if (UseDrift)
57  {
58  assignDrift(Tau, MassInvP, thisWalker.G, drift); // fill variable drift
60  { // W.R = thisWalker.R + drift + deltaR; W.DistTables,SK are updated; W.G,L are now stale
61  RealType logpsi = Psi.evaluateLog(W); // update W.G,L; update Psi.PhaseValue,log_real_
62  RealType logGf = -0.5 * Dot(deltaR, deltaR);
63  assignDrift(Tau, MassInvP, W.G, drift); // update drift at proposed configuration
64  deltaR = thisWalker.R - W.R - drift; // hijack deltaR to hold reverse move
65  RealType logGb = logBackwardGF(deltaR);
66 
67  RealType g = std::exp(logGb - logGf + 2.0 * (logpsi - logpsi_old));
68  // accept or reject
69  if (RandomGen() <= g)
70  {
71  thisWalker.R = W.R;
72  thisWalker.G = W.G;
73  ++nAccept;
74  logpsi_old = logpsi;
75  updated = true;
76  }
77  }
78  }
79  else
80  {
81  if (W.makeMoveAllParticles(thisWalker, deltaR, SqrtTauOverMass))
82  { // W.R += dR*dt; W.DistTables,SK are updated; W.G,L are now stale
83  RealType logpsi = Psi.evaluateLog(W); // update W.G,L at changed W.R; update Psi.log_real_,PhaseValue
84  RealType g = std::exp(2.0 * (logpsi - logpsi_old));
85  if (RandomGen() <= g)
86  { // move is accepted; logpsi_old and R_old are stale
87  logpsi_old = logpsi; // update logpsi_old
88  thisWalker.R = W.R; // update R_old; side effect: thisWalker.G,L,DistTables,SK,Properties are now stale
89  ++nAccept;
90  updated = true;
91  }
92  }
93  }
94 
95  if (!updated)
96  { // W.R,G,L,DistTables,SK are not updated. i.e. they are still consistent
97  thisWalker.Age++;
98  ++nReject;
99  }
100  }
101 
102  if (!updated)
103  { // W.G and W.L have to be computed because the last move was rejected
104  W.loadWalker(thisWalker, false); // move W back to last accepted configuration
105  W.update(); // update W.DistTables and SK
106  logpsi_old = Psi.evaluateLog(W); // update W.G,L
107  } // W and logpsi_old are up-to-date at this point
108 
109  RealType eloc = H.evaluate(
110  W); // calculate local energy; W.SK must be up-to-date if Coulomb interaction is used with periodic boundary. W.SK is used to calculate the long-range part of the Coulomb potential.
111  W.saveWalker(thisWalker);
112  thisWalker.resetProperty(logpsi_old, Psi.getPhase(),
113  eloc); // update thisWalker::Properties[WP::LOGPSI,WP::SIGN,WP::LOCALENERGY]
114  H.auxHevaluate(W, thisWalker); // update auxiliary observables, i.e. fill H::Observables
115  H.saveProperty(thisWalker.getPropertyBase()); // copy H::Observables to thisWalker::Properties
116 }
RealType evaluateLog(ParticleSet &P)
evalaute the log (internally gradients and laplacian) of the trial wavefunction.
ParticleSet::ParticlePos drift
temporary storage for drift
TrialWaveFunction & Psi
trial function
void saveProperty(IT first)
save the values of Hamiltonian elements to the Properties
void assignDrift(T s, const ParticleAttrib< TinyVector< TG, D >> &ga, ParticleAttrib< TinyVector< T, D >> &da)
void update(bool skipSK=false)
update the internal data
ParticleSet::ParticlePos deltaR
temporary storage for random displacement
T Dot(const ParticleAttrib< TinyVector< T, D >> &pa, const ParticleAttrib< TinyVector< T, D >> &pb)
std::vector< RealType > SqrtTauOverMass
sqrt(tau/Mass) per particle
ParticleGradient G
gradients of the particles
Definition: ParticleSet.h:83
void saveWalker(Walker_t &awalker)
save this to awalker
RealType Tau
timestep
Definition: QMCUpdateBase.h:73
RealType logBackwardGF(const ParticleSet::ParticlePos &displ)
ParticlePos R
Position.
Definition: ParticleSet.h:79
MakeReturn< UnaryNode< FnExp, typename CreateLeaf< Vector< T1, C1 > >::Leaf_t > >::Expression_t exp(const Vector< T1, C1 > &l)
MCWalkerConfiguration & W
walker ensemble
std::vector< RealType > MassInvP
1/Mass per particle
void loadWalker(Walker_t &awalker, bool pbyp)
load a Walker_t to the current ParticleSet
void auxHevaluate(ParticleSet &P)
int nSubSteps
number of steps per measurement
Definition: QMCUpdateBase.h:56
QMCTraits::RealType RealType
RandomBase< FullPrecRealType > & RandomGen
random number generator
FullPrecRealType evaluate(ParticleSet &P)
evaluate Local Energy
bool makeMoveAllParticlesWithDrift(const Walker_t &awalker, const ParticlePos &drift, const ParticlePos &deltaR, RealType dt)
move all the particles including the drift
IndexType nAccept
counter for number of moves accepted
Definition: QMCUpdateBase.h:63
IndexType nReject
counter for number of moves rejected
Definition: QMCUpdateBase.h:65
bool makeMoveAllParticles(const Walker_t &awalker, const ParticlePos &deltaR, RealType dt)
move all the particles of a walker
QMCHamiltonian & H
Hamiltonian.
void makeGaussRandomWithEngine(ParticleAttrib< TinyVector< T, D >> &a, RG &rng)

◆ operator=()

VMCUpdateAll& operator= ( const VMCUpdateAll )
privatedelete

Copy operator (disabled).

◆ qmcplusplus::VMCUpdatePbyP

class qmcplusplus::VMCUpdatePbyP


Implements the VMC algorithm using particle-by-particle move.

Definition at line 25 of file VMCUpdatePbyP.h.

+ Inheritance diagram for VMCUpdatePbyP:
+ Collaboration diagram for VMCUpdatePbyP:

Public Member Functions

 VMCUpdatePbyP (MCWalkerConfiguration &w, TrialWaveFunction &psi, QMCHamiltonian &h, RandomBase< FullPrecRealType > &rg)
 Constructor. More...
 
 ~VMCUpdatePbyP () override
 
void advanceWalker (Walker_t &thisWalker, bool recompute) override
 move a walker More...
 
- Public Member Functions inherited from QMCUpdateBase
 QMCUpdateBase (MCWalkerConfiguration &w, TrialWaveFunction &psi, QMCHamiltonian &h, RandomBase< FullPrecRealType > &rg)
 Constructor. More...
 
 QMCUpdateBase (MCWalkerConfiguration &w, TrialWaveFunction &psi, TrialWaveFunction &guide, QMCHamiltonian &h, RandomBase< FullPrecRealType > &rg)
 Alt Constructor. More...
 
virtual ~QMCUpdateBase ()
 destructor More...
 
RealType acceptRatio () const
 
void resetRun (BranchEngineType *brancher, EstimatorManagerBase *est, TraceManager *traces, const DriftModifierBase *driftmodifer)
 reset the QMCUpdateBase parameters More...
 
void resetRun2 (BranchEngineType *brancher, EstimatorManagerBase *est, TraceManager *traces, WalkerLogCollector *wlog_collector_, const DriftModifierBase *driftmodifer)
 
RealType getTau ()
 
void setTau (RealType t)
 
RealType getSpinMass ()
 
void setSpinMass (RealType m)
 
void getLogs (std::vector< RealType > &logs)
 
void set_step (int step)
 
void startRun (int blocks, bool record)
 start a run More...
 
void stopRun ()
 stop a run More...
 
void stopRun2 ()
 
void startBlock (int steps)
 prepare to start a block More...
 
void stopBlock (bool collectall=true)
 stop a block More...
 
void setMultiplicity (WalkerIter_t it, WalkerIter_t it_end)
 set the multiplicity of the walkers to branch More...
 
void setMultiplicity (Walker_t &awalker) const
 
virtual void initWalkersForPbyP (WalkerIter_t it, WalkerIter_t it_end)
 initialize Walker buffers for PbyP update More...
 
virtual void initWalkers (WalkerIter_t it, WalkerIter_t it_end)
 initialize Walker for walker update More...
 
virtual bool put (xmlNodePtr cur)
 process options More...
 
void accumulate (WalkerIter_t it, WalkerIter_t it_end)
 
virtual void advanceWalkers (WalkerIter_t it, WalkerIter_t it_end, bool recompute)
 advance walkers executed at each step More...
 
virtual RealType advanceWalkerForEE (Walker_t &w1, std::vector< PosType > &dR, std::vector< int > &iats, std::vector< int > &rs, std::vector< RealType > &ratios)
 
int RMC_checkIndex (int N, int NMax)
 
void RMC_checkWalkerBounds (WalkerIter_t &it, WalkerIter_t first, WalkerIter_t last)
 
RealType logBackwardGF (const ParticleSet::ParticlePos &displ)
 

Private Attributes

NewTimerbuffer_timer_
 
NewTimermovepbyp_timer_
 
NewTimerhamiltonian_timer_
 
NewTimercollectables_timer_
 

Additional Inherited Members

- Public Types inherited from QMCUpdateBase
using Walker_t = MCWalkerConfiguration::Walker_t
 
using WalkerIter_t = MCWalkerConfiguration::iterator
 
using BranchEngineType = SimpleFixedNodeBranch
 
using mPosType = PosType
 
using mTensorType = TensorType
 
- Public Types inherited from QMCTraits
enum  { DIM = OHMMS_DIM, DIM_VGL = OHMMS_DIM + 2 }
 
using QTBase = QMCTypes< OHMMS_PRECISION, DIM >
 
using QTFull = QMCTypes< OHMMS_PRECISION_FULL, DIM >
 
using RealType = QTBase::RealType
 
using ComplexType = QTBase::ComplexType
 
using ValueType = QTBase::ValueType
 
using PosType = QTBase::PosType
 
using GradType = QTBase::GradType
 
using TensorType = QTBase::TensorType
 
using IndexType = OHMMS_INDEXTYPE
 define other types More...
 
using FullPrecRealType = QTFull::RealType
 
using FullPrecValueType = QTFull::ValueType
 
using PropertySetType = RecordNamedProperty< FullPrecRealType >
 define PropertyList_t More...
 
using PtclGrpIndexes = std::vector< std::pair< int, int > >
 
- Public Attributes inherited from QMCUpdateBase
int nSubSteps
 number of steps per measurement More...
 
DriverDebugChecks debug_checks_ = DriverDebugChecks::ALL_OFF
 determine additional checks for debugging purpose More...
 
std::string debug_checks_str_
 
IndexType MaxAge
 MaxAge>0 indicates branch is done. More...
 
IndexType nAccept
 counter for number of moves accepted More...
 
IndexType nReject
 counter for number of moves rejected More...
 
IndexType nAllRejected
 Total number of the steps when all the particle moves are rejected. More...
 
IndexType nNodeCrossing
 Total number of node crossings per block. More...
 
IndexType NonLocalMoveAccepted
 Total numer of non-local moves accepted. More...
 
RealType Tau
 timestep More...
 
RealType spinMass
 spin mass More...
 
bool UseDrift
 use Drift More...
 
RealType csoffset
 normalization offset for cs type runs. More...
 
TraceManagerTraces
 traces More...
 
WalkerLogCollectorwlog_collector
 
- Protected Member Functions inherited from QMCUpdateBase
RealType getNodeCorrection (const ParticleSet::ParticleGradient &g, ParticleSet::ParticlePos &gscaled)
 evaluate the ratio of scaled velocity and velocity More...
 
 QMCUpdateBase (const QMCUpdateBase &)=delete
 copy constructor (disabled) More...
 
- Static Protected Member Functions inherited from QMCUpdateBase
static void checkLogAndGL (ParticleSet &pset, TrialWaveFunction &twf, const std::string_view location)
 check logpsi and grad and lap against values computed from scratch More...
 
- Protected Attributes inherited from QMCUpdateBase
bool UpdatePbyP
 update particle-by-particle More...
 
IndexType NumPtcl
 number of particles More...
 
RealType m_oneover2tau
 Time-step factor $ 1/(2\tau)$. More...
 
RealType m_sqrttau
 Time-step factor $ \sqrt{\tau}$. More...
 
RealType m_tauovermass
 tau/mass More...
 
RealType m_r2max
 maximum displacement^2 More...
 
MCWalkerConfigurationW
 walker ensemble More...
 
TrialWaveFunctionPsi
 trial function More...
 
TrialWaveFunctionGuide
 guide function More...
 
QMCHamiltonianH
 Hamiltonian. More...
 
RandomBase< FullPrecRealType > & RandomGen
 random number generator More...
 
const BranchEngineTypebranchEngine
 branch engine, stateless reference to the one in QMCDriver More...
 
const DriftModifierBaseDriftModifier
 drift modifer, stateless reference to the one in QMCDriver More...
 
EstimatorManagerBaseEstimators
 estimator More...
 
ParameterSet myParams
 parameters More...
 
std::vector< RealTypeMassInvS
 1/Mass per species More...
 
std::vector< RealTypeMassInvP
 1/Mass per particle More...
 
std::vector< RealTypeSqrtTauOverMass
 sqrt(tau/Mass) per particle More...
 
ParticleSet::ParticlePos drift
 temporary storage for drift More...
 
ParticleSet::ParticlePos deltaR
 temporary storage for random displacement More...
 
ParticleSet::ParticleScalar deltaS
 temporart storage for spin displacement More...
 
ParticleSet::ParticleGradient G
 storage for differential gradients for PbyP update More...
 
ParticleSet::ParticleGradient dG
 
ParticleSet::ParticleLaplacian L
 storage for differential laplacians for PbyP update More...
 
ParticleSet::ParticleLaplacian dL
 

Constructor & Destructor Documentation

◆ VMCUpdatePbyP()

Constructor.

Definition at line 30 of file VMCUpdatePbyP.cpp.

34  : QMCUpdateBase(w, psi, h, rg),
35  buffer_timer_(createGlobalTimer("VMCUpdatePbyP::Buffer", timer_level_medium)),
36  movepbyp_timer_(createGlobalTimer("VMCUpdatePbyP::MovePbyP", timer_level_medium)),
37  hamiltonian_timer_(createGlobalTimer("VMCUpdatePbyP::Hamiltonian", timer_level_medium)),
38  collectables_timer_(createGlobalTimer("VMCUpdatePbyP::Collectables", timer_level_medium))
39 {}
NewTimer & createGlobalTimer(const std::string &myname, timer_levels mylevel)
QMCUpdateBase(MCWalkerConfiguration &w, TrialWaveFunction &psi, QMCHamiltonian &h, RandomBase< FullPrecRealType > &rg)
Constructor.

◆ ~VMCUpdatePbyP()

~VMCUpdatePbyP ( )
override

Definition at line 41 of file VMCUpdatePbyP.cpp.

41 {}

Member Function Documentation

◆ advanceWalker()

void advanceWalker ( Walker_t thisWalker,
bool  recompute 
)
overridevirtual

move a walker

Implements QMCUpdateBase.

Definition at line 43 of file VMCUpdatePbyP.cpp.

References ParticleSet::accept_rejectMove(), TrialWaveFunction::acceptMove(), QMCHamiltonian::auxHevaluate(), TraceManager::buffer_sample(), VMCUpdatePbyP::buffer_timer_, TrialWaveFunction::calcRatio(), TrialWaveFunction::calcRatioGrad(), qmcplusplus::CHECKGL_AFTER_MOVES, QMCUpdateBase::checkLogAndGL(), WalkerLogCollector::collect(), VMCUpdatePbyP::collectables_timer_, TrialWaveFunction::completeUpdates(), TrialWaveFunction::copyFromBuffer(), ParticleSet::current_step, Walker< t_traits, p_traits >::DataSet, QMCUpdateBase::debug_checks_, QMCUpdateBase::deltaR, ParticleSet::donePbyP(), qmcplusplus::dot(), QMCUpdateBase::DriftModifier, TrialWaveFunction::evalGrad(), QMCHamiltonian::evaluate(), qmcplusplus::exp(), ParticleSet::first(), ParticleSet::getActivePos(), DriftModifierBase::getDrift(), TrialWaveFunction::getPhase(), Walker< t_traits, p_traits >::getPropertyBase(), ParticleSet::groups(), QMCUpdateBase::H, VMCUpdatePbyP::hamiltonian_timer_, ParticleSet::last(), ParticleSet::loadWalker(), qmcplusplus::makeGaussRandomWithEngine(), ParticleSet::makeMoveAndCheck(), QMCUpdateBase::MassInvS, VMCUpdatePbyP::movepbyp_timer_, QMCUpdateBase::nAccept, QMCUpdateBase::nAllRejected, norm(), QMCUpdateBase::nReject, QMCUpdateBase::nSubSteps, TrialWaveFunction::prepareGroup(), QMCUpdateBase::Psi, ParticleSet::R, QMCUpdateBase::RandomGen, TrialWaveFunction::rejectMove(), Walker< t_traits, p_traits >::resetProperty(), QMCHamiltonian::saveProperty(), ParticleSet::saveWalker(), qmcplusplus::sqrt(), TimerType< CLOCK >::start(), TimerType< CLOCK >::stop(), QMCUpdateBase::Tau, QMCUpdateBase::Traces, TrialWaveFunction::updateBuffer(), QMCUpdateBase::UseDrift, QMCUpdateBase::W, and QMCUpdateBase::wlog_collector.

44 {
46  W.loadWalker(thisWalker, true);
47  Walker_t::WFBuffer_t& w_buffer(thisWalker.DataSet);
48  Psi.copyFromBuffer(W, w_buffer);
50 
51  // start PbyP moves
53  bool moved = false;
54  constexpr RealType mhalf(-0.5);
55  for (int iter = 0; iter < nSubSteps; ++iter)
56  {
57  //create a 3N-Dimensional Gaussian with variance=1
59  moved = false;
60  for (int ig = 0; ig < W.groups(); ++ig) //loop over species
61  {
62  RealType tauovermass = Tau * MassInvS[ig];
63  RealType oneover2tau = 0.5 / (tauovermass);
64  RealType sqrttau = std::sqrt(tauovermass);
65  Psi.prepareGroup(W, ig);
66  for (int iat = W.first(ig); iat < W.last(ig); ++iat)
67  {
68  PosType dr;
69  if (UseDrift)
70  {
71  GradType grad_now = Psi.evalGrad(W, iat);
72  DriftModifier->getDrift(tauovermass, grad_now, dr);
73  dr += sqrttau * deltaR[iat];
74  }
75  else
76  dr = sqrttau * deltaR[iat];
77 
78  if (!W.makeMoveAndCheck(iat, dr))
79  {
80  ++nReject;
81  W.accept_rejectMove(iat, false);
82  continue;
83  }
84 
85  RealType prob(0);
86  if (UseDrift)
87  {
88  GradType grad_new;
89  prob = std::norm(Psi.calcRatioGrad(W, iat, grad_new));
90  DriftModifier->getDrift(tauovermass, grad_new, dr);
91  dr = W.R[iat] - W.getActivePos() - dr;
92  RealType logGb = -oneover2tau * dot(dr, dr);
93  RealType logGf = mhalf * dot(deltaR[iat], deltaR[iat]);
94  prob *= std::exp(logGb - logGf);
95  }
96  else
97  prob = std::norm(Psi.calcRatio(W, iat));
98 
99  bool is_accepted = false;
100  if (prob >= std::numeric_limits<RealType>::epsilon() && RandomGen() < prob)
101  {
102  is_accepted = true;
103  moved = true;
104  ++nAccept;
105  Psi.acceptMove(W, iat, true);
106  }
107  else
108  {
109  ++nReject;
110  Psi.rejectMove(iat);
111  }
112  W.accept_rejectMove(iat, is_accepted);
113  }
114  }
116  }
117  W.donePbyP();
120  RealType logpsi = Psi.updateBuffer(W, w_buffer, recompute);
122  checkLogAndGL(W, Psi, "checkGL_after_moves");
123  W.saveWalker(thisWalker);
125  // end PbyP moves
127  FullPrecRealType eloc = H.evaluate(W);
128  thisWalker.resetProperty(logpsi, Psi.getPhase(), eloc);
131  H.auxHevaluate(W, thisWalker);
132  H.saveProperty(thisWalker.getPropertyBase());
134 #if !defined(REMOVE_TRACEMANAGER)
136 #endif
137  if(wlog_collector)
138  wlog_collector->collect(thisWalker,W,Psi,H);
139  if (!moved)
140  ++nAllRejected;
141 }
TraceManager * Traces
traces
WalkerLogCollector * wlog_collector
void rejectMove(int iat)
restore to the original state
ValueType calcRatio(ParticleSet &P, int iat, ComputeType ct=ComputeType::ALL)
compute psi(R_new) / psi(R_current) ratio It returns a complex value if the wavefunction is complex...
void copyFromBuffer(ParticleSet &P, WFBufferType &buf)
copy all the wavefunction components from buffer.
QTBase::GradType GradType
Definition: Configuration.h:62
TrialWaveFunction & Psi
trial function
void acceptMove(ParticleSet &P, int iat, bool safe_to_delay=false)
update the state with the new data
void saveProperty(IT first)
save the values of Hamiltonian elements to the Properties
void buffer_sample(int current_step)
int first(int igroup) const
return the first index of a group i
Definition: ParticleSet.h:514
int current_step
current MC step
Definition: ParticleSet.h:134
ParticleSet::ParticlePos deltaR
temporary storage for random displacement
RealType updateBuffer(ParticleSet &P, WFBufferType &buf, bool fromscratch=false)
update all the wavefunction components in buffer.
DriverDebugChecks debug_checks_
determine additional checks for debugging purpose
Definition: QMCUpdateBase.h:58
QMCTraits::PosType PosType
int groups() const
return the number of groups
Definition: ParticleSet.h:511
PooledMemory< FullPrecRealType > WFBuffer_t
Definition: Walker.h:80
const PosType & getActivePos() const
Definition: ParticleSet.h:261
double norm(const zVec &c)
Definition: VectorOps.h:118
void saveWalker(Walker_t &awalker)
save this to awalker
RealType Tau
timestep
Definition: QMCUpdateBase.h:73
void accept_rejectMove(Index_t iat, bool accepted, bool forward_mode=true)
accept or reject a proposed move Two operation modes: The using and updating distance tables via Part...
ParticlePos R
Position.
Definition: ParticleSet.h:79
int last(int igroup) const
return the last index of a group i
Definition: ParticleSet.h:517
MakeReturn< UnaryNode< FnExp, typename CreateLeaf< Vector< T1, C1 > >::Leaf_t > >::Expression_t exp(const Vector< T1, C1 > &l)
MCWalkerConfiguration & W
walker ensemble
static void checkLogAndGL(ParticleSet &pset, TrialWaveFunction &twf, const std::string_view location)
check logpsi and grad and lap against values computed from scratch
void loadWalker(Walker_t &awalker, bool pbyp)
load a Walker_t to the current ParticleSet
void collect(const MCPWalker &walker, const ParticleSet &pset, const TrialWaveFunction &wfn, const QMCHamiltonian &ham, int step=-1)
collect all data for one walker into the data buffers
void auxHevaluate(ParticleSet &P)
int nSubSteps
number of steps per measurement
Definition: QMCUpdateBase.h:56
MakeReturn< UnaryNode< FnSqrt, typename CreateLeaf< Vector< T1, C1 > >::Leaf_t > >::Expression_t sqrt(const Vector< T1, C1 > &l)
QMCTraits::RealType RealType
RandomBase< FullPrecRealType > & RandomGen
random number generator
GradType evalGrad(ParticleSet &P, int iat)
FullPrecRealType evaluate(ParticleSet &P)
evaluate Local Energy
Tensor< typename BinaryReturn< T1, T2, OpMultiply >::Type_t, D > dot(const AntiSymTensor< T1, D > &lhs, const AntiSymTensor< T2, D > &rhs)
bool makeMoveAndCheck(Index_t iat, const SingleParticlePos &displ)
move the iat-th particle to active_pos_
QTFull::RealType FullPrecRealType
Definition: Configuration.h:66
IndexType nAccept
counter for number of moves accepted
Definition: QMCUpdateBase.h:63
IndexType nReject
counter for number of moves rejected
Definition: QMCUpdateBase.h:65
virtual void getDrift(RealType tau, const GradType &qf, PosType &drift) const =0
evaluate a drift with a real force
void prepareGroup(ParticleSet &P, int ig)
Prepare internal data for updating WFC correspond to a particle group Particle groups usually corresp...
std::vector< RealType > MassInvS
1/Mass per species
QMCHamiltonian & H
Hamiltonian.
ValueType calcRatioGrad(ParticleSet &P, int iat, GradType &grad_iat)
compute psi(R_new) / psi(R_current) ratio and ln(psi(R_new)) gradients It returns a complex value if...
void donePbyP(bool skipSK=false)
update structure factor and unmark active_ptcl_
void completeUpdates()
complete all the delayed or asynchronous operations before leaving the p-by-p move region...
IndexType nAllRejected
Total number of the steps when all the particle moves are rejected.
Definition: QMCUpdateBase.h:67
const DriftModifierBase * DriftModifier
drift modifer, stateless reference to the one in QMCDriver
void makeGaussRandomWithEngine(ParticleAttrib< TinyVector< T, D >> &a, RG &rng)

Member Data Documentation

◆ buffer_timer_

NewTimer& buffer_timer_
private

Definition at line 36 of file VMCUpdatePbyP.h.

Referenced by VMCUpdatePbyP::advanceWalker().

◆ collectables_timer_

NewTimer& collectables_timer_
private

Definition at line 39 of file VMCUpdatePbyP.h.

Referenced by VMCUpdatePbyP::advanceWalker().

◆ hamiltonian_timer_

NewTimer& hamiltonian_timer_
private

Definition at line 38 of file VMCUpdatePbyP.h.

Referenced by VMCUpdatePbyP::advanceWalker().

◆ movepbyp_timer_

NewTimer& movepbyp_timer_
private

Definition at line 37 of file VMCUpdatePbyP.h.

Referenced by VMCUpdatePbyP::advanceWalker().

◆ qmcplusplus::CostFunctionCrowdData

class qmcplusplus::CostFunctionCrowdData

Implements wave-function optimization.

Class to hold temporary data and object copies for crowd-local evaluation

Definition at line 28 of file CostFunctionCrowdData.h.

+ Collaboration diagram for CostFunctionCrowdData:

Public Types

using Return_rt = qmcplusplus::QMCTraits::RealType
 
using FullPrecRealType = QMCTraits::FullPrecRealType
 

Public Member Functions

 CostFunctionCrowdData (int crowd_size, ParticleSet &P, TrialWaveFunction &Psi, QMCHamiltonian &H, RandomBase< FullPrecRealType > &Rng)
 Create the arrays of crowd_size and create object copies. More...
 
void zero_log_psi ()
 Set the log_psi_* arrays to zero. More...
 
RefVector< ParticleSetget_p_list (int len)
 
RefVector< TrialWaveFunctionget_wf_list (int len)
 
RefVector< QMCHamiltonianget_h_list (int len)
 
RefVector< QMCHamiltonianget_h0_list (int len)
 
std::vector< Return_rt > & get_log_psi_fixed ()
 
std::vector< Return_rt > & get_log_psi_opt ()
 
UPtrVector< RandomBase< FullPrecRealType > > & get_rng_ptr_list ()
 
RandomBase< FullPrecRealType > & get_rng_save ()
 
UPtrVector< TrialWaveFunction > & get_wf_ptr_list ()
 
Return_rtget_e0 ()
 
Return_rtget_e2 ()
 
Return_rtget_wgt ()
 
Return_rtget_wgt2 ()
 
DriverWalkerResourceCollectiongetSharedResource ()
 
ResourceCollectionget_h0_res ()
 

Private Attributes

std::vector< Return_rtlog_psi_fixed_
 
std::vector< Return_rtlog_psi_opt_
 
UPtrVector< TrialWaveFunctionwf_ptr_list_
 
UPtrVector< ParticleSetp_ptr_list_
 
UPtrVector< QMCHamiltonianh_ptr_list_
 
UPtrVector< QMCHamiltonianh0_ptr_list_
 
UPtrVector< RandomBase< FullPrecRealType > > rng_ptr_list_
 
DriverWalkerResourceCollection driverwalker_resource_collection_
 
ResourceCollection h0_res_
 resource collection corresponding to h0 More...
 
std::unique_ptr< RandomBase< FullPrecRealType > > rng_save_ptr_
 
Return_rt e0_
 
Return_rt e2_
 
Return_rt wgt_
 
Return_rt wgt2_
 

Member Typedef Documentation

◆ FullPrecRealType

◆ Return_rt

Constructor & Destructor Documentation

◆ CostFunctionCrowdData()

CostFunctionCrowdData ( int  crowd_size,
ParticleSet P,
TrialWaveFunction Psi,
QMCHamiltonian H,
RandomBase< FullPrecRealType > &  Rng 
)

Create the arrays of crowd_size and create object copies.

Definition at line 18 of file CostFunctionCrowdData.cpp.

References QMCHamiltonian::addOperator(), QMCHamiltonian::createResource(), TrialWaveFunction::createResource(), ParticleSet::createResource(), CostFunctionCrowdData::driverwalker_resource_collection_, QMCHamiltonian::getTWFDependentComponents(), CostFunctionCrowdData::h0_ptr_list_, CostFunctionCrowdData::h0_res_, CostFunctionCrowdData::h_ptr_list_, DriverWalkerResourceCollection::ham_res, CostFunctionCrowdData::log_psi_fixed_, CostFunctionCrowdData::log_psi_opt_, RandomBase< T >::makeClone(), QMCHamiltonian::makeClone(), TrialWaveFunction::makeClone(), CostFunctionCrowdData::p_ptr_list_, DriverWalkerResourceCollection::pset_res, CostFunctionCrowdData::rng_ptr_list_, CostFunctionCrowdData::rng_save_ptr_, DriverWalkerResourceCollection::twf_res, and CostFunctionCrowdData::wf_ptr_list_.

23  : h0_res_("h0 resource"), e0_(0.0), e2_(0.0), wgt_(0.0), wgt2_(0.0)
24 {
26  Psi.createResource(driverwalker_resource_collection_.twf_res);
28 
29  log_psi_fixed_.resize(crowd_size);
30  log_psi_opt_.resize(crowd_size);
31 
32  wf_ptr_list_.resize(crowd_size);
33  p_ptr_list_.resize(crowd_size);
34  h_ptr_list_.resize(crowd_size);
35  h0_ptr_list_.resize(crowd_size);
36 
37  rng_ptr_list_.resize(crowd_size);
38 
39  // build a temporary H_KE for later calling makeClone
40  // need makeClone to setup internal my_index_ of a new copy.
41  const auto components = H.getTWFDependentComponents();
42  QMCHamiltonian H_KE("h_free");
43  for (OperatorBase& component : components)
44  H_KE.addOperator(component.makeClone(P, Psi), component.getName());
45  H_KE.createResource(h0_res_);
46 
47  for (int ib = 0; ib < crowd_size; ib++)
48  {
49  p_ptr_list_[ib] = std::make_unique<ParticleSet>(P);
50  auto& pCopy = *p_ptr_list_[ib];
51 
52  wf_ptr_list_[ib] = Psi.makeClone(pCopy);
53  auto& psiCopy = *wf_ptr_list_[ib];
54 
55  h_ptr_list_[ib] = H.makeClone(pCopy, psiCopy);
56  h0_ptr_list_[ib] = H_KE.makeClone(pCopy, psiCopy);
57 
58  rng_ptr_list_[ib] = Rng.makeClone();
59  h_ptr_list_[ib]->setRandomGenerator(rng_ptr_list_[ib].get());
60  h0_ptr_list_[ib]->setRandomGenerator(rng_ptr_list_[ib].get());
61  }
62  rng_save_ptr_ = Rng.makeClone();
63 }
DriverWalkerResourceCollection driverwalker_resource_collection_
UPtrVector< QMCHamiltonian > h_ptr_list_
UPtrVector< TrialWaveFunction > wf_ptr_list_
UPtrVector< RandomBase< FullPrecRealType > > rng_ptr_list_
ResourceCollection h0_res_
resource collection corresponding to h0
virtual std::unique_ptr< RandomBase< T > > makeClone() const =0
UPtrVector< QMCHamiltonian > h0_ptr_list_
UPtrVector< ParticleSet > p_ptr_list_
std::vector< Return_rt > log_psi_fixed_
std::unique_ptr< RandomBase< FullPrecRealType > > rng_save_ptr_

Member Function Documentation

◆ get_e0()

Return_rt& get_e0 ( )
inline

◆ get_e2()

Return_rt& get_e2 ( )
inline

◆ get_h0_list()

RefVector< QMCHamiltonian > get_h0_list ( int  len)

Definition at line 80 of file CostFunctionCrowdData.cpp.

References qmcplusplus::convertUPtrToRefVectorSubset(), and CostFunctionCrowdData::h0_ptr_list_.

Referenced by QMCCostFunctionBatched::correlatedSampling().

81 {
83 }
static RefVector< T > convertUPtrToRefVectorSubset(const UPtrVector< T > &ptr_list, int offset, int len)
UPtrVector< QMCHamiltonian > h0_ptr_list_

◆ get_h0_res()

ResourceCollection& get_h0_res ( )
inline

Definition at line 63 of file CostFunctionCrowdData.h.

References CostFunctionCrowdData::h0_res_.

Referenced by QMCCostFunctionBatched::correlatedSampling().

63 { return h0_res_; }
ResourceCollection h0_res_
resource collection corresponding to h0

◆ get_h_list()

RefVector< QMCHamiltonian > get_h_list ( int  len)

Definition at line 75 of file CostFunctionCrowdData.cpp.

References qmcplusplus::convertUPtrToRefVectorSubset(), and CostFunctionCrowdData::h_ptr_list_.

Referenced by QMCCostFunctionBatched::checkConfigurations().

76 {
78 }
UPtrVector< QMCHamiltonian > h_ptr_list_
static RefVector< T > convertUPtrToRefVectorSubset(const UPtrVector< T > &ptr_list, int offset, int len)

◆ get_log_psi_fixed()

std::vector<Return_rt>& get_log_psi_fixed ( )
inline

◆ get_log_psi_opt()

std::vector<Return_rt>& get_log_psi_opt ( )
inline

◆ get_p_list()

RefVector< ParticleSet > get_p_list ( int  len)

Definition at line 65 of file CostFunctionCrowdData.cpp.

References qmcplusplus::convertUPtrToRefVectorSubset(), and CostFunctionCrowdData::p_ptr_list_.

Referenced by QMCCostFunctionBatched::checkConfigurations(), and QMCCostFunctionBatched::correlatedSampling().

66 {
68 }
static RefVector< T > convertUPtrToRefVectorSubset(const UPtrVector< T > &ptr_list, int offset, int len)
UPtrVector< ParticleSet > p_ptr_list_

◆ get_rng_ptr_list()

UPtrVector<RandomBase<FullPrecRealType> >& get_rng_ptr_list ( )
inline

◆ get_rng_save()

RandomBase<FullPrecRealType>& get_rng_save ( )
inline

Definition at line 52 of file CostFunctionCrowdData.h.

References CostFunctionCrowdData::rng_save_ptr_.

Referenced by QMCCostFunctionBatched::checkConfigurations(), and QMCCostFunctionBatched::correlatedSampling().

52 { return *rng_save_ptr_; }
std::unique_ptr< RandomBase< FullPrecRealType > > rng_save_ptr_

◆ get_wf_list()

RefVector< TrialWaveFunction > get_wf_list ( int  len)

Definition at line 70 of file CostFunctionCrowdData.cpp.

References qmcplusplus::convertUPtrToRefVectorSubset(), and CostFunctionCrowdData::wf_ptr_list_.

Referenced by QMCCostFunctionBatched::checkConfigurations(), and QMCCostFunctionBatched::correlatedSampling().

71 {
73 }
UPtrVector< TrialWaveFunction > wf_ptr_list_
static RefVector< T > convertUPtrToRefVectorSubset(const UPtrVector< T > &ptr_list, int offset, int len)

◆ get_wf_ptr_list()

UPtrVector<TrialWaveFunction>& get_wf_ptr_list ( )
inline

Definition at line 54 of file CostFunctionCrowdData.h.

References CostFunctionCrowdData::wf_ptr_list_.

54 { return wf_ptr_list_; }
UPtrVector< TrialWaveFunction > wf_ptr_list_

◆ get_wgt()

Return_rt& get_wgt ( )
inline

◆ get_wgt2()

Return_rt& get_wgt2 ( )
inline

◆ getSharedResource()

◆ zero_log_psi()

void zero_log_psi ( )

Set the log_psi_* arrays to zero.

Definition at line 85 of file CostFunctionCrowdData.cpp.

References CostFunctionCrowdData::log_psi_fixed_, and CostFunctionCrowdData::log_psi_opt_.

Referenced by QMCCostFunctionBatched::checkConfigurations(), and QMCCostFunctionBatched::correlatedSampling().

86 {
87  std::fill(log_psi_opt_.begin(), log_psi_opt_.end(), 0.0);
88  std::fill(log_psi_fixed_.begin(), log_psi_fixed_.end(), 0.0);
89 }
std::vector< Return_rt > log_psi_fixed_

Member Data Documentation

◆ driverwalker_resource_collection_

DriverWalkerResourceCollection driverwalker_resource_collection_
private

◆ e0_

Return_rt e0_
private

Definition at line 87 of file CostFunctionCrowdData.h.

Referenced by CostFunctionCrowdData::get_e0().

◆ e2_

Return_rt e2_
private

Definition at line 88 of file CostFunctionCrowdData.h.

Referenced by CostFunctionCrowdData::get_e2().

◆ h0_ptr_list_

◆ h0_res_

ResourceCollection h0_res_
private

resource collection corresponding to h0

Definition at line 81 of file CostFunctionCrowdData.h.

Referenced by CostFunctionCrowdData::CostFunctionCrowdData(), and CostFunctionCrowdData::get_h0_res().

◆ h_ptr_list_

◆ log_psi_fixed_

◆ log_psi_opt_

◆ p_ptr_list_

◆ rng_ptr_list_

◆ rng_save_ptr_

std::unique_ptr<RandomBase<FullPrecRealType> > rng_save_ptr_
private

◆ wf_ptr_list_

◆ wgt2_

Return_rt wgt2_
private

Definition at line 91 of file CostFunctionCrowdData.h.

Referenced by CostFunctionCrowdData::get_wgt2().

◆ wgt_

Return_rt wgt_
private

Definition at line 90 of file CostFunctionCrowdData.h.

Referenced by CostFunctionCrowdData::get_wgt().

◆ qmcplusplus::QMCCostFunction

class qmcplusplus::QMCCostFunction

Implements wave-function optimization.

Optimization by correlated sampling method with configurations generated from VMC running on a single thread.

Definition at line 31 of file QMCCostFunction.h.

+ Inheritance diagram for QMCCostFunction:
+ Collaboration diagram for QMCCostFunction:

Public Member Functions

 QMCCostFunction (MCWalkerConfiguration &w, TrialWaveFunction &psi, QMCHamiltonian &h, Communicate *comm)
 Constructor. More...
 
 ~QMCCostFunction () override
 Destructor. More...
 
void getConfigurations (const std::string &aroot) override
 
void checkConfigurations (EngineHandle &handle) override
 evaluate everything before optimization More...
 
void resetPsi (bool final_reset=false) override
 reset the wavefunction More...
 
void GradCost (std::vector< Return_rt > &PGradient, const std::vector< Return_rt > &PM, Return_rt FiniteDiff=0) override
 
Return_rt fillOverlapHamiltonianMatrices (Matrix< Return_rt > &Left, Matrix< Return_rt > &Right) override
 
- Public Member Functions inherited from QMCCostFunctionBase
 QMCCostFunctionBase (ParticleSet &w, TrialWaveFunction &psi, QMCHamiltonian &h, Communicate *comm)
 Constructor. More...
 
 ~QMCCostFunctionBase () override
 Destructor. More...
 
bool put (xmlNodePtr cur)
 process xml node More...
 
void resetCostFunction (std::vector< xmlNodePtr > &cset)
 
Return_rt & Params (int i) override
 assign optimization parameter i More...
 
Return_t Params (int i) const override
 return optimization parameter i More...
 
int getType (int i) const
 
Return_rt Cost (bool needGrad=true) override
 return the cost value for CGMinimization More...
 
Return_rt computedCost ()
 return the cost value for CGMinimization More...
 
void printEstimates ()
 
void GradCost (std::vector< Return_rt > &PGradient, const std::vector< Return_rt > &PM, Return_rt FiniteDiff=0) override
 return the gradient of cost value for CGMinimization More...
 
int getNumParams () const override
 return the number of optimizable parameters More...
 
int getNumSamples () const
 return the global number of samples More...
 
void setNumSamples (int newNumSamples)
 
void getParameterTypes (std::vector< int > &types) const
 
void Report () override
 dump the current parameters and other report More...
 
void reportParameters ()
 report parameters at the end More...
 
void reportParametersH5 ()
 report parameters in HDF5 at the end More...
 
int getReportCounter () const
 return the counter which keeps track of optimization steps More...
 
void setWaveFunctionNode (xmlNodePtr cur)
 
void setTargetEnergy (Return_rt et)
 
void setRootName (const std::string &aroot)
 
void setStream (std::ostream *os)
 
void addCoefficients (xmlXPathContextPtr acontext, const char *cname)
 add coefficient or coefficients More...
 
void printCJParams (xmlNodePtr cur, std::string &rname)
 
void addCJParams (xmlXPathContextPtr acontext, const char *cname)
 
void setRng (RefVector< RandomBase< FullPrecRealType >> r)
 
bool getneedGrads () const
 
void setneedGrads (bool tf)
 
void setDMC ()
 
std::string getParamName (int i) const override
 
const opt_variables_typegetOptVariables () const
 
Return_rt getVariance () const
 return variance after checkConfigurations More...
 
- Public Member Functions inherited from MPIObjectBase
 MPIObjectBase (Communicate *c)
 constructor with communicator More...
 
int rank () const
 return the rank of the communicator More...
 
int getGroupID () const
 return the group id of the communicator More...
 
CommunicategetCommunicator () const
 return myComm More...
 
CommunicategetCommRef () const
 return a TEMPORARY reference to Communicate More...
 
mpi_comm_type getMPI () const
 return MPI communicator if one wants to use MPI directly More...
 
bool is_manager () const
 return true if the rank == 0 More...
 
const std::string & getName () const
 return the name More...
 
void setName (const std::string &aname)
 
- Public Member Functions inherited from CloneManager
 CloneManager ()
 Constructor. More...
 
virtual ~CloneManager ()
 virtual destructor More...
 
void makeClones (MCWalkerConfiguration &w, TrialWaveFunction &psi, QMCHamiltonian &ham)
 
void makeClones (MCWalkerConfiguration &w, std::vector< TrialWaveFunction *> &psi, std::vector< QMCHamiltonian *> &ham)
 
void makeClones (MCWalkerConfiguration &wg, TrialWaveFunction &guide)
 
void makeClones (TrialWaveFunction &guide)
 
RealType acceptRatio () const
 

Protected Member Functions

EffectiveWeight correlatedSampling (bool needGrad=true) override
 run correlated sampling return effective walkers ( w_i)^2/(Nw * w^2_i) More...
 
- Protected Member Functions inherited from QMCCostFunctionBase
bool checkParameters ()
 Apply constraints on the optimizables. More...
 
void updateXmlNodes ()
 
bool isEffectiveWeightValid (EffectiveWeight effective_weight) const
 check the validity of the effective weight calculated by correlatedSampling More...
 
UniqueOptObjRefs extractOptimizableObjects (TrialWaveFunction &psi) const
 survey all the optimizable objects More...
 
void resetOptimizableObjects (TrialWaveFunction &psi, const opt_variables_type &opt_variables) const
 
- Protected Member Functions inherited from CloneManager
RefVector< WalkerLogCollectorgetWalkerLogCollectorRefs ()
 

Protected Attributes

std::vector< std::unique_ptr< HamiltonianRef > > H_KE_Node
 
std::vector< Matrix< Return_rt > * > RecordsOnNode
 
std::vector< Matrix< Return_t > * > DerivRecords
 Temp derivative properties and Hderivative properties of all the walkers. More...
 
std::vector< Matrix< Return_rt > * > HDerivRecords
 
Return_rt CSWeight
 
NewTimerfill_timer_
 
- Protected Attributes inherited from QMCCostFunctionBase
ParticleSetW
 Particle set. More...
 
TrialWaveFunctionPsi
 Trial function. More...
 
QMCHamiltonianH
 Hamiltonian. More...
 
bool Write2OneXml
 if true, do not write the *.opt.#.xml More...
 
int PowerE
 |E-E_T|^PowerE is used for the cost function More...
 
int NumCostCalls
 number of times cost function evaluated More...
 
int NumSamples
 global number of samples to use in correlated sampling More...
 
int NumOptimizables
 total number of optimizable variables More...
 
int ReportCounter
 counter for output More...
 
Return_rt w_en
 weights for energy and variance in the cost function More...
 
Return_rt w_var
 
Return_rt w_abs
 
Return_rt w_w
 
Return_rt CostValue
 value of the cost function More...
 
Return_rt Etarget
 target energy More...
 
Return_rt EtargetEff
 real target energy with the Correlation Factor More...
 
Return_rt MinNumWalkers
 fraction of the number of walkers below which the costfunction becomes invalid More...
 
Return_rt MaxWeight
 maximum weight beyond which the weight is set to 1 More...
 
Return_rt curAvg
 current Average More...
 
Return_rt curVar
 current Variance More...
 
Return_rt curAvg_w
 current weighted average (correlated sampling) More...
 
Return_rt curVar_w
 current weighted variance (correlated sampling) More...
 
Return_rt curVar_abs
 current variance of SUM_ABSE_WGT/SUM_WGT More...
 
Return_rt w_beta
 
Return_rt vmc_or_dmc
 
bool needGrads
 
std::string targetExcitedStr
 whether we are targeting an excited state More...
 
bool targetExcited
 whether we are targeting an excited state More...
 
double omega_shift
 the shift to use when targeting an excited state More...
 
opt_variables_type OptVariables
 list of optimizables More...
 
opt_variables_type OptVariablesForPsi
 full list of optimizables More...
 
opt_variables_type InitVariables
 
std::vector< TinyVector< int, 2 > > equalVarMap
 index mapping for <equal> constraints More...
 
std::vector< TinyVector< int, 2 > > negateVarMap
 index mapping for <negate> constraints More...
 
std::ostream * msg_stream
 stream to which progress is sent More...
 
xmlNodePtr m_wfPtr
 xml node to be dumped More...
 
xmlDocPtr m_doc_out
 document node to be dumped More...
 
std::map< std::string, xmlNodePtr > paramNodes
 parameters to be updated` More...
 
std::map< std::string, xmlNodePtr > coeffNodes
 coefficients to be updated More...
 
std::map< std::string, std::pair< xmlNodePtr, std::string > > attribNodes
 attributes to be updated More...
 
std::string RootName
 string for the file root More...
 
UPtrVector< RandomBase< FullPrecRealType > > RngSaved
 Random number generators. More...
 
std::vector< RandomBase< FullPrecRealType > * > MoverRng
 
std::vector< std::string > variational_subset_names
 optimized parameter names More...
 
std::vector< Return_rt > SumValue
 Sum of energies and weights for averages. More...
 
Matrix< Return_rt > Records
 Saved properties of all the walkers. More...
 
std::vector< ParticleGradient * > dLogPsi
 Fixed Gradients , $\nabla\ln\Psi$, components. More...
 
std::vector< ParticleLaplacian * > d2LogPsi
 Fixed Laplacian , $\nabla^2\ln\Psi$, components. More...
 
std::unique_ptr< std::ostream > debug_stream
 stream for debug More...
 
bool do_override_output
 Flag on whether the variational parameter override is output to the new wavefunction. More...
 
- Protected Attributes inherited from MPIObjectBase
CommunicatemyComm
 pointer to Communicate More...
 
std::string ClassName
 class Name More...
 
std::string myName
 name of the object More...
 
- Protected Attributes inherited from CloneManager
const IndexType NumThreads
 number of threads More...
 
std::vector< QMCUpdateBase * > Movers
 update engines More...
 
std::vector< EstimatorManagerBase * > estimatorClones
 estimator managers More...
 
std::vector< TraceManager * > traceClones
 trace managers More...
 
UPtrVector< WalkerLogCollectorwlog_collectors
 trace collectors More...
 
UPtrVector< CSUpdateBaseCSMovers
 
std::vector< int > wPerRank
 Walkers per MPI rank. More...
 

Additional Inherited Members

- Public Types inherited from QMCCostFunctionBase
enum  FieldIndex_OPT {
  LOGPSI_FIXED = 0, LOGPSI_FREE = 1, ENERGY_TOT = 2, ENERGY_FIXED = 3,
  ENERGY_NEW = 4, REWEIGHT = 5
}
 
enum  SumIndex_OPT {
  SUM_E_BARE = 0, SUM_ESQ_BARE, SUM_ABSE_BARE, SUM_E_WGT,
  SUM_ESQ_WGT, SUM_ABSE_WGT, SUM_WGT, SUM_WGTSQ,
  SUM_INDEX_SIZE
}
 
using EffectiveWeight = QMCTraits::QTFull::RealType
 
using FullPrecRealType = QMCTraits::FullPrecRealType
 
- Public Types inherited from MPIObjectBase
using mpi_comm_type = Communicate::mpi_comm_type
 
- Public Types inherited from QMCTraits
enum  { DIM = OHMMS_DIM, DIM_VGL = OHMMS_DIM + 2 }
 
using QTBase = QMCTypes< OHMMS_PRECISION, DIM >
 
using QTFull = QMCTypes< OHMMS_PRECISION_FULL, DIM >
 
using RealType = QTBase::RealType
 
using ComplexType = QTBase::ComplexType
 
using ValueType = QTBase::ValueType
 
using PosType = QTBase::PosType
 
using GradType = QTBase::GradType
 
using TensorType = QTBase::TensorType
 
using IndexType = OHMMS_INDEXTYPE
 define other types More...
 
using FullPrecRealType = QTFull::RealType
 
using FullPrecValueType = QTFull::ValueType
 
using PropertySetType = RecordNamedProperty< FullPrecRealType >
 define PropertyList_t More...
 
using PtclGrpIndexes = std::vector< std::pair< int, int > >
 
- Static Public Member Functions inherited from CloneManager
static void clearClones ()
 
- Public Attributes inherited from QMCCostFunctionBase
bool reportH5
 Save opt parameters to HDF5. More...
 
bool CI_Opt
 
std::string newh5
 Path and name of the HDF5 prefix where CI coeffs are saved. More...
 
- Protected Types inherited from QMCCostFunctionBase
using ParticleGradient = ParticleSet::ParticleGradient
 Saved derivative properties and Hderivative properties of all the walkers. More...
 
using ParticleLaplacian = ParticleSet::ParticleLaplacian
 
- Static Protected Attributes inherited from CloneManager
static UPtrVector< MCWalkerConfigurationwClones_uptr
 walkers More...
 
static std::vector< MCWalkerConfiguration * > wClones
 
static UPtrVector< MCWalkerConfigurationwgClones
 
static UPtrVector< TrialWaveFunctionpsiClones_uptr
 trial wavefunctions More...
 
static std::vector< TrialWaveFunction * > psiClones
 
static UPtrVector< TrialWaveFunctionguideClones_uptr
 guide wavefunctions More...
 
static std::vector< TrialWaveFunction * > guideClones
 
static UPtrVector< QMCHamiltonianhClones_uptr
 Hamiltonians. More...
 
static std::vector< QMCHamiltonian * > hClones
 
static std::vector< UPtrVector< MCWalkerConfiguration > > WPoolClones_uptr
 
static std::vector< std::vector< MCWalkerConfiguration * > > WPoolClones
 
static std::vector< UPtrVector< TrialWaveFunction > > PsiPoolClones_uptr
 
static std::vector< std::vector< TrialWaveFunction * > > PsiPoolClones
 
static std::vector< UPtrVector< QMCHamiltonian > > HPoolClones_uptr
 
static std::vector< std::vector< QMCHamiltonian * > > HPoolClones
 

Constructor & Destructor Documentation

◆ QMCCostFunction()

Constructor.

Definition at line 28 of file QMCCostFunction.cpp.

References qmcplusplus::app_log(), and QMCCostFunction::CSWeight.

29  : QMCCostFunctionBase(w, psi, h, comm),
30  fill_timer_(createGlobalTimer("QMCCostFunction::fillOverlapHamiltonianMatrices", timer_level_medium))
31 {
32  CSWeight = 1.0;
33  app_log() << " Using QMCCostFunction::QMCCostFunction" << std::endl;
34 }
std::ostream & app_log()
Definition: OutputManager.h:65
NewTimer & createGlobalTimer(const std::string &myname, timer_levels mylevel)
QMCCostFunctionBase(ParticleSet &w, TrialWaveFunction &psi, QMCHamiltonian &h, Communicate *comm)
Constructor.

◆ ~QMCCostFunction()

~QMCCostFunction ( )
override

Destructor.

Clean up the vector.

Definition at line 38 of file QMCCostFunction.cpp.

References qmcplusplus::delete_iter(), QMCCostFunction::DerivRecords, QMCCostFunction::HDerivRecords, and QMCCostFunction::RecordsOnNode.

39 {
40  delete_iter(RecordsOnNode.begin(), RecordsOnNode.end());
41  delete_iter(DerivRecords.begin(), DerivRecords.end());
42  delete_iter(HDerivRecords.begin(), HDerivRecords.end());
43 }
void delete_iter(IT first, IT last)
delete the pointers in [first,last)
std::vector< Matrix< Return_t > * > DerivRecords
Temp derivative properties and Hderivative properties of all the walkers.
std::vector< Matrix< Return_rt > * > HDerivRecords
std::vector< Matrix< Return_rt > * > RecordsOnNode

Member Function Documentation

◆ checkConfigurations()

void checkConfigurations ( EngineHandle handle)
overridevirtual

evaluate everything before optimization

Implements QMCCostFunctionBase.

Definition at line 226 of file QMCCostFunction.cpp.

References Communicate::allreduce(), qmcplusplus::app_log(), Vector< T, Alloc >::begin(), copy(), QMCCostFunctionBase::d2LogPsi, QMCCostFunction::DerivRecords, QMCCostFunctionBase::dLogPsi, Vector< T, Alloc >::end(), QMCCostFunctionBase::ENERGY_FIXED, QMCCostFunctionBase::ENERGY_NEW, QMCCostFunctionBase::ENERGY_TOT, QMCCostFunctionBase::Etarget, CloneManager::hClones, QMCCostFunction::HDerivRecords, MCWalkerConfiguration::loadSample(), QMCCostFunctionBase::LOGPSI_FIXED, QMCCostFunctionBase::LOGPSI_FREE, QMCCostFunctionBase::MoverRng, MPIObjectBase::myComm, QMCCostFunctionBase::needGrads, QMCCostFunctionBase::NumOptimizables, MCWalkerConfiguration::numSamples(), QMCCostFunctionBase::NumSamples, CloneManager::NumThreads, omp_get_thread_num(), QMCCostFunctionBase::OptVariablesForPsi, CloneManager::psiClones, QMCCostFunction::RecordsOnNode, QMCCostFunctionBase::ReportCounter, QMCCostFunctionBase::REWEIGHT, QMCCostFunctionBase::RngSaved, VariableSet::setComputed(), QMCCostFunctionBase::setTargetEnergy(), QMCCostFunctionBase::SUM_ABSE_BARE, QMCCostFunctionBase::SUM_E_BARE, QMCCostFunctionBase::SUM_E_WGT, QMCCostFunctionBase::SUM_ESQ_BARE, QMCCostFunctionBase::SUM_ESQ_WGT, QMCCostFunctionBase::SUM_INDEX_SIZE, QMCCostFunctionBase::SUM_WGT, QMCCostFunctionBase::SUM_WGTSQ, QMCCostFunctionBase::SumValue, ParticleSet::update(), CloneManager::wClones, and CloneManager::wPerRank.

227 {
228  RealType et_tot = 0.0;
229  RealType e2_tot = 0.0;
230 #pragma omp parallel reduction(+ : et_tot, e2_tot)
231  {
232  int ip = omp_get_thread_num();
233  MCWalkerConfiguration& wRef(*wClones[ip]);
234  if (RecordsOnNode[ip] == 0)
235  {
236  RecordsOnNode[ip] = new Matrix<Return_rt>;
237  RecordsOnNode[ip]->resize(wRef.numSamples(), SUM_INDEX_SIZE);
238  if (needGrads)
239  {
240  DerivRecords[ip] = new Matrix<Return_t>;
241  DerivRecords[ip]->resize(wRef.numSamples(), NumOptimizables);
242  HDerivRecords[ip] = new Matrix<Return_rt>;
243  HDerivRecords[ip]->resize(wRef.numSamples(), NumOptimizables);
244  }
245  }
246  else if (RecordsOnNode[ip]->size1() != wRef.numSamples())
247  {
248  RecordsOnNode[ip]->resize(wRef.numSamples(), SUM_INDEX_SIZE);
249  if (needGrads)
250  {
251  DerivRecords[ip]->resize(wRef.numSamples(), NumOptimizables);
252  HDerivRecords[ip]->resize(wRef.numSamples(), NumOptimizables);
253  }
254  }
255  // Populate local to global index mapping into psiClone internal component 'myVars',
256  // because psiClones persist between different sections and need update.
257  psiClones[ip]->checkOutVariables(OptVariablesForPsi);
258  // synchronize the random number generator with the node
259  (*MoverRng[ip]) = (*RngSaved[ip]);
260  hClones[ip]->setRandomGenerator(MoverRng[ip]);
261  //int nat = wRef.getTotalNum();
262  Return_rt e0 = 0.0;
263  // Return_t ef=0.0;
264  Return_rt e2 = 0.0;
265  for (int iw = 0, iwg = wPerRank[ip]; iw < wRef.numSamples(); ++iw, ++iwg)
266  {
267  wRef.loadSample(wRef, iw);
268  wRef.update();
269  Return_rt* restrict saved = (*RecordsOnNode[ip])[iw];
270  psiClones[ip]->evaluateDeltaLogSetup(wRef, saved[LOGPSI_FIXED], saved[LOGPSI_FREE], *dLogPsi[iwg],
271  *d2LogPsi[iwg]);
272  saved[REWEIGHT] = 1.0;
273  Return_rt etmp;
274  if (needGrads)
275  {
276  //allocate vector
277  Vector<Return_rt> rDsaved(NumOptimizables, 0.0);
278  Vector<Return_rt> rHDsaved(NumOptimizables, 0.0);
279 
280  Vector<Return_t> Dsaved(NumOptimizables, 0.0);
281  Vector<Return_t> HDsaved(NumOptimizables, 0.0);
282 
283  etmp = hClones[ip]->evaluateValueAndDerivatives(wRef, OptVariablesForPsi, Dsaved, HDsaved);
284 
285 
286  //FIXME the ifdef should be removed after the optimizer is made compatible with complex coefficients
287  for (int i = 0; i < NumOptimizables; i++)
288  {
289  rHDsaved[i] = std::real(HDsaved[i]);
290  }
291  std::copy(Dsaved.begin(), Dsaved.end(), (*DerivRecords[ip])[iw]);
292  std::copy(rHDsaved.begin(), rHDsaved.end(), (*HDerivRecords[ip])[iw]);
293  }
294  else
295  etmp = hClones[ip]->evaluate(wRef);
296 
297  e0 += saved[ENERGY_TOT] = saved[ENERGY_NEW] = etmp;
298  e2 += etmp * etmp;
299  saved[ENERGY_FIXED] = saved[ENERGY_TOT];
300  const auto twf_dependent_components = hClones[ip]->getTWFDependentComponents();
301  for (const OperatorBase& component : twf_dependent_components)
302  saved[ENERGY_FIXED] -= component.getValue();
303  }
304  //add them all using reduction
305  et_tot += e0;
306  e2_tot += e2;
307  // #pragma omp atomic
308  // eft_tot+=ef;
309  }
311  // app_log() << " VMC Efavg = " << eft_tot/static_cast<Return_t>(wPerRank[NumThreads]) << std::endl;
312  //Need to sum over the processors
313  std::vector<Return_rt> etemp(3);
314  etemp[0] = et_tot;
315  etemp[1] = static_cast<Return_rt>(wPerRank[NumThreads]);
316  etemp[2] = e2_tot;
317  myComm->allreduce(etemp);
318  Etarget = static_cast<Return_rt>(etemp[0] / etemp[1]);
319  NumSamples = static_cast<int>(etemp[1]);
320  app_log() << " VMC Eavg = " << Etarget << std::endl;
321  app_log() << " VMC Evar = " << etemp[2] / etemp[1] - Etarget * Etarget << std::endl;
322  app_log() << " Total weights = " << etemp[1] << std::endl;
323  app_log().flush();
325  ReportCounter = 0;
326  IsValid = true;
327  //collect SumValue for computedCost
328  SumValue[SUM_WGT] = etemp[1];
329  SumValue[SUM_WGTSQ] = etemp[1];
330  SumValue[SUM_E_WGT] = etemp[0];
331  SumValue[SUM_ESQ_WGT] = etemp[2];
332  SumValue[SUM_E_BARE] = etemp[0];
333  SumValue[SUM_ESQ_BARE] = etemp[2];
334  SumValue[SUM_ABSE_BARE] = 0.0;
335 }
std::vector< ParticleLaplacian * > d2LogPsi
Fixed Laplacian , , components.
static std::vector< TrialWaveFunction * > psiClones
Definition: CloneManager.h:65
QMCTraits::RealType real
std::vector< int > wPerRank
Walkers per MPI rank.
Definition: CloneManager.h:91
int NumSamples
global number of samples to use in correlated sampling
static std::vector< MCWalkerConfiguration * > wClones
Definition: CloneManager.h:61
std::ostream & app_log()
Definition: OutputManager.h:65
int NumOptimizables
total number of optimizable variables
UPtrVector< RandomBase< FullPrecRealType > > RngSaved
Random number generators.
void copy(const Array< T1, 3 > &src, Array< T2, 3 > &dest)
Definition: Blitz.h:639
void allreduce(T &)
omp_int_t omp_get_thread_num()
Definition: OpenMP.h:25
std::vector< ParticleGradient * > dLogPsi
Fixed Gradients , , components.
Communicate * myComm
pointer to Communicate
Definition: MPIObjectBase.h:62
std::vector< Matrix< Return_t > * > DerivRecords
Temp derivative properties and Hderivative properties of all the walkers.
opt_variables_type OptVariablesForPsi
full list of optimizables
const IndexType NumThreads
number of threads
Definition: CloneManager.h:54
int ReportCounter
counter for output
static std::vector< QMCHamiltonian * > hClones
Definition: CloneManager.h:71
QMCTraits::RealType RealType
std::vector< Return_rt > SumValue
Sum of energies and weights for averages.
std::vector< Matrix< Return_rt > * > HDerivRecords
std::vector< Matrix< Return_rt > * > RecordsOnNode
std::vector< RandomBase< FullPrecRealType > * > MoverRng

◆ correlatedSampling()

QMCCostFunction::EffectiveWeight correlatedSampling ( bool  needGrad = true)
overrideprotectedvirtual

run correlated sampling return effective walkers ( w_i)^2/(Nw * w^2_i)

Implements QMCCostFunctionBase.

Definition at line 515 of file QMCCostFunction.cpp.

References qmcplusplus::abs(), Communicate::allreduce(), Communicate::barrier(), OHMMS::Controller, QMCCostFunction::CSWeight, QMCCostFunctionBase::d2LogPsi, QMCCostFunction::DerivRecords, QMCCostFunctionBase::dLogPsi, QMCCostFunctionBase::ENERGY_FIXED, QMCCostFunctionBase::ENERGY_NEW, QMCCostFunctionBase::EtargetEff, qmcplusplus::exp(), ParticleSet::G, QMCCostFunction::H_KE_Node, CloneManager::hClones, QMCCostFunction::HDerivRecords, ParticleSet::L, MCWalkerConfiguration::loadSample(), QMCCostFunctionBase::LOGPSI_FREE, QMCCostFunctionBase::MaxWeight, omptarget::min(), QMCCostFunctionBase::MoverRng, MPIObjectBase::myComm, QMCCostFunctionBase::NumOptimizables, MCWalkerConfiguration::numSamples(), QMCCostFunctionBase::NumSamples, CloneManager::NumThreads, omp_get_thread_num(), QMCCostFunctionBase::OptVariablesForPsi, qmcplusplus::pow(), QMCCostFunctionBase::PowerE, CloneManager::psiClones, VariableSet::recompute(), QMCCostFunction::RecordsOnNode, QMCCostFunctionBase::REWEIGHT, QMCCostFunctionBase::RngSaved, QMCCostFunctionBase::SUM_ABSE_BARE, QMCCostFunctionBase::SUM_ABSE_WGT, QMCCostFunctionBase::SUM_E_BARE, QMCCostFunctionBase::SUM_E_WGT, QMCCostFunctionBase::SUM_ESQ_BARE, QMCCostFunctionBase::SUM_ESQ_WGT, QMCCostFunctionBase::SUM_WGT, QMCCostFunctionBase::SUM_WGTSQ, QMCCostFunctionBase::SumValue, ParticleSet::update(), QMCCostFunctionBase::vmc_or_dmc, CloneManager::wClones, and CloneManager::wPerRank.

Referenced by QMCCostFunction::GradCost().

516 {
517  for (int ip = 0; ip < NumThreads; ++ip)
518  {
519  // synchronize the random number generator with the node
520  (*MoverRng[ip]) = (*RngSaved[ip]);
521  hClones[ip]->setRandomGenerator(MoverRng[ip]);
522  }
523 
524  Return_rt wgt_tot = 0.0;
525  Return_rt wgt_tot2 = 0.0;
526  Return_rt inv_n_samples = 1.0 / NumSamples;
527 #pragma omp parallel reduction(+ : wgt_tot, wgt_tot2)
528  {
529  const int ip = omp_get_thread_num();
530  //if we have more than KE depending on TWF, TWF must be fully recomputed.
531  const bool compute_all_from_scratch = hClones[ip]->getTWFDependentComponents().size() > 1;
532 
533  MCWalkerConfiguration& wRef(*wClones[ip]);
534  Return_rt wgt_node = 0.0, wgt_node2 = 0.0;
535  for (int iw = 0, iwg = wPerRank[ip]; iw < wRef.numSamples(); ++iw, ++iwg)
536  {
537  wRef.loadSample(wRef, iw);
538  wRef.update(true);
539  Return_rt* restrict saved = (*RecordsOnNode[ip])[iw];
540  Return_rt logpsi;
541  logpsi = psiClones[ip]->evaluateDeltaLog(wRef, compute_all_from_scratch);
542  wRef.G += *dLogPsi[iwg];
543  wRef.L += *d2LogPsi[iwg];
544  Return_rt weight = saved[REWEIGHT] = vmc_or_dmc * (logpsi - saved[LOGPSI_FREE]);
545  if (needGrad)
546  {
547  Vector<Return_t> Dsaved(NumOptimizables, 0);
548  Vector<Return_t> HDsaved(NumOptimizables, 0);
549 
550  Vector<Return_rt> rDsaved(NumOptimizables, 0);
551  Vector<Return_rt> rHDsaved(NumOptimizables, 0);
552 
553  saved[ENERGY_NEW] =
554  H_KE_Node[ip]->evaluateValueAndDerivatives(wRef, OptVariablesForPsi, Dsaved, HDsaved) + saved[ENERGY_FIXED];
555  ;
556 
557  for (int i = 0; i < NumOptimizables; i++)
558  {
559  rDsaved[i] = std::real(Dsaved[i]);
560  rHDsaved[i] = std::real(HDsaved[i]);
561  }
562 
563  for (int i = 0; i < NumOptimizables; i++)
565  {
566  (*DerivRecords[ip])(iw, i) = rDsaved[i];
567  (*HDerivRecords[ip])(iw, i) = rHDsaved[i];
568  }
569  }
570  else
571  saved[ENERGY_NEW] = H_KE_Node[ip]->evaluate(wRef) + saved[ENERGY_FIXED];
572  wgt_node += inv_n_samples * weight;
573  wgt_node2 += inv_n_samples * weight * weight;
574  }
575  wgt_tot += wgt_node;
576  wgt_tot2 += wgt_node2;
577  }
578  //this is MPI barrier
580  //collect the total weight for normalization and apply maximum weight
581  myComm->allreduce(wgt_tot);
582  myComm->allreduce(wgt_tot2);
583  // app_log()<<"Before Purge"<<wgt_tot<<" "<<wgt_tot2<< std::endl;
584  Return_rt wgtnorm = (wgt_tot == 0) ? 0 : wgt_tot;
585  wgt_tot = 0.0;
586  for (int ip = 0; ip < NumThreads; ip++)
587  {
588  int nw = wClones[ip]->numSamples();
589  for (int iw = 0; iw < nw; iw++)
590  {
591  Return_rt* restrict saved = (*RecordsOnNode[ip])[iw];
592  saved[REWEIGHT] =
593  std::min(std::exp(saved[REWEIGHT] - wgtnorm), std::numeric_limits<Return_rt>::max() * (RealType)0.1);
594  wgt_tot += inv_n_samples * saved[REWEIGHT];
595  }
596  }
597  myComm->allreduce(wgt_tot);
598  // app_log()<<"During Purge"<<wgt_tot<<" "<< std::endl;
599  wgtnorm = (wgt_tot == 0) ? 1 : 1.0 / wgt_tot;
600  wgt_tot = 0.0;
601  for (int ip = 0; ip < NumThreads; ip++)
602  {
603  int nw = wClones[ip]->numSamples();
604  for (int iw = 0; iw < nw; iw++)
605  {
606  Return_rt* restrict saved = (*RecordsOnNode[ip])[iw];
607  saved[REWEIGHT] = std::min(saved[REWEIGHT] * wgtnorm, MaxWeight);
608  wgt_tot += inv_n_samples * saved[REWEIGHT];
609  }
610  }
611  myComm->allreduce(wgt_tot);
612  // app_log()<<"After Purge"<<wgt_tot<<" "<< std::endl;
613  for (int i = 0; i < SumValue.size(); i++)
614  SumValue[i] = 0.0;
615  CSWeight = wgt_tot = (wgt_tot == 0) ? 1 : 1.0 / wgt_tot;
616  for (int ip = 0; ip < NumThreads; ip++)
617  {
618  int nw = wClones[ip]->numSamples();
619  for (int iw = 0; iw < nw; iw++)
620  {
621  const Return_rt* restrict saved = (*RecordsOnNode[ip])[iw];
622  // Return_t weight=saved[REWEIGHT]*wgt_tot;
623  Return_rt eloc_new = saved[ENERGY_NEW];
624  Return_rt delE = std::pow(std::abs(eloc_new - EtargetEff), PowerE);
625  SumValue[SUM_E_BARE] += eloc_new;
626  SumValue[SUM_ESQ_BARE] += eloc_new * eloc_new;
627  SumValue[SUM_ABSE_BARE] += delE;
628  SumValue[SUM_E_WGT] += eloc_new * saved[REWEIGHT];
629  SumValue[SUM_ESQ_WGT] += eloc_new * eloc_new * saved[REWEIGHT];
630  SumValue[SUM_ABSE_WGT] += delE * saved[REWEIGHT];
631  SumValue[SUM_WGT] += saved[REWEIGHT];
632  SumValue[SUM_WGTSQ] += saved[REWEIGHT] * saved[REWEIGHT];
633  }
634  }
635  //collect everything
638 }
std::vector< ParticleLaplacian * > d2LogPsi
Fixed Laplacian , , components.
bool recompute(int i) const
Definition: VariableSet.h:206
void barrier() const
static std::vector< TrialWaveFunction * > psiClones
Definition: CloneManager.h:65
QMCTraits::RealType real
std::vector< int > wPerRank
Walkers per MPI rank.
Definition: CloneManager.h:91
int NumSamples
global number of samples to use in correlated sampling
MakeReturn< UnaryNode< FnFabs, typename CreateLeaf< Vector< T1, C1 > >::Leaf_t > >::Expression_t abs(const Vector< T1, C1 > &l)
static std::vector< MCWalkerConfiguration * > wClones
Definition: CloneManager.h:61
int NumOptimizables
total number of optimizable variables
UPtrVector< RandomBase< FullPrecRealType > > RngSaved
Random number generators.
Communicate * Controller
Global Communicator for a process.
Definition: Communicate.cpp:35
std::vector< std::unique_ptr< HamiltonianRef > > H_KE_Node
T min(T a, T b)
void allreduce(T &)
MakeReturn< BinaryNode< FnPow, typename CreateLeaf< Vector< T1, C1 > >::Leaf_t, typename CreateLeaf< Vector< T2, C2 > >::Leaf_t > >::Expression_t pow(const Vector< T1, C1 > &l, const Vector< T2, C2 > &r)
omp_int_t omp_get_thread_num()
Definition: OpenMP.h:25
std::vector< ParticleGradient * > dLogPsi
Fixed Gradients , , components.
Communicate * myComm
pointer to Communicate
Definition: MPIObjectBase.h:62
std::vector< Matrix< Return_t > * > DerivRecords
Temp derivative properties and Hderivative properties of all the walkers.
opt_variables_type OptVariablesForPsi
full list of optimizables
const IndexType NumThreads
number of threads
Definition: CloneManager.h:54
MakeReturn< UnaryNode< FnExp, typename CreateLeaf< Vector< T1, C1 > >::Leaf_t > >::Expression_t exp(const Vector< T1, C1 > &l)
static std::vector< QMCHamiltonian * > hClones
Definition: CloneManager.h:71
QMCTraits::RealType RealType
std::vector< Return_rt > SumValue
Sum of energies and weights for averages.
Return_rt MaxWeight
maximum weight beyond which the weight is set to 1
std::vector< Matrix< Return_rt > * > HDerivRecords
int PowerE
|E-E_T|^PowerE is used for the cost function
std::vector< Matrix< Return_rt > * > RecordsOnNode
Return_rt EtargetEff
real target energy with the Correlation Factor
std::vector< RandomBase< FullPrecRealType > * > MoverRng

◆ fillOverlapHamiltonianMatrices()

QMCCostFunction::Return_rt fillOverlapHamiltonianMatrices ( Matrix< Return_rt > &  Left,
Matrix< Return_rt > &  Right 
)
overridevirtual

Implements QMCCostFunctionBase.

Definition at line 641 of file QMCCostFunction.cpp.

References Communicate::allreduce(), qmcplusplus::conj(), QMCCostFunctionBase::curAvg_w, QMCCostFunction::DerivRecords, QMCCostFunctionBase::ENERGY_NEW, QMCCostFunction::fill_timer_, QMCCostFunctionBase::getNumParams(), QMCCostFunction::HDerivRecords, MPIObjectBase::myComm, CloneManager::NumThreads, qmcplusplus::Units::distance::pm, QMCCostFunction::RecordsOnNode, QMCCostFunctionBase::REWEIGHT, QMCCostFunctionBase::SUM_E_WGT, QMCCostFunctionBase::SUM_ESQ_WGT, QMCCostFunctionBase::SUM_WGT, QMCCostFunctionBase::SumValue, QMCCostFunctionBase::w_beta, and CloneManager::wClones.

643 {
644  ScopedTimer tmp_timer(fill_timer_);
645 
646  RealType b2(w_beta);
647 
648  Right = 0.0;
649  Left = 0.0;
650 
651  // resetPsi();
653  Return_rt curAvg2_w = SumValue[SUM_ESQ_WGT] / SumValue[SUM_WGT];
654  RealType V_avg = curAvg2_w - curAvg_w * curAvg_w;
655  std::vector<Return_t> D_avg(getNumParams(), 0.0);
656  Return_rt wgtinv = 1.0 / SumValue[SUM_WGT];
657  for (int ip = 0; ip < NumThreads; ip++)
658  {
659  int nw = wClones[ip]->numSamples();
660  for (int iw = 0; iw < nw; iw++)
661  {
662  const Return_rt* restrict saved = (*RecordsOnNode[ip])[iw];
663  Return_rt weight = saved[REWEIGHT] * wgtinv;
664  const Return_t* Dsaved = (*DerivRecords[ip])[iw];
665  for (int pm = 0; pm < getNumParams(); pm++)
666  {
667  D_avg[pm] += Dsaved[pm] * weight;
668  }
669  }
670  }
671 
672  myComm->allreduce(D_avg);
673 
674  for (int ip = 0; ip < NumThreads; ip++)
675  {
676  int nw = wClones[ip]->numSamples();
677  for (int iw = 0; iw < nw; iw++)
678  {
679  const Return_rt* restrict saved = (*RecordsOnNode[ip])[iw];
680  Return_rt weight = saved[REWEIGHT] * wgtinv;
681  Return_rt eloc_new = saved[ENERGY_NEW];
682  const Return_t* Dsaved = (*DerivRecords[ip])[iw];
683  const Return_rt* HDsaved = (*HDerivRecords[ip])[iw];
684 #pragma omp parallel for
685  for (int pm = 0; pm < getNumParams(); pm++)
686  {
687  Return_t wfe = (HDsaved[pm] + (Dsaved[pm] - D_avg[pm]) * eloc_new) * weight;
688  Return_t wfd = (Dsaved[pm] - D_avg[pm]) * weight;
689  Return_t vterm = HDsaved[pm] * (eloc_new - curAvg_w) +
690  (Dsaved[pm] - D_avg[pm]) * eloc_new * (eloc_new - RealType(2.0) * curAvg_w);
691  // Return_t vterm = (HDsaved[pm]+(Dsaved[pm]-D_avg[pm])*eloc_new -curAvg_w)*(eloc_new-curAvg_w);
692  // Variance
693  Left(0, pm + 1) += b2 * std::real(vterm) * weight;
694  Left(pm + 1, 0) += b2 * std::real(vterm) * weight;
695  // Hamiltonian
696  Left(0, pm + 1) += (1 - b2) * std::real(wfe);
697  Left(pm + 1, 0) += (1 - b2) * std::real(wfd) * eloc_new;
698  for (int pm2 = 0; pm2 < getNumParams(); pm2++)
699  {
700  // Hamiltonian
701  Left(pm + 1, pm2 + 1) +=
702  std::real((1 - b2) * std::conj(wfd) * (HDsaved[pm2] + (Dsaved[pm2] - D_avg[pm2]) * eloc_new));
703  // Overlap
704  RealType ovlij = std::real(std::conj(wfd) * (Dsaved[pm2] - D_avg[pm2]));
705  Right(pm + 1, pm2 + 1) += ovlij;
706  // Variance
707  RealType varij = weight *
708  std::real((HDsaved[pm] - RealType(2.0) * std::conj(Dsaved[pm] - D_avg[pm]) * eloc_new) *
709  (HDsaved[pm2] - RealType(2.0) * (Dsaved[pm2] - D_avg[pm2]) * eloc_new));
710  // RealType varij=weight*(HDsaved[pm] +(Dsaved[pm]-D_avg[pm])*eloc_new-curAvg_w)*
711  // (HDsaved[pm2] + (Dsaved[pm2]-D_avg[pm2])*eloc_new-curAvg_w);
712  Left(pm + 1, pm2 + 1) += b2 * (varij + V_avg * ovlij);
713  }
714  }
715  }
716  }
717  myComm->allreduce(Right);
718  myComm->allreduce(Left);
719  Left(0, 0) = (1 - b2) * curAvg_w + b2 * V_avg;
720  Right(0, 0) = 1.0;
721 
722  return 1.0;
723 }
QMCTraits::RealType real
QTBase::RealType RealType
Definition: Configuration.h:58
static std::vector< MCWalkerConfiguration * > wClones
Definition: CloneManager.h:61
Return_rt curAvg_w
current weighted average (correlated sampling)
ScopeGuard< NewTimer > ScopedTimer
Definition: NewTimer.h:257
void allreduce(T &)
Communicate * myComm
pointer to Communicate
Definition: MPIObjectBase.h:62
std::vector< Matrix< Return_t > * > DerivRecords
Temp derivative properties and Hderivative properties of all the walkers.
const IndexType NumThreads
number of threads
Definition: CloneManager.h:54
float conj(const float &c)
Workaround to allow conj on scalar to return real instead of complex.
QMCTraits::RealType RealType
std::vector< Return_rt > SumValue
Sum of energies and weights for averages.
int getNumParams() const override
return the number of optimizable parameters
std::vector< Matrix< Return_rt > * > HDerivRecords
std::vector< Matrix< Return_rt > * > RecordsOnNode
BareKineticEnergy::Return_t Return_t

◆ getConfigurations()

void getConfigurations ( const std::string &  aroot)
overridevirtual

Implements QMCCostFunctionBase.

Definition at line 170 of file QMCCostFunction.cpp.

References qmcplusplus::app_log(), QMCCostFunctionBase::d2LogPsi, qmcplusplus::delete_iter(), QMCCostFunction::DerivRecords, QMCCostFunctionBase::dLogPsi, ParticleSet::getTotalNum(), QMCCostFunction::H_KE_Node, CloneManager::hClones, QMCCostFunction::HDerivRecords, CloneManager::NumThreads, QMCCostFunction::RecordsOnNode, QMCCostFunctionBase::W, CloneManager::wClones, and CloneManager::wPerRank.

171 {
172  //makeClones(W,Psi,H);
173  if (H_KE_Node.empty())
174  {
175  app_log() << " QMCCostFunction is created with " << NumThreads << " threads." << std::endl;
176  //make H_KE_Node
177  H_KE_Node.resize(NumThreads);
178  RecordsOnNode.resize(NumThreads, 0);
179  DerivRecords.resize(NumThreads, 0);
180  HDerivRecords.resize(NumThreads, 0);
181  }
182 
183  //#pragma omp parallel for
184  for (int ip = 0; ip < NumThreads; ++ip)
185  if (!H_KE_Node[ip])
186  {
187  auto components = hClones[ip]->getTWFDependentComponents();
188  if (ip == 0)
189  {
190  app_log() << " Found " << components.size() << " wavefunction dependent components in the Hamiltonian";
191  if (components.size())
192  for (const OperatorBase& component : components)
193  app_log() << " '" << component.getName() << "'";
194  app_log() << "." << std::endl;
195  }
196  H_KE_Node[ip] = std::make_unique<HamiltonianRef>(components);
197  }
198 
199  //load samples from SampleStack
200  app_log() << " Number of samples loaded to each thread : ";
201  wPerRank[0] = 0;
202  for (int ip = 0; ip < NumThreads; ++ip)
203  {
204  wPerRank[ip + 1] = wPerRank[ip] + wClones[ip]->numSamples();
205  app_log() << wClones[ip]->numSamples() << " ";
206  }
207  app_log() << std::endl;
208  app_log().flush();
209 
210  if (dLogPsi.size() != wPerRank[NumThreads])
211  {
212  delete_iter(dLogPsi.begin(), dLogPsi.end());
213  delete_iter(d2LogPsi.begin(), d2LogPsi.end());
214  int nptcl = W.getTotalNum();
215  int nwtot = wPerRank[NumThreads];
216  dLogPsi.resize(nwtot);
217  d2LogPsi.resize(nwtot);
218  for (int i = 0; i < nwtot; ++i)
219  dLogPsi[i] = new ParticleGradient(nptcl);
220  for (int i = 0; i < nwtot; ++i)
221  d2LogPsi[i] = new ParticleLaplacian(nptcl);
222  }
223 }
std::vector< ParticleLaplacian * > d2LogPsi
Fixed Laplacian , , components.
void delete_iter(IT first, IT last)
delete the pointers in [first,last)
std::vector< int > wPerRank
Walkers per MPI rank.
Definition: CloneManager.h:91
size_t getTotalNum() const
Definition: ParticleSet.h:493
static std::vector< MCWalkerConfiguration * > wClones
Definition: CloneManager.h:61
std::ostream & app_log()
Definition: OutputManager.h:65
ParticleSet::ParticleLaplacian ParticleLaplacian
ParticleSet::ParticleGradient ParticleGradient
Saved derivative properties and Hderivative properties of all the walkers.
std::vector< std::unique_ptr< HamiltonianRef > > H_KE_Node
std::vector< ParticleGradient * > dLogPsi
Fixed Gradients , , components.
std::vector< Matrix< Return_t > * > DerivRecords
Temp derivative properties and Hderivative properties of all the walkers.
const IndexType NumThreads
number of threads
Definition: CloneManager.h:54
ParticleSet & W
Particle set.
static std::vector< QMCHamiltonian * > hClones
Definition: CloneManager.h:71
std::vector< Matrix< Return_rt > * > HDerivRecords
std::vector< Matrix< Return_rt > * > RecordsOnNode

◆ GradCost()

void GradCost ( std::vector< Return_rt > &  PGradient,
const std::vector< Return_rt > &  PM,
Return_rt  FiniteDiff = 0 
)
override

Definition at line 45 of file QMCCostFunction.cpp.

References qmcplusplus::abs(), Communicate::allreduce(), QMCCostFunction::correlatedSampling(), QMCCostFunctionBase::Cost(), QMCCostFunctionBase::curAvg, QMCCostFunctionBase::curAvg_w, QMCCostFunctionBase::curVar_w, QMCCostFunction::DerivRecords, qmcplusplus::Units::charge::e, QMCCostFunctionBase::ENERGY_NEW, QMCCostFunctionBase::EtargetEff, QMCCostFunction::HDerivRecords, QMCCostFunctionBase::isEffectiveWeightValid(), MPIObjectBase::myComm, QMCCostFunctionBase::NumOptimizables, QMCCostFunctionBase::NumSamples, CloneManager::NumThreads, QMCCostFunctionBase::OptVariables, qmcplusplus::Units::distance::pm, qmcplusplus::pow(), QMCCostFunctionBase::PowerE, QMCCostFunction::RecordsOnNode, QMCCostFunction::resetPsi(), QMCCostFunctionBase::REWEIGHT, QMCCostFunctionBase::SUM_E_WGT, QMCCostFunctionBase::SUM_ESQ_WGT, QMCCostFunctionBase::SUM_WGT, QMCCostFunctionBase::SumValue, QMCCostFunctionBase::w_abs, QMCCostFunctionBase::w_en, QMCCostFunctionBase::w_var, QMCCostFunctionBase::w_w, and CloneManager::wClones.

48 {
49  if (FiniteDiff > 0)
50  {
51  QMCTraits::RealType dh = 1.0 / (2.0 * FiniteDiff);
52  for (int i = 0; i < NumOptimizables; i++)
53  {
54  for (int j = 0; j < NumOptimizables; j++)
55  OptVariables[j] = PM[j];
56  OptVariables[i] = PM[i] + FiniteDiff;
57  QMCTraits::RealType CostPlus = this->Cost();
58  OptVariables[i] = PM[i] - FiniteDiff;
59  QMCTraits::RealType CostMinus = this->Cost();
60  PGradient[i] = (CostPlus - CostMinus) * dh;
61  }
62  }
63  else
64  {
65  for (int j = 0; j < NumOptimizables; j++)
66  OptVariables[j] = PM[j];
67  resetPsi();
68  //evaluate new local energies and derivatives
69  EffectiveWeight effective_weight = correlatedSampling(true);
70  //Estimators::accumulate has been called by correlatedSampling
72  // Return_t curAvg2_w = curAvg_w*curAvg_w;
74  std::vector<Return_rt> EDtotals(NumOptimizables, 0.0);
75  std::vector<Return_rt> EDtotals_w(NumOptimizables, 0.0);
76  std::vector<Return_rt> E2Dtotals_w(NumOptimizables, 0.0);
77  std::vector<Return_rt> URV(NumOptimizables, 0.0);
78  std::vector<Return_rt> HD_avg(NumOptimizables, 0.0);
79  Return_rt wgtinv = 1.0 / SumValue[SUM_WGT];
80  Return_rt delE_bar = 0;
81  for (int ip = 0; ip < NumThreads; ip++)
82  {
83  int nw = wClones[ip]->numSamples();
84  for (int iw = 0; iw < nw; iw++)
85  {
86  const Return_rt* restrict saved = (*RecordsOnNode[ip])[iw];
87  Return_rt weight = saved[REWEIGHT] * wgtinv;
88  Return_rt eloc_new = saved[ENERGY_NEW];
89  delE_bar += weight * std::pow(std::abs(eloc_new - EtargetEff), PowerE);
90  const Return_rt* HDsaved = (*HDerivRecords[ip])[iw];
91  for (int pm = 0; pm < NumOptimizables; pm++)
92  HD_avg[pm] += HDsaved[pm];
93  }
94  }
95  myComm->allreduce(HD_avg);
96  myComm->allreduce(delE_bar);
97  for (int pm = 0; pm < NumOptimizables; pm++)
98  HD_avg[pm] *= 1.0 / static_cast<Return_rt>(NumSamples);
99  for (int ip = 0; ip < NumThreads; ip++)
100  {
101  int nw = wClones[ip]->numSamples();
102  for (int iw = 0; iw < nw; iw++)
103  {
104  const Return_rt* restrict saved = (*RecordsOnNode[ip])[iw];
105  Return_rt weight = saved[REWEIGHT] * wgtinv;
106  Return_rt eloc_new = saved[ENERGY_NEW];
107  Return_rt delta_l = (eloc_new - curAvg_w);
108  bool ltz(true);
109  if (eloc_new - EtargetEff < 0)
110  ltz = false;
111  Return_rt delE = std::pow(std::abs(eloc_new - EtargetEff), PowerE);
112  Return_rt ddelE = PowerE * std::pow(std::abs(eloc_new - EtargetEff), PowerE - 1);
113  const Return_t* Dsaved = (*DerivRecords[ip])[iw];
114  const Return_rt* HDsaved = (*HDerivRecords[ip])[iw];
115  for (int pm = 0; pm < NumOptimizables; pm++)
116  {
117  EDtotals_w[pm] += weight * (HDsaved[pm] + 2.0 * std::real(Dsaved[pm]) * delta_l);
118  URV[pm] += 2.0 * (eloc_new * HDsaved[pm] - curAvg * HD_avg[pm]);
119  if (ltz)
120  EDtotals[pm] += weight * (2.0 * std::real(Dsaved[pm]) * (delE - delE_bar) + ddelE * HDsaved[pm]);
121  else
122  EDtotals[pm] += weight * (2.0 * std::real(Dsaved[pm]) * (delE - delE_bar) - ddelE * HDsaved[pm]);
123  }
124  }
125  }
126  myComm->allreduce(EDtotals);
127  myComm->allreduce(EDtotals_w);
128  myComm->allreduce(URV);
129  Return_rt smpinv = 1.0 / static_cast<Return_rt>(NumSamples);
130  for (int ip = 0; ip < NumThreads; ip++)
131  {
132  int nw = wClones[ip]->numSamples();
133  for (int iw = 0; iw < nw; iw++)
134  {
135  const Return_rt* restrict saved = (*RecordsOnNode[ip])[iw];
136  Return_rt weight = saved[REWEIGHT] * wgtinv;
137  Return_rt eloc_new = saved[ENERGY_NEW];
138  Return_rt delta_l = (eloc_new - curAvg_w);
139  Return_rt sigma_l = delta_l * delta_l;
140  const Return_t* Dsaved = (*DerivRecords[ip])[iw];
141  const Return_rt* HDsaved = (*HDerivRecords[ip])[iw];
142  for (int pm = 0; pm < NumOptimizables; pm++)
143  {
144  E2Dtotals_w[pm] +=
145  weight * 2.0 * (std::real(Dsaved[pm]) * (sigma_l - curVar_w) + delta_l * (HDsaved[pm] - EDtotals_w[pm]));
146  }
147  }
148  }
149  myComm->allreduce(E2Dtotals_w);
150  for (int pm = 0; pm < NumOptimizables; pm++)
151  URV[pm] *= smpinv;
152  for (int j = 0; j < NumOptimizables; j++)
153  {
154  PGradient[j] = 0.0;
155  if (std::abs(w_var) > 1.0e-10)
156  PGradient[j] += w_var * E2Dtotals_w[j];
157  if (std::abs(w_en) > 1.0e-10)
158  PGradient[j] += w_en * EDtotals_w[j];
159  if (std::abs(w_w) > 1.0e-10)
160  PGradient[j] += w_w * URV[j];
161  if (std::abs(w_abs) > 1.0e-10)
162  PGradient[j] += w_abs * EDtotals[j];
163  }
164 
165  IsValid = isEffectiveWeightValid(effective_weight);
166  }
167 }
Return_rt Cost(bool needGrad=true) override
return the cost value for CGMinimization
QMCTraits::RealType real
int NumSamples
global number of samples to use in correlated sampling
QTBase::RealType RealType
Definition: Configuration.h:58
MakeReturn< UnaryNode< FnFabs, typename CreateLeaf< Vector< T1, C1 > >::Leaf_t > >::Expression_t abs(const Vector< T1, C1 > &l)
static std::vector< MCWalkerConfiguration * > wClones
Definition: CloneManager.h:61
int NumOptimizables
total number of optimizable variables
EffectiveWeight correlatedSampling(bool needGrad=true) override
run correlated sampling return effective walkers ( w_i)^2/(Nw * w^2_i)
QMCTraits::QTFull::RealType EffectiveWeight
Return_rt curAvg_w
current weighted average (correlated sampling)
opt_variables_type OptVariables
list of optimizables
void allreduce(T &)
MakeReturn< BinaryNode< FnPow, typename CreateLeaf< Vector< T1, C1 > >::Leaf_t, typename CreateLeaf< Vector< T2, C2 > >::Leaf_t > >::Expression_t pow(const Vector< T1, C1 > &l, const Vector< T2, C2 > &r)
Communicate * myComm
pointer to Communicate
Definition: MPIObjectBase.h:62
std::vector< Matrix< Return_t > * > DerivRecords
Temp derivative properties and Hderivative properties of all the walkers.
Return_rt curAvg
current Average
const IndexType NumThreads
number of threads
Definition: CloneManager.h:54
void resetPsi(bool final_reset=false) override
reset the wavefunction
Return_rt w_en
weights for energy and variance in the cost function
bool isEffectiveWeightValid(EffectiveWeight effective_weight) const
check the validity of the effective weight calculated by correlatedSampling
std::vector< Return_rt > SumValue
Sum of energies and weights for averages.
std::vector< Matrix< Return_rt > * > HDerivRecords
int PowerE
|E-E_T|^PowerE is used for the cost function
Return_rt curVar_w
current weighted variance (correlated sampling)
std::vector< Matrix< Return_rt > * > RecordsOnNode
BareKineticEnergy::Return_t Return_t
Return_rt EtargetEff
real target energy with the Correlation Factor

◆ resetPsi()

void resetPsi ( bool  final_reset = false)
overridevirtual

reset the wavefunction

Implements QMCCostFunctionBase.

Definition at line 498 of file QMCCostFunction.cpp.

References QMCCostFunctionBase::equalVarMap, QMCCostFunctionBase::OptVariables, QMCCostFunctionBase::OptVariablesForPsi, QMCCostFunctionBase::Psi, CloneManager::psiClones, QMCCostFunctionBase::resetOptimizableObjects(), and VariableSet::size().

Referenced by QMCCostFunction::GradCost().

499 {
501  for (int i = 0; i < equalVarMap.size(); ++i)
503  else
504  for (int i = 0; i < OptVariables.size(); ++i)
506  //cout << "######### QMCCostFunction::resetPsi " << std::endl;
507  //OptVariablesForPsi.print(std::cout);
508  //cout << "-------------------------------------- " << std::endl;
509 
511  for (int i = 0; i < psiClones.size(); ++i)
513 }
static std::vector< TrialWaveFunction * > psiClones
Definition: CloneManager.h:65
std::vector< TinyVector< int, 2 > > equalVarMap
index mapping for <equal> constraints
opt_variables_type OptVariables
list of optimizables
opt_variables_type OptVariablesForPsi
full list of optimizables
size_type size() const
return the size
Definition: VariableSet.h:88
void resetOptimizableObjects(TrialWaveFunction &psi, const opt_variables_type &opt_variables) const
TrialWaveFunction & Psi
Trial function.

Member Data Documentation

◆ CSWeight

Return_rt CSWeight
protected

◆ DerivRecords

std::vector<Matrix<Return_t>*> DerivRecords
protected

◆ fill_timer_

NewTimer& fill_timer_
protected

Definition at line 70 of file QMCCostFunction.h.

Referenced by QMCCostFunction::fillOverlapHamiltonianMatrices().

◆ H_KE_Node

std::vector<std::unique_ptr<HamiltonianRef> > H_KE_Node
protected

◆ HDerivRecords

◆ RecordsOnNode

◆ qmcplusplus::QMCCostFunctionBase

class qmcplusplus::QMCCostFunctionBase

Implements wave-function optimization.

Optimization by correlated sampling method with configurations generated from VMC.

Definition at line 46 of file QMCCostFunctionBase.h.

+ Inheritance diagram for QMCCostFunctionBase:
+ Collaboration diagram for QMCCostFunctionBase:

Public Types

enum  FieldIndex_OPT {
  LOGPSI_FIXED = 0, LOGPSI_FREE = 1, ENERGY_TOT = 2, ENERGY_FIXED = 3,
  ENERGY_NEW = 4, REWEIGHT = 5
}
 
enum  SumIndex_OPT {
  SUM_E_BARE = 0, SUM_ESQ_BARE, SUM_ABSE_BARE, SUM_E_WGT,
  SUM_ESQ_WGT, SUM_ABSE_WGT, SUM_WGT, SUM_WGTSQ,
  SUM_INDEX_SIZE
}
 
using EffectiveWeight = QMCTraits::QTFull::RealType
 
using FullPrecRealType = QMCTraits::FullPrecRealType
 
- Public Types inherited from MPIObjectBase
using mpi_comm_type = Communicate::mpi_comm_type
 

Public Member Functions

 QMCCostFunctionBase (ParticleSet &w, TrialWaveFunction &psi, QMCHamiltonian &h, Communicate *comm)
 Constructor. More...
 
 ~QMCCostFunctionBase () override
 Destructor. More...
 
bool put (xmlNodePtr cur)
 process xml node More...
 
void resetCostFunction (std::vector< xmlNodePtr > &cset)
 
Return_rt & Params (int i) override
 assign optimization parameter i More...
 
Return_t Params (int i) const override
 return optimization parameter i More...
 
int getType (int i) const
 
Return_rt Cost (bool needGrad=true) override
 return the cost value for CGMinimization More...
 
Return_rt computedCost ()
 return the cost value for CGMinimization More...
 
void printEstimates ()
 
void GradCost (std::vector< Return_rt > &PGradient, const std::vector< Return_rt > &PM, Return_rt FiniteDiff=0) override
 return the gradient of cost value for CGMinimization More...
 
int getNumParams () const override
 return the number of optimizable parameters More...
 
int getNumSamples () const
 return the global number of samples More...
 
void setNumSamples (int newNumSamples)
 
virtual void resetPsi (bool final_reset=false)=0
 reset the wavefunction More...
 
void getParameterTypes (std::vector< int > &types) const
 
void Report () override
 dump the current parameters and other report More...
 
void reportParameters ()
 report parameters at the end More...
 
void reportParametersH5 ()
 report parameters in HDF5 at the end More...
 
int getReportCounter () const
 return the counter which keeps track of optimization steps More...
 
void setWaveFunctionNode (xmlNodePtr cur)
 
void setTargetEnergy (Return_rt et)
 
void setRootName (const std::string &aroot)
 
void setStream (std::ostream *os)
 
void addCoefficients (xmlXPathContextPtr acontext, const char *cname)
 add coefficient or coefficients More...
 
void printCJParams (xmlNodePtr cur, std::string &rname)
 
void addCJParams (xmlXPathContextPtr acontext, const char *cname)
 
virtual Return_rt fillOverlapHamiltonianMatrices (Matrix< Return_rt > &Left, Matrix< Return_rt > &Right)=0
 
virtual void getConfigurations (const std::string &aroot)=0
 
virtual void checkConfigurations (EngineHandle &handle)=0
 
void setRng (RefVector< RandomBase< FullPrecRealType >> r)
 
bool getneedGrads () const
 
void setneedGrads (bool tf)
 
void setDMC ()
 
std::string getParamName (int i) const override
 
const opt_variables_typegetOptVariables () const
 
Return_rt getVariance () const
 return variance after checkConfigurations More...
 
- Public Member Functions inherited from MPIObjectBase
 MPIObjectBase (Communicate *c)
 constructor with communicator More...
 
int rank () const
 return the rank of the communicator More...
 
int getGroupID () const
 return the group id of the communicator More...
 
CommunicategetCommunicator () const
 return myComm More...
 
CommunicategetCommRef () const
 return a TEMPORARY reference to Communicate More...
 
mpi_comm_type getMPI () const
 return MPI communicator if one wants to use MPI directly More...
 
bool is_manager () const
 return true if the rank == 0 More...
 
const std::string & getName () const
 return the name More...
 
void setName (const std::string &aname)
 

Public Attributes

bool reportH5
 Save opt parameters to HDF5. More...
 
bool CI_Opt
 
std::string newh5
 Path and name of the HDF5 prefix where CI coeffs are saved. More...
 

Protected Types

using ParticleGradient = ParticleSet::ParticleGradient
 Saved derivative properties and Hderivative properties of all the walkers. More...
 
using ParticleLaplacian = ParticleSet::ParticleLaplacian
 

Protected Member Functions

bool checkParameters ()
 Apply constraints on the optimizables. More...
 
void updateXmlNodes ()
 
virtual EffectiveWeight correlatedSampling (bool needGrad=true)=0
 run correlated sampling return effective walkers ( w_i)^2/(Nw * w^2_i) More...
 
bool isEffectiveWeightValid (EffectiveWeight effective_weight) const
 check the validity of the effective weight calculated by correlatedSampling More...
 
UniqueOptObjRefs extractOptimizableObjects (TrialWaveFunction &psi) const
 survey all the optimizable objects More...
 
void resetOptimizableObjects (TrialWaveFunction &psi, const opt_variables_type &opt_variables) const
 

Protected Attributes

ParticleSetW
 Particle set. More...
 
TrialWaveFunctionPsi
 Trial function. More...
 
QMCHamiltonianH
 Hamiltonian. More...
 
bool Write2OneXml
 if true, do not write the *.opt.#.xml More...
 
int PowerE
 |E-E_T|^PowerE is used for the cost function More...
 
int NumCostCalls
 number of times cost function evaluated More...
 
int NumSamples
 global number of samples to use in correlated sampling More...
 
int NumOptimizables
 total number of optimizable variables More...
 
int ReportCounter
 counter for output More...
 
Return_rt w_en
 weights for energy and variance in the cost function More...
 
Return_rt w_var
 
Return_rt w_abs
 
Return_rt w_w
 
Return_rt CostValue
 value of the cost function More...
 
Return_rt Etarget
 target energy More...
 
Return_rt EtargetEff
 real target energy with the Correlation Factor More...
 
Return_rt MinNumWalkers
 fraction of the number of walkers below which the costfunction becomes invalid More...
 
Return_rt MaxWeight
 maximum weight beyond which the weight is set to 1 More...
 
Return_rt curAvg
 current Average More...
 
Return_rt curVar
 current Variance More...
 
Return_rt curAvg_w
 current weighted average (correlated sampling) More...
 
Return_rt curVar_w
 current weighted variance (correlated sampling) More...
 
Return_rt curVar_abs
 current variance of SUM_ABSE_WGT/SUM_WGT More...
 
Return_rt w_beta
 
Return_rt vmc_or_dmc
 
bool needGrads
 
std::string targetExcitedStr
 whether we are targeting an excited state More...
 
bool targetExcited
 whether we are targeting an excited state More...
 
double omega_shift
 the shift to use when targeting an excited state More...
 
opt_variables_type OptVariables
 list of optimizables More...
 
opt_variables_type OptVariablesForPsi
 full list of optimizables More...
 
opt_variables_type InitVariables
 
std::vector< TinyVector< int, 2 > > equalVarMap
 index mapping for <equal> constraints More...
 
std::vector< TinyVector< int, 2 > > negateVarMap
 index mapping for <negate> constraints More...
 
std::ostream * msg_stream
 stream to which progress is sent More...
 
xmlNodePtr m_wfPtr
 xml node to be dumped More...
 
xmlDocPtr m_doc_out
 document node to be dumped More...
 
std::map< std::string, xmlNodePtr > paramNodes
 parameters to be updated` More...
 
std::map< std::string, xmlNodePtr > coeffNodes
 coefficients to be updated More...
 
std::map< std::string, std::pair< xmlNodePtr, std::string > > attribNodes
 attributes to be updated More...
 
std::string RootName
 string for the file root More...
 
UPtrVector< RandomBase< FullPrecRealType > > RngSaved
 Random number generators. More...
 
std::vector< RandomBase< FullPrecRealType > * > MoverRng
 
std::vector< std::string > variational_subset_names
 optimized parameter names More...
 
std::vector< Return_rt > SumValue
 Sum of energies and weights for averages. More...
 
Matrix< Return_rt > Records
 Saved properties of all the walkers. More...
 
std::vector< ParticleGradient * > dLogPsi
 Fixed Gradients , $\nabla\ln\Psi$, components. More...
 
std::vector< ParticleLaplacian * > d2LogPsi
 Fixed Laplacian , $\nabla^2\ln\Psi$, components. More...
 
std::unique_ptr< std::ostream > debug_stream
 stream for debug More...
 
bool do_override_output
 Flag on whether the variational parameter override is output to the new wavefunction. More...
 
- Protected Attributes inherited from MPIObjectBase
CommunicatemyComm
 pointer to Communicate More...
 
std::string ClassName
 class Name More...
 
std::string myName
 name of the object More...
 

Member Typedef Documentation

◆ EffectiveWeight

◆ FullPrecRealType

◆ ParticleGradient

Saved derivative properties and Hderivative properties of all the walkers.

Definition at line 296 of file QMCCostFunctionBase.h.

◆ ParticleLaplacian

Definition at line 297 of file QMCCostFunctionBase.h.

Member Enumeration Documentation

◆ FieldIndex_OPT

◆ SumIndex_OPT

Constructor & Destructor Documentation

◆ QMCCostFunctionBase()

Constructor.

Definition at line 33 of file QMCCostFunctionBase.cpp.

References OHMMS::Controller, QMCCostFunctionBase::debug_stream, QMCCostFunctionBase::MinNumWalkers, Communicate::rank(), QMCCostFunctionBase::SUM_INDEX_SIZE, and QMCCostFunctionBase::SumValue.

35  reportH5(false),
36  CI_Opt(false),
37  W(w),
38  Psi(psi),
39  H(h),
40  Write2OneXml(true),
41  PowerE(2),
42  NumCostCalls(0),
43  NumSamples(0),
44  w_en(0.9),
45  w_var(0.1),
46  w_abs(0.0),
47  w_w(0.0),
48  MaxWeight(1e6),
49  w_beta(0.0),
50  vmc_or_dmc(2.0),
51  needGrads(true),
52  targetExcitedStr("no"),
53  targetExcited(false),
54  omega_shift(0.0),
55  msg_stream(nullptr),
56  m_wfPtr(nullptr),
57  m_doc_out(nullptr),
58  do_override_output(true)
59 {
60  //default: don't check fo MinNumWalkers
61  MinNumWalkers = 0.3;
62  SumValue.resize(SUM_INDEX_SIZE, 0.0);
63  IsValid = true;
64 #if defined(QMCCOSTFUNCTION_DEBUG)
65  std::array<char, 16> fname;
66  int length = std::snprintf(fname.data(), fname.size(), "optdebug.p%d", OHMMS::Controller->rank());
67  if (length < 0)
68  throw std::runtime_error("Error generating filename");
69  debug_stream = std::make_unique<std::ofstream>(fname.data());
70  debug_stream->setf(std::ios::scientific, std::ios::floatfield);
71  debug_stream->precision(8);
72 #endif
73 }
bool targetExcited
whether we are targeting an excited state
bool Write2OneXml
if true, do not write the *.opt.#.xml
bool reportH5
Save opt parameters to HDF5.
int NumSamples
global number of samples to use in correlated sampling
int rank() const
return the rank
Definition: Communicate.h:116
std::ostream * msg_stream
stream to which progress is sent
Return_rt MinNumWalkers
fraction of the number of walkers below which the costfunction becomes invalid
xmlNodePtr m_wfPtr
xml node to be dumped
Communicate * Controller
Global Communicator for a process.
Definition: Communicate.cpp:35
bool do_override_output
Flag on whether the variational parameter override is output to the new wavefunction.
int NumCostCalls
number of times cost function evaluated
QMCHamiltonian & H
Hamiltonian.
Return_rt w_en
weights for energy and variance in the cost function
ParticleSet & W
Particle set.
std::unique_ptr< std::ostream > debug_stream
stream for debug
xmlDocPtr m_doc_out
document node to be dumped
std::string targetExcitedStr
whether we are targeting an excited state
std::vector< Return_rt > SumValue
Sum of energies and weights for averages.
TrialWaveFunction & Psi
Trial function.
Return_rt MaxWeight
maximum weight beyond which the weight is set to 1
MPIObjectBase(Communicate *c)
constructor with communicator
int PowerE
|E-E_T|^PowerE is used for the cost function
double omega_shift
the shift to use when targeting an excited state

◆ ~QMCCostFunctionBase()

~QMCCostFunctionBase ( )
override

Destructor.

Clean up the vector.

Definition at line 76 of file QMCCostFunctionBase.cpp.

References QMCCostFunctionBase::d2LogPsi, QMCCostFunctionBase::debug_stream, qmcplusplus::delete_iter(), QMCCostFunctionBase::dLogPsi, and QMCCostFunctionBase::m_doc_out.

77 {
78  delete_iter(dLogPsi.begin(), dLogPsi.end());
79  delete_iter(d2LogPsi.begin(), d2LogPsi.end());
80  if (m_doc_out != nullptr)
81  xmlFreeDoc(m_doc_out);
82  debug_stream.reset();
83 }
std::vector< ParticleLaplacian * > d2LogPsi
Fixed Laplacian , , components.
void delete_iter(IT first, IT last)
delete the pointers in [first,last)
std::vector< ParticleGradient * > dLogPsi
Fixed Gradients , , components.
std::unique_ptr< std::ostream > debug_stream
stream for debug
xmlDocPtr m_doc_out
document node to be dumped

Member Function Documentation

◆ addCJParams()

void addCJParams ( xmlXPathContextPtr  acontext,
const char *  cname 
)

Definition at line 770 of file QMCCostFunctionBase.cpp.

References OhmmsAttributeSet::add(), VariableSet::begin(), QMCCostFunctionBase::coeffNodes, VariableSet::end(), VariableSet::find(), QMCCostFunctionBase::InitVariables, QMCCostFunctionBase::OptVariables, OhmmsAttributeSet::put(), and qmcplusplus::sqrt().

Referenced by QMCCostFunctionBase::updateXmlNodes().

771 {
772  xmlXPathObjectPtr result = xmlXPathEvalExpression((const xmlChar*)cname, acontext);
773  for (int iparam = 0; iparam < result->nodesetval->nodeNr; iparam++)
774  {
775  // check that we're in a counting jastrow tag space
776  xmlNodePtr cur = result->nodesetval->nodeTab[iparam];
777  OhmmsAttributeSet cAttrib;
778  std::string aname("none");
779  std::string atype("none");
780  cAttrib.add(aname, "name");
781  cAttrib.add(atype, "type");
782  cAttrib.put(cur);
783  if (atype == "Counting")
784  {
785  // iterate through children
786  xmlNodePtr cur2 = cur->xmlChildrenNode;
787  int Fnum = 0;
788  bool Ftag_found = false;
789  // find the <var name="F" /> tag, save the location
790  while (cur2 != NULL)
791  {
792  std::string tname2((const char*)cur2->name);
793  OhmmsAttributeSet cAttrib2;
794  std::string aname2("none");
795  std::string aopt2("yes");
796  std::string ref_id("g0");
797  cAttrib2.add(aname2, "name");
798  cAttrib2.add(aopt2, "opt");
799  cAttrib2.add(ref_id, "reference_id");
800  cAttrib2.put(cur2);
801  // find the <var name="F" /> tags and register the tag location first
802  if (tname2 == "var" && aname2 == "F" && (aopt2 == "yes" || aopt2 == "true"))
803  {
804  coeffNodes["cj_F"] = cur2;
805  Ftag_found = true;
806  }
807  cur2 = cur2->next;
808  }
809 
810  // count the total number of registered F matrix variables
812  for (; oit != oit_end; ++oit)
813  {
814  const std::string& oname((*oit).first);
815  if (oname.find("F_") == 0)
816  ++Fnum;
817  }
818  ++Fnum;
819 
820  // F variable tag isn't found; build the tag.
821  if (!Ftag_found)
822  {
823  xmlNodeAddContent(cur, (const xmlChar*)"\n ");
824  xmlNodePtr F_tag = xmlNewChild(cur, NULL, (const xmlChar*)"var", NULL);
825  xmlSetProp(F_tag, (const xmlChar*)"name", (const xmlChar*)"F");
826  xmlSetProp(F_tag, (const xmlChar*)"opt", (const xmlChar*)"true");
827  xmlNodeSetContent(F_tag, (const xmlChar*)" ");
828  coeffNodes["cj_F"] = F_tag;
829  xmlNodeAddContent(cur, (const xmlChar*)"\n ");
830  }
831 
832  cur2 = cur->xmlChildrenNode;
833  while (cur2 != NULL)
834  {
835  std::string tname2((const char*)cur2->name);
836  OhmmsAttributeSet cAttrib2;
837  std::string aname2("none");
838  std::string atype2("normalized_gaussian");
839  std::string aopt2("yes");
840  std::string ref_id("g0");
841  cAttrib2.add(aname2, "name");
842  cAttrib2.add(atype2, "type");
843  cAttrib2.add(aopt2, "opt");
844  cAttrib2.add(ref_id, "reference_id");
845  cAttrib2.put(cur2);
846  // find <region /> tag
847  if (tname2 == "region" && (aopt2 == "true" || aopt2 == "yes") && Fnum != 0)
848  {
849  // if type is voronoi, reconstruct the tag structure
850  if (atype2 == "voronoi")
851  {
852  // set property to normalized_gaussian, add reference, remove source
853  xmlUnsetProp(cur, (const xmlChar*)"source");
854  xmlSetProp(cur2, (const xmlChar*)"type", (const xmlChar*)"normalized_gaussian");
855  xmlSetProp(cur2, (const xmlChar*)"reference_id", (const xmlChar*)ref_id.c_str());
856  // remove existing children
857  xmlNodePtr child = cur2->xmlChildrenNode;
858  while (child != NULL)
859  {
860  xmlUnlinkNode(child);
861  child = cur2->xmlChildrenNode;
862  }
863  // get Fdim
864  int Fdim = (std::sqrt(1 + 8 * Fnum) - 1) / 2;
865  for (int i = 0; i < Fdim; ++i)
866  {
867  std::ostringstream os;
868  os << "g" << i;
869  std::string gid = os.str();
870  std::string opt = (gid != ref_id) ? "true" : "false";
871 
872  // create function tag, set id
873  xmlNodeAddContent(cur2, (const xmlChar*)"\n ");
874  xmlNodePtr function_tag = xmlNewChild(cur2, NULL, (const xmlChar*)"function", NULL);
875  xmlNewProp(function_tag, (const xmlChar*)"id", (const xmlChar*)gid.c_str());
876  xmlNodeAddContent(function_tag, (const xmlChar*)"\n ");
877  // create A tag
878  xmlNodePtr A_tag = xmlNewChild(function_tag, NULL, (const xmlChar*)"var", NULL);
879  xmlNodeAddContent(function_tag, (const xmlChar*)"\n ");
880  xmlNewProp(A_tag, (const xmlChar*)"name", (const xmlChar*)"A");
881  xmlNewProp(A_tag, (const xmlChar*)"opt", (const xmlChar*)opt.c_str());
882  os.str("");
883  if (gid == ref_id)
884  {
885  os << std::setprecision(6) << std::scientific;
886  os << InitVariables.find(gid + "_A_xx")->second << " " << InitVariables.find(gid + "_A_xy")->second
887  << " " << InitVariables.find(gid + "_A_xz")->second << " "
888  << InitVariables.find(gid + "_A_yy")->second << " " << InitVariables.find(gid + "_A_yz")->second
889  << " " << InitVariables.find(gid + "_A_zz")->second;
890  }
891  else
892  os << " ";
893  xmlNodeSetContent(A_tag, (const xmlChar*)(os.str().c_str()));
894 
895  // create B tag
896  xmlNodePtr B_tag = xmlNewChild(function_tag, NULL, (const xmlChar*)"var", NULL);
897  xmlNodeAddContent(function_tag, (const xmlChar*)"\n ");
898  xmlNewProp(B_tag, (const xmlChar*)"name", (const xmlChar*)"B");
899  xmlNewProp(B_tag, (const xmlChar*)"opt", (const xmlChar*)opt.c_str());
900  os.str("");
901  if (gid == ref_id)
902  {
903  os << std::setprecision(6) << std::scientific;
904  os << InitVariables.find(gid + "_B_x")->second << " " << InitVariables.find(gid + "_B_y")->second << " "
905  << InitVariables.find(gid + "_B_z")->second;
906  }
907  else
908  os << " ";
909  xmlNodeSetContent(B_tag, (const xmlChar*)(os.str().c_str()));
910 
911  // create C tag
912  xmlNodePtr C_tag = xmlNewChild(function_tag, NULL, (const xmlChar*)"var", NULL);
913  xmlNodeAddContent(function_tag, (const xmlChar*)"\n ");
914  xmlNewProp(C_tag, (const xmlChar*)"name", (const xmlChar*)"C");
915  xmlNewProp(C_tag, (const xmlChar*)"opt", (const xmlChar*)opt.c_str());
916  os.str("");
917  if (gid == ref_id)
918  {
919  os << std::setprecision(6) << std::scientific;
920  os << InitVariables.find(gid + "_C")->second;
921  }
922  else
923  os << " ";
924  xmlNodeSetContent(C_tag, (const xmlChar*)(os.str().c_str()));
925  }
926  xmlNodeAddContent(cur2, (const xmlChar*)"\n ");
927  }
928 
929  // register the optimizable variables for each function
930  // find <function /> tags
931  xmlNodePtr cur3 = cur2->xmlChildrenNode;
932  while (cur3 != NULL)
933  {
934  std::string tname3((const char*)cur3->name);
935  OhmmsAttributeSet cAttrib3;
936  std::string fid("none");
937  cAttrib3.add(fid, "id");
938  cAttrib3.put(cur3);
939  // for each function tag, register coeffNodes[gid_A/B/C] as each variable location
940  if (tname3 == "function")
941  {
942  // find <var name="A/B/C" /> tags
943  xmlNodePtr cur4 = cur3->xmlChildrenNode;
944  while (cur4 != NULL)
945  {
946  std::string tname4((const char*)cur4->name);
947  OhmmsAttributeSet cAttrib4;
948  std::string aname4("none");
949  std::string aopt4("false");
950  cAttrib4.add(aname4, "name");
951  cAttrib4.add(aopt4, "opt");
952  cAttrib4.put(cur4);
953  if (tname4 == "var" && (aopt4 == "true" || aopt4 == "yes"))
954  {
955  std::string varname = "cj_" + fid + "_" + aname4;
956  bool notlisted = true;
958  while (notlisted && oit != oit_end)
959  {
960  const std::string& oname((*oit).first);
961  notlisted = (oname.find(varname.substr(3)) >= oname.size());
962  ++oit;
963  }
964  if (!notlisted)
965  {
966  coeffNodes[varname] = cur4;
967  }
968  }
969  cur4 = cur4->next;
970  }
971  }
972  cur3 = cur3->next;
973  }
974  }
975  cur2 = cur2->next;
976  }
977  }
978  }
979  xmlXPathFreeObject(result);
980 }
iterator find(const std::string &vname)
return the iterator of a named parameter
Definition: VariableSet.h:98
const_iterator end() const
return the last const_iterator
Definition: VariableSet.h:82
std::vector< pair_type >::iterator iterator
Definition: VariableSet.h:55
bool put(xmlNodePtr cur)
assign attributes to the set
Definition: AttributeSet.h:55
opt_variables_type OptVariables
list of optimizables
class to handle a set of attributes of an xmlNode
Definition: AttributeSet.h:24
const_iterator begin() const
return the first const_iterator
Definition: VariableSet.h:80
MakeReturn< UnaryNode< FnSqrt, typename CreateLeaf< Vector< T1, C1 > >::Leaf_t > >::Expression_t sqrt(const Vector< T1, C1 > &l)
void add(PDT &aparam, const std::string &aname, std::vector< PDT > candidate_values={}, TagStatus status=TagStatus::OPTIONAL)
add a new attribute
Definition: AttributeSet.h:42
std::map< std::string, xmlNodePtr > coeffNodes
coefficients to be updated

◆ addCoefficients()

void addCoefficients ( xmlXPathContextPtr  acontext,
const char *  cname 
)

add coefficient or coefficients

Parameters
acontextcontext from which xpath cname is searched
cnamexpath

Definition at line 728 of file QMCCostFunctionBase.cpp.

References OhmmsAttributeSet::add(), VariableSet::begin(), QMCCostFunctionBase::coeffNodes, VariableSet::end(), QMCCostFunctionBase::OptVariablesForPsi, and OhmmsAttributeSet::put().

Referenced by QMCCostFunctionBase::updateXmlNodes().

729 {
730  xmlXPathObjectPtr result = xmlXPathEvalExpression((const xmlChar*)cname, acontext);
731  for (int iparam = 0; iparam < result->nodesetval->nodeNr; iparam++)
732  {
733  xmlNodePtr cur = result->nodesetval->nodeTab[iparam];
734  OhmmsAttributeSet cAttrib;
735  std::string aname("0");
736  std::string optimize("yes");
737  std::string datatype("none");
738  cAttrib.add(aname, "id");
739  cAttrib.add(aname, "name");
740  cAttrib.add(datatype, "type");
741  cAttrib.add(optimize, "optimize");
742  cAttrib.put(cur);
743  if (aname[0] == '0')
744  continue;
745  if (datatype == "Array")
746  {
747  if (optimize == "yes")
748  coeffNodes[aname] = cur;
749  }
750  else
751  {
752  //check if any optimizables contains the id of coefficients
753  bool notlisted = true;
755  while (notlisted && oit != oit_end)
756  {
757  const std::string& oname((*oit).first);
758  notlisted = (oname.find(aname) >= oname.size());
759  ++oit;
760  }
761  if (!notlisted)
762  {
763  coeffNodes[aname] = cur;
764  }
765  }
766  }
767  xmlXPathFreeObject(result);
768 }
const_iterator end() const
return the last const_iterator
Definition: VariableSet.h:82
std::vector< pair_type >::iterator iterator
Definition: VariableSet.h:55
bool put(xmlNodePtr cur)
assign attributes to the set
Definition: AttributeSet.h:55
class to handle a set of attributes of an xmlNode
Definition: AttributeSet.h:24
opt_variables_type OptVariablesForPsi
full list of optimizables
const_iterator begin() const
return the first const_iterator
Definition: VariableSet.h:80
void add(PDT &aparam, const std::string &aname, std::vector< PDT > candidate_values={}, TagStatus status=TagStatus::OPTIONAL)
add a new attribute
Definition: AttributeSet.h:42
std::map< std::string, xmlNodePtr > coeffNodes
coefficients to be updated

◆ checkConfigurations()

virtual void checkConfigurations ( EngineHandle handle)
pure virtual

◆ checkParameters()

bool checkParameters ( )
protected

Apply constraints on the optimizables.

Here is where constraints should go

Definition at line 288 of file QMCCostFunctionBase.cpp.

289 {
290  bool samesign = true;
291  //if(samesign) {
292  // paramList.pop_back();
293  // paramList.push_front(OptParams);
294  //}
295  return samesign;
296 }

◆ computedCost()

QMCCostFunctionBase::Return_rt computedCost ( )

return the cost value for CGMinimization

Definition at line 141 of file QMCCostFunctionBase.cpp.

References qmcplusplus::abs(), QMCCostFunctionBase::CostValue, QMCCostFunctionBase::curAvg, QMCCostFunctionBase::curAvg_w, QMCCostFunctionBase::curVar, QMCCostFunctionBase::curVar_abs, QMCCostFunctionBase::curVar_w, QMCCostFunctionBase::NumSamples, QMCCostFunctionBase::SUM_ABSE_WGT, QMCCostFunctionBase::SUM_E_BARE, QMCCostFunctionBase::SUM_E_WGT, QMCCostFunctionBase::SUM_ESQ_BARE, QMCCostFunctionBase::SUM_ESQ_WGT, QMCCostFunctionBase::SUM_WGT, QMCCostFunctionBase::SumValue, QMCCostFunctionBase::w_abs, QMCCostFunctionBase::w_en, QMCCostFunctionBase::w_var, and QMCCostFunctionBase::w_w.

Referenced by QMCCostFunctionBase::Cost().

142 {
143  // Assumes the Sums have been computed all ready
144  //Estimators::accumulate has been called by correlatedSampling
147  Return_rt wgtinv = 1.0 / static_cast<Return_rt>(NumSamples);
148  // app_log() << "wgtinv = " << wgtinv << std::endl;
149  curAvg = SumValue[SUM_E_BARE] * wgtinv;
150  curVar = SumValue[SUM_ESQ_BARE] * wgtinv - curAvg * curAvg;
152  // app_log() << "curVar = " << curVar
153  // << " curAvg = " << curAvg << std::endl;
154  // app_log() << "SumValue[SUM_WGT] = " << SumValue[SUM_WGT] << std::endl;
155  // app_log() << "SumValue[SUM_WGTSQ] = " << SumValue[SUM_WGTSQ] << std::endl;
156  // app_log() << "SumValue[SUM_ABSE_WGT] = " << SumValue[SUM_ABSE_WGT] << std::endl;
157  // app_log() << "SumValue[SUM_E_WGT] = " << SumValue[SUM_E_WGT] << std::endl;
158  // app_log() << "SumValue[SUM_ESQ_WGT] = " << SumValue[SUM_ESQ_WGT] << std::endl;
159  CostValue = 0.0;
160  const Return_rt small = 1.0e-10;
161  if (std::abs(w_abs) > small)
163  if (std::abs(w_var) > small)
164  CostValue += w_var * curVar_w;
165  if (std::abs(w_en) > small)
166  CostValue += w_en * curAvg_w;
167  if (std::abs(w_w) > small)
168  CostValue += w_w * curVar;
169  return CostValue;
170 }
Return_rt CostValue
value of the cost function
int NumSamples
global number of samples to use in correlated sampling
MakeReturn< UnaryNode< FnFabs, typename CreateLeaf< Vector< T1, C1 > >::Leaf_t > >::Expression_t abs(const Vector< T1, C1 > &l)
Return_rt curAvg_w
current weighted average (correlated sampling)
Return_rt curAvg
current Average
Return_rt w_en
weights for energy and variance in the cost function
std::vector< Return_rt > SumValue
Sum of energies and weights for averages.
Return_rt curVar_abs
current variance of SUM_ABSE_WGT/SUM_WGT
Return_rt curVar
current Variance
Return_rt curVar_w
current weighted variance (correlated sampling)

◆ correlatedSampling()

virtual EffectiveWeight correlatedSampling ( bool  needGrad = true)
protectedpure virtual

run correlated sampling return effective walkers ( w_i)^2/(Nw * w^2_i)

Implemented in QMCCostFunctionBatched, QMCCostFunction, and QMCCostFunctionTest.

Referenced by QMCCostFunctionBase::Cost().

◆ Cost()

QMCCostFunctionBase::Return_rt Cost ( bool  needGrad = true)
override

return the cost value for CGMinimization

Definition at line 122 of file QMCCostFunctionBase.cpp.

References QMCCostFunctionBase::computedCost(), QMCCostFunctionBase::correlatedSampling(), QMCCostFunctionBase::isEffectiveWeightValid(), QMCCostFunctionBase::NumCostCalls, and QMCCostFunctionBase::resetPsi().

Referenced by QMCCostFunction::GradCost(), and QMCCostFunctionBatched::GradCost().

123 {
124  NumCostCalls++;
125  //reset the wave function
126  resetPsi();
127  //evaluate new local energies
128  EffectiveWeight effective_weight = correlatedSampling(needGrad);
129  IsValid = isEffectiveWeightValid(effective_weight);
130  return computedCost();
131 }
Return_rt computedCost()
return the cost value for CGMinimization
QMCTraits::QTFull::RealType EffectiveWeight
int NumCostCalls
number of times cost function evaluated
bool isEffectiveWeightValid(EffectiveWeight effective_weight) const
check the validity of the effective weight calculated by correlatedSampling
virtual EffectiveWeight correlatedSampling(bool needGrad=true)=0
run correlated sampling return effective walkers ( w_i)^2/(Nw * w^2_i)
virtual void resetPsi(bool final_reset=false)=0
reset the wavefunction

◆ extractOptimizableObjects()

UniqueOptObjRefs extractOptimizableObjects ( TrialWaveFunction psi) const
protected

survey all the optimizable objects

Definition at line 1074 of file QMCCostFunctionBase.cpp.

References TrialWaveFunction::extractOptimizableObjectRefs(), and QMCCostFunctionBase::variational_subset_names.

Referenced by QMCCostFunctionBase::put(), and QMCCostFunctionBase::resetOptimizableObjects().

1075 {
1076  const auto& names(variational_subset_names);
1077  // survey all the optimizable objects
1078  const auto opt_obj_refs = psi.extractOptimizableObjectRefs();
1079  // check if input names are valid
1080  for (auto& name : names)
1081  if (std::find_if(opt_obj_refs.begin(), opt_obj_refs.end(),
1082  [&name](const OptimizableObject& obj) { return name == obj.getName(); }) == opt_obj_refs.end())
1083  {
1084  std::ostringstream msg;
1085  msg << "Variational subset entry '" << name << "' doesn't exist in the trial wavefunction which contains";
1086  for (OptimizableObject& obj : opt_obj_refs)
1087  msg << " '" << obj.getName() << "'";
1088  msg << "." << std::endl;
1089  throw UniformCommunicateError(msg.str());
1090  }
1091 
1092  for (OptimizableObject& obj : opt_obj_refs)
1093  obj.setOptimization(names.empty() || std::find_if(names.begin(), names.end(), [&obj](const std::string& name) {
1094  return name == obj.getName();
1095  }) != names.end());
1096  return opt_obj_refs;
1097 }
std::vector< std::string > variational_subset_names
optimized parameter names

◆ fillOverlapHamiltonianMatrices()

virtual Return_rt fillOverlapHamiltonianMatrices ( Matrix< Return_rt > &  Left,
Matrix< Return_rt > &  Right 
)
pure virtual

◆ getConfigurations()

virtual void getConfigurations ( const std::string &  aroot)
pure virtual

◆ getneedGrads()

bool getneedGrads ( ) const
inline

Definition at line 159 of file QMCCostFunctionBase.h.

References QMCCostFunctionBase::needGrads.

◆ getNumParams()

int getNumParams ( ) const
inlineoverride

return the number of optimizable parameters

Definition at line 103 of file QMCCostFunctionBase.h.

References QMCCostFunctionBase::OptVariables, and VariableSet::size().

Referenced by QMCCostFunction::fillOverlapHamiltonianMatrices(), QMCCostFunctionBatched::fillOverlapHamiltonianMatrices(), and GradientTest::run().

103 { return OptVariables.size(); }
opt_variables_type OptVariables
list of optimizables
size_type size() const
return the size
Definition: VariableSet.h:88

◆ getNumSamples()

int getNumSamples ( ) const
inline

return the global number of samples

Definition at line 105 of file QMCCostFunctionBase.h.

References QMCCostFunctionBase::NumSamples.

105 { return NumSamples; }
int NumSamples
global number of samples to use in correlated sampling

◆ getOptVariables()

const opt_variables_type& getOptVariables ( ) const
inline

Definition at line 166 of file QMCCostFunctionBase.h.

References QMCCostFunctionBase::OptVariables.

166 { return OptVariables; }
opt_variables_type OptVariables
list of optimizables

◆ getParameterTypes()

void getParameterTypes ( std::vector< int > &  types) const
inline

Definition at line 110 of file QMCCostFunctionBase.h.

References VariableSet::getParameterTypeList(), and QMCCostFunctionBase::OptVariablesForPsi.

Referenced by LinearMethod::getNonLinearRange().

111  {
113  }
opt_variables_type OptVariablesForPsi
full list of optimizables
void getParameterTypeList(std::vector< int > &types) const
Definition: VariableSet.h:159

◆ getParamName()

std::string getParamName ( int  i) const
inlineoverride

Definition at line 164 of file QMCCostFunctionBase.h.

References VariableSet::name(), and QMCCostFunctionBase::OptVariables.

Referenced by GradientTest::run().

164 { return OptVariables.name(i); }
opt_variables_type OptVariables
list of optimizables
const std::string & name(int i) const
return the name of i-th variable
Definition: VariableSet.h:189

◆ getReportCounter()

int getReportCounter ( ) const
inline

return the counter which keeps track of optimization steps

Definition at line 123 of file QMCCostFunctionBase.h.

References QMCCostFunctionBase::ReportCounter.

123 { return ReportCounter; }
int ReportCounter
counter for output

◆ getType()

int getType ( int  i) const
inline

Definition at line 91 of file QMCCostFunctionBase.h.

References VariableSet::getType(), and QMCCostFunctionBase::OptVariables.

91 { return OptVariables.getType(i); }
opt_variables_type OptVariables
list of optimizables
int getType(int i) const
get the i-th parameter&#39;s type
Definition: VariableSet.h:204

◆ getVariance()

◆ GradCost()

void GradCost ( std::vector< Return_rt > &  PGradient,
const std::vector< Return_rt > &  PM,
Return_rt  FiniteDiff = 0 
)
inlineoverride

return the gradient of cost value for CGMinimization

Definition at line 99 of file QMCCostFunctionBase.h.

Referenced by GradientTest::run().

101  {};

◆ isEffectiveWeightValid()

bool isEffectiveWeightValid ( EffectiveWeight  effective_weight) const
protected

check the validity of the effective weight calculated by correlatedSampling

Definition at line 1058 of file QMCCostFunctionBase.cpp.

References qmcplusplus::app_log(), QMCCostFunctionBase::MinNumWalkers, and WARNMSG.

Referenced by QMCCostFunctionBase::Cost(), QMCCostFunction::GradCost(), and QMCCostFunctionBatched::GradCost().

1059 {
1060  app_log() << "Effective weight of all the samples measured by correlated sampling is " << effective_weight
1061  << std::endl;
1062  if (effective_weight < MinNumWalkers)
1063  {
1064  WARNMSG(" Smaller than the user specified threshold \"minwalkers\" = "
1065  << MinNumWalkers << std::endl
1066  << " If this message appears frequently. You might have to be cautious. " << std::endl
1067  << " Find info about parameter \"minwalkers\" in the user manual!");
1068  return false;
1069  }
1070 
1071  return true;
1072 }
std::ostream & app_log()
Definition: OutputManager.h:65
Return_rt MinNumWalkers
fraction of the number of walkers below which the costfunction becomes invalid
#define WARNMSG(msg)
Definition: OutputManager.h:90

◆ Params() [1/2]

Return_rt& Params ( int  i)
inlineoverride

assign optimization parameter i

Definition at line 88 of file QMCCostFunctionBase.h.

References QMCCostFunctionBase::OptVariables.

Referenced by GradientTest::run().

88 { return OptVariables[i]; }
opt_variables_type OptVariables
list of optimizables

◆ Params() [2/2]

Return_t Params ( int  i) const
inlineoverride

return optimization parameter i

Definition at line 90 of file QMCCostFunctionBase.h.

References QMCCostFunctionBase::OptVariables.

90 { return OptVariables[i]; }
opt_variables_type OptVariables
list of optimizables

◆ printCJParams()

void printCJParams ( xmlNodePtr  cur,
std::string &  rname 
)

Definition at line 983 of file QMCCostFunctionBase.cpp.

References VariableSet::begin(), VariableSet::end(), QMCCostFunctionBase::OptVariables, QMCCostFunctionBase::OptVariablesForPsi, and qmcplusplus::sqrt().

Referenced by QMCCostFunctionBase::updateXmlNodes().

984 {
986  // F matrix variables
987  if (rname.find("cj_F") < rname.size())
988  {
989  // get a vector of pairs with f matrix names, values
990  std::vector<Return_rt> f_vals;
991  for (auto vit = OptVariables.begin(); vit != OptVariables.end(); ++vit)
992  {
993  if ((*vit).first.find("F_") == 0)
994  {
995  Return_rt fval = std::real(vit->second);
996  f_vals.push_back(fval);
997  }
998  }
999  // manually add final element = 0
1000  f_vals.push_back(0);
1001  // get the dimensions of the f matrix
1002  int Fdim = (std::sqrt(1 + 8 * f_vals.size()) - 1) / 2;
1003  std::ostringstream os;
1004  std::string pad_str = std::string(14, ' ');
1005  os << std::endl;
1006  os << std::setprecision(6) << std::scientific;
1007  // print out the values with the proper indentation
1008  auto fit = f_vals.begin();
1009  for (int i = 0; i < Fdim; ++i)
1010  {
1011  os << pad_str;
1012  for (int j = 0; j < Fdim; ++j)
1013  {
1014  if (j < i)
1015  os << pad_str; //print blank
1016  else // print value
1017  {
1018  os << " " << (*fit);
1019  ++fit;
1020  }
1021  }
1022  // line break
1023  if (i < Fdim - 1)
1024  os << std::endl;
1025  }
1026  // assign to tag
1027  xmlNodePtr cur2 = cur->children;
1028  xmlNodeSetContent(cur2, (const xmlChar*)(os.str().c_str()));
1029  xmlNodeAddContent(cur2, (const xmlChar*)"\n ");
1030  }
1031  // gaussian function parameters A, B, C
1032  else
1033  {
1034  std::string var_prefix = rname.substr(3);
1035  std::vector<Return_rt> vals;
1036 
1037  for (auto vit = OptVariablesForPsi.begin(); vit != OptVariablesForPsi.end(); ++vit)
1038  {
1039  if (vit->first.find(var_prefix) == 0)
1040  {
1041  Return_rt val = std::real(vit->second);
1042  vals.push_back(val);
1043  }
1044  }
1045  std::ostringstream os;
1046  os << std::setprecision(6) << std::scientific;
1047  for (int i = 0; i < vals.size(); ++i)
1048  {
1049  os << vals[i];
1050  if (i < vals.size() - 1)
1051  os << " ";
1052  }
1053  xmlNodePtr cur2 = cur->children;
1054  xmlNodeSetContent(cur2, (const xmlChar*)(os.str().c_str()));
1055  }
1056 }
QMCTraits::RealType real
const_iterator end() const
return the last const_iterator
Definition: VariableSet.h:82
std::vector< pair_type >::iterator iterator
Definition: VariableSet.h:55
opt_variables_type OptVariables
list of optimizables
opt_variables_type OptVariablesForPsi
full list of optimizables
const_iterator begin() const
return the first const_iterator
Definition: VariableSet.h:80
MakeReturn< UnaryNode< FnSqrt, typename CreateLeaf< Vector< T1, C1 > >::Leaf_t > >::Expression_t sqrt(const Vector< T1, C1 > &l)

◆ printEstimates()

void printEstimates ( )

Definition at line 133 of file QMCCostFunctionBase.cpp.

References qmcplusplus::app_log(), QMCCostFunctionBase::curAvg, QMCCostFunctionBase::curAvg_w, QMCCostFunctionBase::curVar, and QMCCostFunctionBase::curVar_w.

134 {
135  app_log() << " Current ene: " << curAvg_w << std::endl;
136  app_log() << " Current var: " << curVar_w << std::endl;
137  app_log() << " Current ene_urw: " << curAvg << std::endl;
138  app_log() << " Current var_urw: " << curVar << std::endl;
139 }
std::ostream & app_log()
Definition: OutputManager.h:65
Return_rt curAvg_w
current weighted average (correlated sampling)
Return_rt curAvg
current Average
Return_rt curVar
current Variance
Return_rt curVar_w
current weighted variance (correlated sampling)

◆ put()

bool put ( xmlNodePtr  q)

process xml node

Parses the xml input file for parameter definitions for the wavefunction optimization.

Parameters
qcurrent xmlNode
Returns
true if successful

Must provide a list of the id's of the variables to be optimized. Other available elements

  • mcwalkerset->file: name of configuration file
  • optimize->method: method of optimization, right now only congjugate gradient
  • cost->weight: either weight for the energy term, default 1.0, or weight for the variance, default 1.0
  • tolerance: for conjugate gradient, default 1e-8
  • stepsize: for conjugate gradient, default 0.01
  • epsilon: for conjugate gradient, default 1e-6

Definition at line 315 of file QMCCostFunctionBase.cpp.

References VariableSet::activate(), OhmmsAttributeSet::add(), ParameterSet::add(), APP_ABORT, qmcplusplus::app_log(), qmcplusplus::app_warning(), TrialWaveFunction::checkOutVariables(), VariableSet::clear(), DEPRECATED, VariableSet::disable(), QMCCostFunctionBase::do_override_output, QMCCostFunctionBase::equalVarMap, QMCCostFunctionBase::Etarget, QMCCostFunctionBase::EtargetEff, QMCCostFunctionBase::extractOptimizableObjects(), VariableSet::getIndex(), TrialWaveFunction::getName(), QMCCostFunctionBase::InitVariables, qmcplusplus::lowerCase(), QMCCostFunctionBase::MaxWeight, QMCCostFunctionBase::MinNumWalkers, QMCCostFunctionBase::msg_stream, MPIObjectBase::myComm, VariableSet::name(), QMCCostFunctionBase::NumOptimizables, QMCCostFunctionBase::omega_shift, QMCCostFunctionBase::OptVariables, QMCCostFunctionBase::OptVariablesForPsi, QMCCostFunctionBase::Psi, ParameterSet::put(), OhmmsAttributeSet::put(), putContent(), Communicate::rank(), QMCCostFunctionBase::resetCostFunction(), VariableSet::resetIndex(), QMCCostFunctionBase::resetPsi(), qmcplusplus::Units::time::s, astring::s, VariableSet::size(), QMCCostFunctionBase::targetExcited, QMCCostFunctionBase::targetExcitedStr, QMCCostFunctionBase::variational_subset_names, QMCCostFunctionBase::w_beta, and QMCCostFunctionBase::Write2OneXml.

316 {
317  std::string includeNonlocalH;
318  std::string writeXmlPerStep("no");
319  std::string computeNLPPderiv;
320  std::string GEVType;
321  astring variational_subset_str;
322  ParameterSet m_param;
323  m_param.add(writeXmlPerStep, "dumpXML");
324  m_param.add(MinNumWalkers, "minwalkers");
325  m_param.add(MaxWeight, "maxWeight");
326  m_param.add(includeNonlocalH, "nonlocalpp", {}, TagStatus::DEPRECATED);
327  m_param.add(computeNLPPderiv, "use_nonlocalpp_deriv", {}, TagStatus::DEPRECATED);
328  m_param.add(w_beta, "beta");
329  m_param.add(GEVType, "GEVMethod", {}, TagStatus::DEPRECATED);
330  m_param.add(targetExcitedStr, "targetExcited");
331  m_param.add(omega_shift, "omega");
332  m_param.add(do_override_output, "output_vp_override", {true});
333  m_param.add(variational_subset_str, "variational_subset");
334  m_param.put(q);
335 
336  if (!includeNonlocalH.empty())
337  app_warning() << "'nonlocalpp' no more affects any part of the execution. Please remove it from your input file."
338  << std::endl;
339  if (!computeNLPPderiv.empty())
340  app_warning()
341  << "'use_nonlocalpp_deriv' no more affects any part of the execution. Please remove it from your input file."
342  << std::endl;
343 
345  targetExcited = (targetExcitedStr == "yes");
346 
347  variational_subset_names = convertStrToVec<std::string>(variational_subset_str.s);
348 
349  // app_log() << " QMCCostFunctionBase::put " << std::endl;
350  // m_param.get(app_log());
351  Write2OneXml = (writeXmlPerStep == "no");
352  xmlNodePtr qsave = q;
353  //Estimators.put(q);
354  std::vector<xmlNodePtr> cset;
355  std::vector<std::string> excluded;
356  std::map<std::string, std::vector<std::string>*> equalConstraints;
357  std::map<std::string, std::vector<std::string>*> negateConstraints;
358  std::vector<std::string> idtag;
359  xmlNodePtr cur = qsave->children;
360  int pid = myComm->rank();
361  while (cur != NULL)
362  {
363  std::string cname((const char*)(cur->name));
364  if (cname == "optimize")
365  {
366  std::vector<std::string> tmpid;
367  putContent(tmpid, cur);
368  idtag.insert(idtag.end(), tmpid.begin(), tmpid.end());
369  }
370  else if (cname == "exclude")
371  {
372  std::vector<std::string> tmpid;
373  putContent(tmpid, cur);
374  excluded.insert(excluded.end(), tmpid.begin(), tmpid.end());
375  }
376  else if (cname == "cost")
377  {
378  cset.push_back(cur);
379  }
380  else if (cname == "set")
381  {
382  std::string ctype("equal");
383  std::string s("0");
384  OhmmsAttributeSet pAttrib;
385  pAttrib.add(ctype, "type");
386  pAttrib.add(s, "name");
387  pAttrib.put(cur);
388  if (ctype == "equal" || ctype == "=")
389  {
390  std::map<std::string, std::vector<std::string>*>::iterator eit(equalConstraints.find(s));
391  std::vector<std::string>* eqSet = 0;
392  if (eit == equalConstraints.end())
393  {
394  eqSet = new std::vector<std::string>;
395  equalConstraints[s] = eqSet;
396  }
397  else
398  eqSet = (*eit).second;
399  std::vector<std::string> econt;
400  putContent(econt, cur);
401  eqSet->insert(eqSet->end(), econt.begin(), econt.end());
402  }
403  }
404  cur = cur->next;
405  }
406 
407  UniqueOptObjRefs opt_obj_refs = extractOptimizableObjects(Psi);
408  app_log() << " TrialWaveFunction \"" << Psi.getName() << "\" has " << opt_obj_refs.size()
409  << " optimizable objects:" << std::endl;
410  for (OptimizableObject& obj : opt_obj_refs)
411  app_log() << " '" << obj.getName() << "'" << (obj.isOptimized() ? " optimized" : " fixed") << std::endl;
412 
413  //build optimizables from the wavefunction
415  for (OptimizableObject& obj : opt_obj_refs)
416  if (obj.isOptimized())
417  obj.checkInVariablesExclusive(OptVariablesForPsi);
419  app_log() << " Variational subset selects " << OptVariablesForPsi.size() << " parameters." << std::endl;
420 
421  //synchronize OptVariables and OptVariablesForPsi
424  //first disable <exclude>.... </exclude> from the big list used by a TrialWaveFunction
425  OptVariablesForPsi.disable(excluded.begin(), excluded.end(), false);
426  //now, set up the real variable list for optimization
427  //check <equal>
428  int nc = 0;
429  if (equalConstraints.size())
430  {
431  std::map<std::string, std::vector<std::string>*>::iterator eit(equalConstraints.begin());
432  while (eit != equalConstraints.end())
433  {
434  nc += (*eit).second->size();
435  //actiave the active variable even though it is probably unnecessary
436  OptVariablesForPsi.activate((*eit).second->begin(), (*eit).second->end(), false);
437  excluded.insert(excluded.end(), (*eit).second->begin(), (*eit).second->end());
438  ++eit;
439  }
440  }
441  //build OptVariables which is equal to or identical to OptVariablesForPsi
442  //disable the variables that are equal to a variable
443  OptVariables.disable(excluded.begin(), excluded.end(), false);
444  //set up OptVariables and OptVariablesForPsi
445  OptVariables.activate(idtag.begin(), idtag.end(), true);
446  OptVariablesForPsi.activate(idtag.begin(), idtag.end(), true);
447  //found constraints build equalVarMap
448  if (nc > 0)
449  {
450  equalVarMap.reserve(nc + OptVariables.size());
451  //map the basic lists from the active list
452  for (int i = 0; i < OptVariables.size(); ++i)
453  {
454  int bigloc = OptVariablesForPsi.getIndex(OptVariables.name(i));
455  if (bigloc < 0)
456  continue;
457  equalVarMap.push_back(TinyVector<int, 2>(bigloc, i));
458  }
459  //add <equal/>
460  std::map<std::string, std::vector<std::string>*>::iterator eit(equalConstraints.begin());
461  while (eit != equalConstraints.end())
462  {
463  int loc = OptVariables.getIndex((*eit).first);
464  if (loc >= 0)
465  {
466  const std::vector<std::string>& elist(*((*eit).second));
467  for (int i = 0; i < elist.size(); ++i)
468  {
469  int bigloc = OptVariablesForPsi.getIndex(elist[i]);
470  if (bigloc < 0)
471  continue;
472  equalVarMap.push_back(TinyVector<int, 2>(bigloc, loc));
473  }
474  }
475  //remove std::vector<std::string>
476  delete (*eit).second;
477  ++eit;
478  }
479  }
480  //get the indices
483  if (NumOptimizables == 0)
484  {
485  APP_ABORT("QMCCostFunctionBase::put No valid optimizable variables are found.");
486  }
487  else
488  app_log() << " In total " << NumOptimizables << " parameters being optimized after applying constraints."
489  << std::endl;
490  // app_log() << "<active-optimizables> " << std::endl;
491  // OptVariables.print(app_log());
492  // app_log() << "</active-optimizables>" << std::endl;
493  if (msg_stream)
494  msg_stream->setf(std::ios::scientific, std::ios::floatfield);
495  resetPsi();
496  // Psi.reportStatus(app_log());
497  //set the cost function
498  if (cset.empty())
499  {
500  if (msg_stream)
501  *msg_stream << " Using Default Cost Function: Cost = <|E-E_ff|^2>" << std::endl;
502  }
503  else
504  resetCostFunction(cset);
505  //maybe overwritten but will try out
507  return true;
508 }
bool targetExcited
whether we are targeting an excited state
bool Write2OneXml
if true, do not write the *.opt.#.xml
std::ostream & app_warning()
Definition: OutputManager.h:69
std::vector< std::string > variational_subset_names
optimized parameter names
int rank() const
return the rank
Definition: Communicate.h:116
std::ostream * msg_stream
stream to which progress is sent
std::ostream & app_log()
Definition: OutputManager.h:65
std::vector< TinyVector< int, 2 > > equalVarMap
index mapping for <equal> constraints
bool put(xmlNodePtr cur)
assign attributes to the set
Definition: AttributeSet.h:55
Return_rt MinNumWalkers
fraction of the number of walkers below which the costfunction becomes invalid
int NumOptimizables
total number of optimizable variables
opt_variables_type OptVariables
list of optimizables
void disable(ForwardIterator first, ForwardIterator last, bool reindex)
deactivate variables for optimization
Definition: VariableSet.h:289
const std::string & getName() const
void resetIndex()
reset Index
void activate(ForwardIterator first, ForwardIterator last, bool reindex)
activate variables for optimization
Definition: VariableSet.h:264
bool do_override_output
Flag on whether the variational parameter override is output to the new wavefunction.
bool put(std::istream &is) override
read from std::istream
Definition: ParameterSet.h:42
class to handle a set of parameters
Definition: ParameterSet.h:27
Communicate * myComm
pointer to Communicate
Definition: MPIObjectBase.h:62
class to handle a set of attributes of an xmlNode
Definition: AttributeSet.h:24
std::string lowerCase(const std::string_view s)
++17
opt_variables_type OptVariablesForPsi
full list of optimizables
#define APP_ABORT(msg)
Widely used but deprecated fatal error macros from legacy code.
Definition: AppAbort.h:27
void checkOutVariables(const opt_variables_type &o)
Check out optimizable variables Assign index mappings from global list (o) to local values in each co...
void clear()
clear the variable set
Definition: VariableSet.cpp:28
size_type size() const
return the size
Definition: VariableSet.h:88
bool putContent(T &a, xmlNodePtr cur)
replaces a&#39;s value with the first "element" in the "string" returned by XMLNodeString{cur}.
Definition: libxmldefs.h:88
void add(PDT &aparam, const std::string &aname_in, std::vector< PDT > candidate_values={}, TagStatus status=TagStatus::OPTIONAL)
add a new parameter corresponding to an xmlNode <parameter>
UniqueOptObjRefs extractOptimizableObjects(TrialWaveFunction &psi) const
survey all the optimizable objects
std::string targetExcitedStr
whether we are targeting an excited state
const std::string & name(int i) const
return the name of i-th variable
Definition: VariableSet.h:189
TrialWaveFunction & Psi
Trial function.
Return_rt MaxWeight
maximum weight beyond which the weight is set to 1
void add(PDT &aparam, const std::string &aname, std::vector< PDT > candidate_values={}, TagStatus status=TagStatus::OPTIONAL)
add a new attribute
Definition: AttributeSet.h:42
int getIndex(const std::string &vname) const
return the Index vaule for the named parameter
void resetCostFunction(std::vector< xmlNodePtr > &cset)
double omega_shift
the shift to use when targeting an excited state
Return_rt EtargetEff
real target energy with the Correlation Factor
virtual void resetPsi(bool final_reset=false)=0
reset the wavefunction

◆ Report()

void Report ( )
override

dump the current parameters and other report

Definition at line 173 of file QMCCostFunctionBase.cpp.

References QMCCostFunctionBase::CostValue, QMCCostFunctionBase::curAvg, QMCCostFunctionBase::curAvg_w, QMCCostFunctionBase::curVar, QMCCostFunctionBase::curVar_abs, QMCCostFunctionBase::curVar_w, QMCCostFunctionBase::debug_stream, QMCCostFunctionBase::m_doc_out, QMCCostFunctionBase::msg_stream, MPIObjectBase::myComm, QMCCostFunctionBase::OptVariables, VariableSet::print(), Communicate::rank(), QMCCostFunctionBase::ReportCounter, QMCCostFunctionBase::resetPsi(), QMCCostFunctionBase::RootName, VariableSet::size(), QMCCostFunctionBase::updateXmlNodes(), and QMCCostFunctionBase::Write2OneXml.

174 {
175  //reset the wavefunction for with the new variables
176  resetPsi();
177  if (!myComm->rank())
178  {
179  updateXmlNodes();
180  std::array<char, 128> newxml;
181  int length{0};
182  if (Write2OneXml)
183  length = std::snprintf(newxml.data(), newxml.size(), "%s.opt.xml", RootName.c_str());
184  else
185  length = std::snprintf(newxml.data(), newxml.size(), "%s.opt.%d.xml", RootName.c_str(), ReportCounter);
186  if (length < 0)
187  throw std::runtime_error("Error generating fileroot");
188  xmlSaveFormatFile(newxml.data(), m_doc_out, 1);
189  if (msg_stream)
190  {
191  msg_stream->precision(8);
192  *msg_stream << " curCost " << std::setw(5) << ReportCounter << std::setw(16) << CostValue << std::setw(16)
193  << curAvg_w << std::setw(16) << curAvg << std::setw(16) << curVar_w << std::setw(16) << curVar
194  << std::setw(16) << curVar_abs << std::endl;
195  *msg_stream << " curVars " << std::setw(5) << ReportCounter;
196  for (int i = 0; i < OptVariables.size(); i++)
197  *msg_stream << std::setw(16) << OptVariables[i];
198  *msg_stream << std::endl;
199  }
200  //report the data
201  //Psi.reportStatus(*mgs_stream);
202  }
203 #if defined(QMCCOSTFUNCTION_DEBUG)
206  *debug_stream << std::endl;
207 #endif
208  ReportCounter++;
209  //myComm->barrier();
210 }
bool Write2OneXml
if true, do not write the *.opt.#.xml
Return_rt CostValue
value of the cost function
int rank() const
return the rank
Definition: Communicate.h:116
std::ostream * msg_stream
stream to which progress is sent
std::string RootName
string for the file root
Return_rt curAvg_w
current weighted average (correlated sampling)
opt_variables_type OptVariables
list of optimizables
Communicate * myComm
pointer to Communicate
Definition: MPIObjectBase.h:62
Return_rt curAvg
current Average
size_type size() const
return the size
Definition: VariableSet.h:88
std::unique_ptr< std::ostream > debug_stream
stream for debug
int ReportCounter
counter for output
xmlDocPtr m_doc_out
document node to be dumped
Return_rt curVar_abs
current variance of SUM_ABSE_WGT/SUM_WGT
void print(std::ostream &os, int leftPadSpaces=0, bool printHeader=false) const
Return_rt curVar
current Variance
Return_rt curVar_w
current weighted variance (correlated sampling)
virtual void resetPsi(bool final_reset=false)=0
reset the wavefunction

◆ reportParameters()

void reportParameters ( )

report parameters at the end

Definition at line 212 of file QMCCostFunctionBase.cpp.

References TrialWaveFunction::extractOptimizableObjectRefs(), QMCCostFunctionBase::m_doc_out, QMCCostFunctionBase::msg_stream, MPIObjectBase::myComm, QMCCostFunctionBase::OptVariables, VariableSet::print(), QMCCostFunctionBase::Psi, Communicate::rank(), QMCCostFunctionBase::resetPsi(), QMCCostFunctionBase::RootName, QMCCostFunctionBase::updateXmlNodes(), and VariableSet::writeToHDF().

213 {
214  //final reset
215  resetPsi(true);
216  if (!myComm->rank())
217  {
218  std::ostringstream vp_filename;
219  vp_filename << RootName << ".vp.h5";
220  hdf_archive hout;
221  OptVariables.writeToHDF(vp_filename.str(), hout);
222 
223  UniqueOptObjRefs opt_obj_refs = Psi.extractOptimizableObjectRefs();
224  for (auto opt_obj : opt_obj_refs)
225  opt_obj.get().writeVariationalParameters(hout);
226 
227  std::string newxml = RootName + ".opt.xml";
228  *msg_stream << " <optVariables href=\"" << newxml << "\">" << std::endl;
230  *msg_stream << " </optVariables>" << std::endl;
231  updateXmlNodes();
232  xmlSaveFormatFile(newxml.c_str(), m_doc_out, 1);
233  }
234 }
void writeToHDF(const std::string &filename, qmcplusplus::hdf_archive &hout) const
int rank() const
return the rank
Definition: Communicate.h:116
std::ostream * msg_stream
stream to which progress is sent
std::string RootName
string for the file root
opt_variables_type OptVariables
list of optimizables
UniqueOptObjRefs extractOptimizableObjectRefs()
extract underlying OptimizableObject references
Communicate * myComm
pointer to Communicate
Definition: MPIObjectBase.h:62
xmlDocPtr m_doc_out
document node to be dumped
TrialWaveFunction & Psi
Trial function.
void print(std::ostream &os, int leftPadSpaces=0, bool printHeader=false) const
virtual void resetPsi(bool final_reset=false)=0
reset the wavefunction

◆ reportParametersH5()

void reportParametersH5 ( )

report parameters in HDF5 at the end

This function stores optimized CI coefficients in HDF5 Other parameters (Jastors, orbitals), can also be stored to H5 from this function This function should be called before reportParameters() Since it is needed to call updateXmlNodes() and xmlSaveFormatFile() While it is possible to call updateXmlNodes() from QMCLinearOptimize.cpp It is not clean to call xmlSaveFormatFile() from QMCLinearOptimize.cpp.

Parameters
OptVariables.size()OptVariables.name(i) OptVariables[i]

OptVariables.size(): contains the total number of Optimized variables (not Only CI coeff) OptVariables.name(i): the tag of the optimized variable. To store we use the name of the variable OptVariables[i]: The new value of the optimized variable

Definition at line 248 of file QMCCostFunctionBase.cpp.

References QMCCostFunctionBase::CI_Opt, hdf_archive::close(), hdf_archive::create(), QMCCostFunctionBase::msg_stream, MPIObjectBase::myComm, VariableSet::name(), QMCCostFunctionBase::newh5, QMCCostFunctionBase::OptVariables, hdf_archive::push(), Communicate::rank(), QMCCostFunctionBase::RootName, VariableSet::size(), and hdf_archive::write().

249 {
250  if (!myComm->rank())
251  {
252  int ci_size = 0;
253  std::vector<opt_variables_type::real_type> CIcoeff;
254  for (int i = 0; i < OptVariables.size(); i++)
255  {
256  std::array<char, 128> Coeff;
257  if (std::snprintf(Coeff.data(), Coeff.size(), "CIcoeff_%d", ci_size + 1) < 0)
258  throw std::runtime_error("Error generating fileroot");
259  if (OptVariables.name(i) != Coeff.data())
260  {
261  if (ci_size > 0)
262  break;
263  else
264  continue;
265  }
266 
267  CIcoeff.push_back(OptVariables[i]);
268  ci_size++;
269  }
270  if (ci_size > 0)
271  {
272  CI_Opt = true;
273  newh5 = RootName + ".opt.h5";
274  *msg_stream << " <Ci Coeffs saved in opt_coeffs=\"" << newh5 << "\">" << std::endl;
275  hdf_archive hout;
276  hout.create(newh5, H5F_ACC_TRUNC);
277  hout.push("MultiDet", true);
278  hout.write(ci_size, "NbDet");
279  hout.write(CIcoeff, "Coeff");
280  hout.close();
281  }
282  }
283 }
int rank() const
return the rank
Definition: Communicate.h:116
std::ostream * msg_stream
stream to which progress is sent
std::string RootName
string for the file root
opt_variables_type OptVariables
list of optimizables
std::string newh5
Path and name of the HDF5 prefix where CI coeffs are saved.
Communicate * myComm
pointer to Communicate
Definition: MPIObjectBase.h:62
size_type size() const
return the size
Definition: VariableSet.h:88
const std::string & name(int i) const
return the name of i-th variable
Definition: VariableSet.h:189

◆ resetCostFunction()

void resetCostFunction ( std::vector< xmlNodePtr > &  cset)

Definition at line 510 of file QMCCostFunctionBase.cpp.

References OhmmsAttributeSet::add(), OhmmsAttributeSet::put(), putContent(), QMCCostFunctionBase::w_abs, QMCCostFunctionBase::w_en, QMCCostFunctionBase::w_var, and QMCCostFunctionBase::w_w.

Referenced by QMCCostFunctionBase::put().

511 {
512  for (int i = 0; i < cset.size(); i++)
513  {
514  std::string pname;
515  OhmmsAttributeSet pAttrib;
516  pAttrib.add(pname, "name");
517  pAttrib.put(cset[i]);
518  if (pname == "energy")
519  putContent(w_en, cset[i]);
520  else if ((pname == "variance") || (pname == "unreweightedvariance"))
521  putContent(w_w, cset[i]);
522  else if (pname == "difference")
523  putContent(w_abs, cset[i]);
524  else if ((pname == "reweightedVariance") || (pname == "reweightedvariance"))
525  putContent(w_var, cset[i]);
526  }
527 }
bool put(xmlNodePtr cur)
assign attributes to the set
Definition: AttributeSet.h:55
class to handle a set of attributes of an xmlNode
Definition: AttributeSet.h:24
Return_rt w_en
weights for energy and variance in the cost function
bool putContent(T &a, xmlNodePtr cur)
replaces a&#39;s value with the first "element" in the "string" returned by XMLNodeString{cur}.
Definition: libxmldefs.h:88
void add(PDT &aparam, const std::string &aname, std::vector< PDT > candidate_values={}, TagStatus status=TagStatus::OPTIONAL)
add a new attribute
Definition: AttributeSet.h:42

◆ resetOptimizableObjects()

void resetOptimizableObjects ( TrialWaveFunction psi,
const opt_variables_type opt_variables 
) const
protected

Definition at line 1099 of file QMCCostFunctionBase.cpp.

References QMCCostFunctionBase::extractOptimizableObjects().

Referenced by QMCCostFunction::resetPsi(), and QMCCostFunctionBatched::resetPsi().

1100 {
1101  const auto opt_obj_refs = extractOptimizableObjects(psi);
1102  for (OptimizableObject& obj : opt_obj_refs)
1103  if (obj.isOptimized())
1104  obj.resetParametersExclusive(opt_variables);
1105 }
UniqueOptObjRefs extractOptimizableObjects(TrialWaveFunction &psi) const
survey all the optimizable objects

◆ resetPsi()

virtual void resetPsi ( bool  final_reset = false)
pure virtual

◆ setDMC()

void setDMC ( )
inline

Definition at line 162 of file QMCCostFunctionBase.h.

References QMCCostFunctionBase::vmc_or_dmc.

◆ setneedGrads()

void setneedGrads ( bool  tf)
inline

◆ setNumSamples()

void setNumSamples ( int  newNumSamples)
inline

Definition at line 106 of file QMCCostFunctionBase.h.

References QMCCostFunctionBase::NumSamples.

106 { NumSamples = newNumSamples; }
int NumSamples
global number of samples to use in correlated sampling

◆ setRng()

void setRng ( RefVector< RandomBase< FullPrecRealType >>  r)

Definition at line 85 of file QMCCostFunctionBase.cpp.

References QMCCostFunctionBase::MoverRng, and QMCCostFunctionBase::RngSaved.

86 {
87  if (MoverRng.size() < r.size())
88  {
89  MoverRng.resize(r.size());
90  RngSaved.resize(r.size());
91  }
92  for (int ip = 0; ip < r.size(); ++ip)
93  MoverRng[ip] = &r[ip].get();
94  for (int ip = 0; ip < r.size(); ++ip)
95  RngSaved[ip] = r[ip].get().makeClone();
96 }
UPtrVector< RandomBase< FullPrecRealType > > RngSaved
Random number generators.
std::vector< RandomBase< FullPrecRealType > * > MoverRng

◆ setRootName()

void setRootName ( const std::string &  aroot)
inline

Definition at line 129 of file QMCCostFunctionBase.h.

References QMCCostFunctionBase::RootName.

Referenced by qmcplusplus::TEST_CASE().

129 { RootName = aroot; }
std::string RootName
string for the file root

◆ setStream()

void setStream ( std::ostream *  os)
inline

Definition at line 131 of file QMCCostFunctionBase.h.

References QMCCostFunctionBase::msg_stream.

131 { msg_stream = os; }
std::ostream * msg_stream
stream to which progress is sent

◆ setTargetEnergy()

void setTargetEnergy ( Return_rt  et)

Definition at line 98 of file QMCCostFunctionBase.cpp.

References QMCCostFunctionBase::Etarget, and QMCCostFunctionBase::EtargetEff.

Referenced by QMCCostFunction::checkConfigurations(), and QMCCostFunctionBatched::checkConfigurations().

99 {
100  //evaluate effective target energy
101  EtargetEff = Etarget = et;
102  // app_log() << "Effective Target Energy = " << EtargetEff << std::endl;
103  // app_log() << "Cost Function = " << w_en << "*<E> + "
104  // << w_var << "*<Var> + " << w_w << "*<Var(unreweighted)> " << std::endl;
105  //if(UseWeight)
106  //app_log() << "Correlated sampling is used." << std::endl;
107  //else
108  //app_log() << "Weight is set to one." << std::endl;
109  // if (msg_stream)
110  // {
111  // *msg_stream << " Total number of walkers = " << NumSamples << std::endl;
112  // *msg_stream << " Effective Target Energy = " << EtargetEff << std::endl;
113  // *msg_stream << " Cost Function = " << w_en << "*<E> + " << w_var << "*<Var> + " << w_w << "*<Var(unreweighted)> " << std::endl;
114  // *msg_stream << " Optimization report = ";
115  // *msg_stream << "cost, walkers, eavg/wgt, eavg/walkers, evar/wgt, evar/walkers, evar_abs\n";
116  // *msg_stream << " Optimized variables = " << OptVariables.name(0);
117  // for (int i=1; i<OptVariables.size(); ++i) *msg_stream << "," << OptVariables.name(i) ;
118  // *msg_stream << std::endl;
119  // }
120 }
Return_rt EtargetEff
real target energy with the Correlation Factor

◆ setWaveFunctionNode()

void setWaveFunctionNode ( xmlNodePtr  cur)
inline

Definition at line 125 of file QMCCostFunctionBase.h.

References QMCCostFunctionBase::m_wfPtr.

Referenced by qmcplusplus::TEST_CASE().

125 { m_wfPtr = cur; }
xmlNodePtr m_wfPtr
xml node to be dumped

◆ updateXmlNodes()

void updateXmlNodes ( )
protected

Definition at line 530 of file QMCCostFunctionBase.cpp.

References OhmmsAttributeSet::add(), QMCCostFunctionBase::addCJParams(), QMCCostFunctionBase::addCoefficients(), QMCCostFunctionBase::attribNodes, QMCCostFunctionBase::CI_Opt, QMCCostFunctionBase::coeffNodes, QMCCostFunctionBase::do_override_output, OhmmsXPathObject::empty(), VariableSet::end(), VariableSet::find(), getContent(), getXMLAttributeValue(), QMCCostFunctionBase::m_doc_out, QMCCostFunctionBase::m_wfPtr, QMCCostFunctionBase::newh5, QMCCostFunctionBase::OptVariablesForPsi, QMCCostFunctionBase::paramNodes, QMCCostFunctionBase::printCJParams(), OhmmsAttributeSet::put(), QMCCostFunctionBase::RootName, and OhmmsXPathObject::size().

Referenced by QMCCostFunctionTest::callUpdateXmlNodes(), QMCCostFunctionBase::Report(), and QMCCostFunctionBase::reportParameters().

531 {
532  if (m_doc_out == NULL) //first time, create a document tree and get parameters and attributes to be updated
533  {
534  m_doc_out = xmlNewDoc((const xmlChar*)"1.0");
535  xmlNodePtr qm_root = xmlNewNode(NULL, BAD_CAST "qmcsystem");
536  xmlNodePtr wf_root = xmlAddChild(qm_root, xmlCopyNode(m_wfPtr, 1));
537  xmlDocSetRootElement(m_doc_out, qm_root);
538  xmlXPathContextPtr acontext = xmlXPathNewContext(m_doc_out);
539 
540  if (do_override_output)
541  {
542  std::ostringstream vp_filename;
543  vp_filename << RootName << ".vp.h5";
544 
545  OhmmsXPathObject vp_file_nodes("//override_variational_parameters", acontext);
546  if (vp_file_nodes.empty())
547  {
548  // Element is not present. Create a new one.
549  xmlNodePtr vp_file_node = xmlNewNode(NULL, BAD_CAST "override_variational_parameters");
550  xmlSetProp(vp_file_node, BAD_CAST "href", BAD_CAST vp_filename.str().c_str());
551  xmlAddChild(wf_root, vp_file_node);
552  }
553  else
554  {
555  // Element is present. Rewrite the href attribute.
556  for (int iparam = 0; iparam < vp_file_nodes.size(); iparam++)
557  {
558  xmlSetProp(vp_file_nodes[iparam], BAD_CAST "href", BAD_CAST vp_filename.str().c_str());
559  }
560  }
561  }
562 
563  //check var
564  xmlXPathObjectPtr result = xmlXPathEvalExpression((const xmlChar*)"//var", acontext);
565  for (int iparam = 0; iparam < result->nodesetval->nodeNr; iparam++)
566  {
567  xmlNodePtr cur = result->nodesetval->nodeTab[iparam];
568  std::string aname(getXMLAttributeValue(cur, "id"));
569  if (aname.empty())
570  continue;
571  if (auto oit = OptVariablesForPsi.find(aname); oit != OptVariablesForPsi.end())
572  paramNodes[aname] = cur;
573  }
574  xmlXPathFreeObject(result);
575  //check radfunc
576  result = xmlXPathEvalExpression((const xmlChar*)"//radfunc", acontext);
577  for (int iparam = 0; iparam < result->nodesetval->nodeNr; iparam++)
578  {
579  xmlNodePtr cur = result->nodesetval->nodeTab[iparam];
580  std::string aname(getXMLAttributeValue(cur, "id"));
581  if (aname.empty())
582  continue;
583  if (xmlAttrPtr aptr = xmlHasProp(cur, (const xmlChar*)"exponent"); aptr != nullptr)
584  {
585  std::string expID = aname + "_E";
586  if (auto oit = OptVariablesForPsi.find(expID); oit != OptVariablesForPsi.end())
587  attribNodes[expID] = std::pair<xmlNodePtr, std::string>(cur, "exponent");
588  }
589  std::string cID = aname + "_C";
590  if (xmlAttrPtr aptr = xmlHasProp(cur, (const xmlChar*)"contraction"); aptr != nullptr)
591  if (auto oit = OptVariablesForPsi.find(cID); oit != OptVariablesForPsi.end())
592  attribNodes[cID] = std::pair<xmlNodePtr, std::string>(cur, "contraction");
593  }
594  xmlXPathFreeObject(result);
595  //check ci
596  result = xmlXPathEvalExpression((const xmlChar*)"//ci", acontext);
597  for (int iparam = 0; iparam < result->nodesetval->nodeNr; iparam++)
598  {
599  xmlNodePtr cur = result->nodesetval->nodeTab[iparam];
600  std::string aname(getXMLAttributeValue(cur, "id"));
601  if (aname.empty())
602  continue;
603  xmlAttrPtr aptr = xmlHasProp(cur, (const xmlChar*)"coeff");
605  if (xmlAttrPtr aptr = xmlHasProp(cur, (const xmlChar*)"coeff"); aptr != NULL)
606  if (auto oit = OptVariablesForPsi.find(aname); oit != OptVariablesForPsi.end())
607  attribNodes[aname] = std::pair<xmlNodePtr, std::string>(cur, "coeff");
608  }
609  xmlXPathFreeObject(result);
610  //check csf
611  result = xmlXPathEvalExpression((const xmlChar*)"//csf", acontext);
612  for (int iparam = 0; iparam < result->nodesetval->nodeNr; iparam++)
613  {
614  xmlNodePtr cur = result->nodesetval->nodeTab[iparam];
615  std::string aname(getXMLAttributeValue(cur, "id"));
616  if (aname.empty())
617  continue;
618  if (xmlAttrPtr aptr = xmlHasProp(cur, (const xmlChar*)"coeff"); aptr != nullptr)
619  if (auto oit = OptVariablesForPsi.find(aname); oit != OptVariablesForPsi.end())
620  attribNodes[aname] = std::pair<xmlNodePtr, std::string>(cur, "coeff");
621  }
622  xmlXPathFreeObject(result);
623  if (CI_Opt)
624  {
625  //check multidet
626  result = xmlXPathEvalExpression((const xmlChar*)"//detlist", acontext);
627  for (int iparam = 0; iparam < result->nodesetval->nodeNr; iparam++)
628  {
629  xmlNodePtr cur = result->nodesetval->nodeTab[iparam];
630  xmlSetProp(cur, (const xmlChar*)"opt_coeffs", (const xmlChar*)newh5.c_str());
631  }
632  xmlXPathFreeObject(result);
633  }
634 
635  addCoefficients(acontext, "//coefficient");
636  addCoefficients(acontext, "//coefficients");
637  addCJParams(acontext, "//jastrow");
638  xmlXPathFreeContext(acontext);
639  }
640  for (const auto& [pname, pptr] : paramNodes)
641  {
642  //FIXME real value is forced here to makde sure that the code builds
643  Return_rt v = std::real(OptVariablesForPsi[pname]);
644  getContent(v, pptr);
645  }
646  for (const auto& [aname, attrib] : attribNodes)
647  {
648  std::ostringstream vout;
649  vout.setf(std::ios::scientific, std::ios::floatfield);
650  vout.precision(16);
651  vout << OptVariablesForPsi[aname];
652  xmlSetProp(attrib.first, (const xmlChar*)attrib.second.c_str(), (const xmlChar*)vout.str().c_str());
653  }
654  for (const auto& [cname, cptr] : coeffNodes)
655  {
656  std::string rname(cname);
657  OhmmsAttributeSet cAttrib;
658  std::string datatype("none");
659  std::string aname("0");
660  cAttrib.add(datatype, "type");
661  cAttrib.add(aname, "id");
662  cAttrib.put(cptr);
663  if (datatype == "Array")
664  {
665  //
666  aname.append("_");
667  std::vector<Return_rt> c;
668  for (const auto& [name, value] : OptVariablesForPsi)
669  {
670  if (name.find(aname) == 0)
671  {
672  //FIXME real value is forced here to makde sure that the code builds
673  c.push_back(std::real(value));
674  }
675  }
676  xmlNodePtr contentPtr = cptr;
677  if (xmlNodeIsText(contentPtr->children))
678  contentPtr = contentPtr->children;
679  getContent(c, contentPtr);
680  }
681  // counting jastrow variables
682  else if (rname.find("cj_") == 0)
683  {
684  printCJParams(cptr, rname);
685  }
686  else
687  {
688  xmlNodePtr cur = cptr->children;
689  while (cur != NULL)
690  {
691  std::string childName((const char*)(cur->name));
692  if (childName == "lambda")
693  {
694  int i = 0;
695  int j = -1;
696  OhmmsAttributeSet pAttrib;
697  pAttrib.add(i, "i");
698  pAttrib.add(j, "j");
699  pAttrib.put(cur);
700  std::array<char, 32> lambda_id;
701  int length{0};
702  if (j < 0)
703  length = std::snprintf(lambda_id.data(), lambda_id.size(), "%s_%d", rname.c_str(), i);
704  else
705  length = std::snprintf(lambda_id.data(), lambda_id.size(), "%s_%d_%d", rname.c_str(), i, j);
706  if (length < 0)
707  throw std::runtime_error("Error generating lambda_id");
708  opt_variables_type::iterator vTarget(OptVariablesForPsi.find(lambda_id.data()));
709  if (vTarget != OptVariablesForPsi.end())
710  {
711  std::ostringstream vout;
712  vout.setf(std::ios::scientific, std::ios::floatfield);
713  vout.precision(16);
714  vout << (*vTarget).second;
715  xmlSetProp(cur, (const xmlChar*)"c", (const xmlChar*)vout.str().c_str());
716  }
717  }
718  cur = cur->next;
719  }
720  }
721  }
722 }
iterator find(const std::string &vname)
return the iterator of a named parameter
Definition: VariableSet.h:98
QMCTraits::RealType real
const_iterator end() const
return the last const_iterator
Definition: VariableSet.h:82
std::string RootName
string for the file root
std::vector< pair_type >::iterator iterator
Definition: VariableSet.h:55
bool put(xmlNodePtr cur)
assign attributes to the set
Definition: AttributeSet.h:55
void addCJParams(xmlXPathContextPtr acontext, const char *cname)
xmlNodePtr m_wfPtr
xml node to be dumped
std::map< std::string, std::pair< xmlNodePtr, std::string > > attribNodes
attributes to be updated
bool do_override_output
Flag on whether the variational parameter override is output to the new wavefunction.
class to handle xmlXPathObject
Definition: Libxml2Doc.h:26
std::string newh5
Path and name of the HDF5 prefix where CI coeffs are saved.
class to handle a set of attributes of an xmlNode
Definition: AttributeSet.h:24
std::map< std::string, xmlNodePtr > paramNodes
parameters to be updated`
opt_variables_type OptVariablesForPsi
full list of optimizables
std::string getXMLAttributeValue(const xmlNodePtr cur, const std::string_view name)
get the value string for attribute name if name is unfound in cur you get an empty string back this i...
void printCJParams(xmlNodePtr cur, std::string &rname)
bool getContent(const T &a, xmlNodePtr cur)
write a value to a node.
Definition: libxmldefs.h:119
xmlDocPtr m_doc_out
document node to be dumped
void addCoefficients(xmlXPathContextPtr acontext, const char *cname)
add coefficient or coefficients
void add(PDT &aparam, const std::string &aname, std::vector< PDT > candidate_values={}, TagStatus status=TagStatus::OPTIONAL)
add a new attribute
Definition: AttributeSet.h:42
std::map< std::string, xmlNodePtr > coeffNodes
coefficients to be updated

Member Data Documentation

◆ attribNodes

std::map<std::string, std::pair<xmlNodePtr, std::string> > attribNodes
protected

attributes to be updated

Definition at line 269 of file QMCCostFunctionBase.h.

Referenced by QMCCostFunctionBase::updateXmlNodes().

◆ CI_Opt

◆ coeffNodes

std::map<std::string, xmlNodePtr> coeffNodes
protected

◆ CostValue

Return_rt CostValue
protected

value of the cost function

Definition at line 203 of file QMCCostFunctionBase.h.

Referenced by QMCCostFunctionBase::computedCost(), and QMCCostFunctionBase::Report().

◆ curAvg

◆ curAvg_w

◆ curVar

Return_rt curVar
protected

◆ curVar_abs

Return_rt curVar_abs
protected

current variance of SUM_ABSE_WGT/SUM_WGT

Definition at line 221 of file QMCCostFunctionBase.h.

Referenced by QMCCostFunctionBase::computedCost(), and QMCCostFunctionBase::Report().

◆ curVar_w

Return_rt curVar_w
protected

◆ d2LogPsi

◆ debug_stream

std::unique_ptr<std::ostream> debug_stream
protected

◆ dLogPsi

◆ do_override_output

bool do_override_output
protected

Flag on whether the variational parameter override is output to the new wavefunction.

Definition at line 309 of file QMCCostFunctionBase.h.

Referenced by QMCCostFunctionTest::callUpdateXmlNodes(), QMCCostFunctionBase::put(), and QMCCostFunctionBase::updateXmlNodes().

◆ equalVarMap

std::vector<TinyVector<int, 2> > equalVarMap
protected

index mapping for <equal> constraints

  • equalVarMap[i][0] : index in OptVariablesForPsi
  • equalVarMap[i][1] : index in OptVariables

Definition at line 250 of file QMCCostFunctionBase.h.

Referenced by QMCCostFunctionBase::put(), QMCCostFunction::resetPsi(), and QMCCostFunctionBatched::resetPsi().

◆ Etarget

◆ EtargetEff

◆ H

◆ InitVariables

opt_variables_type InitVariables
protected

◆ m_doc_out

◆ m_wfPtr

xmlNodePtr m_wfPtr
protected

xml node to be dumped

Definition at line 261 of file QMCCostFunctionBase.h.

Referenced by QMCCostFunctionBase::setWaveFunctionNode(), and QMCCostFunctionBase::updateXmlNodes().

◆ MaxWeight

Return_rt MaxWeight
protected

maximum weight beyond which the weight is set to 1

Definition at line 211 of file QMCCostFunctionBase.h.

Referenced by QMCCostFunction::correlatedSampling(), QMCCostFunctionBatched::correlatedSampling(), and QMCCostFunctionBase::put().

◆ MinNumWalkers

Return_rt MinNumWalkers
protected

fraction of the number of walkers below which the costfunction becomes invalid

Definition at line 209 of file QMCCostFunctionBase.h.

Referenced by QMCCostFunctionBase::isEffectiveWeightValid(), QMCCostFunctionBase::put(), and QMCCostFunctionBase::QMCCostFunctionBase().

◆ MoverRng

◆ msg_stream

◆ needGrads

◆ negateVarMap

std::vector<TinyVector<int, 2> > negateVarMap
protected

index mapping for <negate> constraints

  • negateVarMap[i][0] : index in OptVariablesForPsi
  • negateVarMap[i][1] : index in OptVariablesindex mapping for <negative> constraints

Definition at line 257 of file QMCCostFunctionBase.h.

◆ newh5

std::string newh5

Path and name of the HDF5 prefix where CI coeffs are saved.

Definition at line 86 of file QMCCostFunctionBase.h.

Referenced by QMCCostFunctionBase::reportParametersH5(), and QMCCostFunctionBase::updateXmlNodes().

◆ NumCostCalls

int NumCostCalls
protected

number of times cost function evaluated

Definition at line 193 of file QMCCostFunctionBase.h.

Referenced by QMCCostFunctionBase::Cost().

◆ NumOptimizables

◆ NumSamples

◆ omega_shift

double omega_shift
protected

the shift to use when targeting an excited state

Definition at line 231 of file QMCCostFunctionBase.h.

Referenced by QMCCostFunctionBase::put().

◆ OptVariables

◆ OptVariablesForPsi

◆ paramNodes

std::map<std::string, xmlNodePtr> paramNodes
protected

parameters to be updated`

Definition at line 265 of file QMCCostFunctionBase.h.

Referenced by QMCCostFunctionBase::updateXmlNodes().

◆ PowerE

int PowerE
protected

|E-E_T|^PowerE is used for the cost function

default PowerE=1

Definition at line 191 of file QMCCostFunctionBase.h.

Referenced by QMCCostFunction::correlatedSampling(), QMCCostFunctionBatched::correlatedSampling(), QMCCostFunction::GradCost(), and QMCCostFunctionBatched::GradCost().

◆ Psi

◆ Records

Matrix<Return_rt> Records
protected

Saved properties of all the walkers.

Records(iw,field_id) returns the field_id value of the iw-th walker field_id is one of FieldIndex_opt

Definition at line 290 of file QMCCostFunctionBase.h.

◆ ReportCounter

◆ reportH5

bool reportH5

Save opt parameters to HDF5.

Definition at line 83 of file QMCCostFunctionBase.h.

◆ RngSaved

◆ RootName

◆ SumValue

◆ targetExcited

bool targetExcited
protected

whether we are targeting an excited state

Definition at line 229 of file QMCCostFunctionBase.h.

Referenced by QMCCostFunctionBase::put().

◆ targetExcitedStr

std::string targetExcitedStr
protected

whether we are targeting an excited state

Definition at line 227 of file QMCCostFunctionBase.h.

Referenced by QMCCostFunctionBase::put().

◆ variational_subset_names

std::vector<std::string> variational_subset_names
protected

optimized parameter names

Definition at line 278 of file QMCCostFunctionBase.h.

Referenced by QMCCostFunctionBase::extractOptimizableObjects(), and QMCCostFunctionBase::put().

◆ vmc_or_dmc

◆ W

◆ w_abs

◆ w_beta

◆ w_en

Return_rt w_en
protected

weights for energy and variance in the cost function

Definition at line 201 of file QMCCostFunctionBase.h.

Referenced by QMCCostFunctionBase::computedCost(), QMCCostFunction::GradCost(), QMCCostFunctionBatched::GradCost(), and QMCCostFunctionBase::resetCostFunction().

◆ w_var

◆ w_w

◆ Write2OneXml

bool Write2OneXml
protected

if true, do not write the *.opt.#.xml

Definition at line 186 of file QMCCostFunctionBase.h.

Referenced by QMCCostFunctionBase::put(), and QMCCostFunctionBase::Report().

◆ qmcplusplus::QMCFixedSampleLinearOptimize

class qmcplusplus::QMCFixedSampleLinearOptimize

Implements wave-function optimization.

Optimization by correlated sampling method with configurations generated from VMC.

Definition at line 43 of file QMCFixedSampleLinearOptimize.h.

+ Inheritance diagram for QMCFixedSampleLinearOptimize:
+ Collaboration diagram for QMCFixedSampleLinearOptimize:

Public Member Functions

 QMCFixedSampleLinearOptimize (const ProjectData &project_data, MCWalkerConfiguration &w, TrialWaveFunction &psi, QMCHamiltonian &h, Communicate *)
 Constructor. More...
 
 ~QMCFixedSampleLinearOptimize () override
 Destructor. More...
 
bool run () override
 Run the Optimization algorithm. More...
 
bool put (xmlNodePtr cur) override
 preprocess xml node More...
 
bool processOptXML (xmlNodePtr cur, const std::string &vmcMove, bool reportH5)
 process xml node value (parameters for both VMC and OPT) for the actual optimization More...
 
RealType Func (RealType dl) override
 
void setWaveFunctionNode (xmlNodePtr cur)
 
QMCRunType getRunType () override
 
- Public Member Functions inherited from QMCDriver
 QMCDriver (const ProjectData &project_data, MCWalkerConfiguration &w, TrialWaveFunction &psi, QMCHamiltonian &h, Communicate *comm, const std::string &QMC_driver_type, bool enable_profiling=false)
 Constructor. More...
 
 ~QMCDriver () override
 
int current () const
 return current step More...
 
void setUpdateMode (bool pbyp) override
 set the update mode More...
 
void setStatus (const std::string &aname, const std::string &h5name, bool append) override
 Set the status of the QMCDriver. More...
 
void add_H_and_Psi (QMCHamiltonian *h, TrialWaveFunction *psi) override
 add QMCHamiltonian/TrialWaveFunction pair for multiple More...
 
void process (xmlNodePtr cur) override
 initialize with xmlNode More...
 
xmlNodePtr getQMCNode ()
 return a xmlnode with update More...
 
void putWalkers (std::vector< xmlNodePtr > &wset) override
 Read walker configurations from *.config.h5 files. More...
 
void putTraces (xmlNodePtr txml) override
 
void requestTraces (bool traces) override
 
void putWalkerLogs (xmlNodePtr wlxml) override
 
void requestWalkerLogs (bool allow_walker_logs_) override
 
std::string getEngineName () override
 
template<class PDT >
void setValue (const std::string &aname, PDT x)
 
void setBranchEngine (std::unique_ptr< BranchEngineType > &&be) override
 set the BranchEngineType More...
 
std::unique_ptr< BranchEngineTypegetBranchEngine () override
 return BranchEngineType* More...
 
int addObservable (const std::string &aname)
 
RealType getObservable (int i)
 
void setTau (RealType i)
 
void setWalkerOffsets ()
 set global offsets of the walkers More...
 
RefVector< RandomBase< FullPrecRealType > > getRngRefs () const
 return the random generators More...
 
RandomBase< FullPrecRealType > & getRng (int i) override
 return the i-th random generator More...
 
unsigned long getDriverMode () override
 
- Public Member Functions inherited from QMCDriverInterface
virtual ~QMCDriverInterface ()
 
virtual void setBranchEngine (std::unique_ptr< BranchEngineType > &&be)
 
- Public Member Functions inherited from MPIObjectBase
 MPIObjectBase (Communicate *c)
 constructor with communicator More...
 
int rank () const
 return the rank of the communicator More...
 
int getGroupID () const
 return the group id of the communicator More...
 
CommunicategetCommunicator () const
 return myComm More...
 
CommunicategetCommRef () const
 return a TEMPORARY reference to Communicate More...
 
mpi_comm_type getMPI () const
 return MPI communicator if one wants to use MPI directly More...
 
bool is_manager () const
 return true if the rank == 0 More...
 
const std::string & getName () const
 return the name More...
 
void setName (const std::string &aname)
 
- Public Member Functions inherited from LinearMethod
Real getLowestEigenvector (Matrix< Real > &A, std::vector< Real > &ev) const
 
Real getNonLinearRescale (std::vector< Real > &dP, Matrix< Real > &S, const QMCCostFunctionBase &optTarget) const
 

Private Member Functions

bool ValidCostFunction (bool valid)
 
bool is_best_cost (const int ii, const std::vector< RealType > &cv, const std::vector< double > &sh, const RealType ic) const
 
bool adaptive_three_shift_run ()
 
bool one_shift_run ()
 
bool descent_run ()
 
bool test_run ()
 
void solveShiftsWithoutLMYEngine (const std::vector< double > &shifts_i, const std::vector< double > &shiffts_s, std::vector< std::vector< RealType >> &parameterDirections)
 
std::vector< double > prepare_shifts (const double central_shift) const
 
void print_cost_summary_header ()
 
void print_cost_summary (const double si, const double ss, const RealType mc, const RealType cv, const int ind, const int bi, const bool gu)
 
void start ()
 common operation to start optimization, used by the derived classes More...
 
void finish ()
 common operation to finish optimization, used by the derived classes More...
 
void generateSamples ()
 

Private Attributes

std::unique_ptr< GradientTesttestEngineObj
 
std::unique_ptr< DescentEnginedescentEngineObj
 
std::unique_ptr< HybridEnginehybridEngineObj
 
int nstabilizers
 
RealType stabilizerScale
 
RealType bigChange
 
RealType exp0
 
RealType exp1
 
RealType stepsize
 
RealType savedQuadstep
 
std::string StabilizerMethod
 
RealType w_beta
 
int eigCG
 number of previous steps to orthogonalize to. More...
 
int TotalCGSteps
 total number of cg steps per iterations More...
 
RealType bestShift_i
 the previous best identity shift More...
 
RealType bestShift_s
 the previous best overlap shift More...
 
RealType shift_i_input
 current shift_i, shift_s input values More...
 
RealType shift_s_input
 
std::bitset< 2 > accept_history
 accept history, remember the last 2 iterations, value 00, 01, 10, 11 More...
 
RealType shift_s_base
 Shift_s adjustment base. More...
 
int num_shifts
 number of shifts we will try More...
 
RealType max_relative_cost_change
 the maximum relative change in the cost function for the adaptive three-shift scheme More...
 
RealType max_param_change
 max amount a parameter may change relative to current wave function weight More...
 
RealType cost_increase_tol
 the tolerance to cost function increases when choosing the best shift in the adaptive shift method More...
 
RealType target_shift_i
 the shift_i value that the adaptive shift method should aim for More...
 
std::string targetExcitedStr
 whether we are targeting an excited state More...
 
bool targetExcited
 whether we are targeting an excited state More...
 
std::string block_lmStr
 whether we are doing block algorithm More...
 
bool block_lm
 whether we are doing block algorithm More...
 
int nblocks
 number of blocks used in block algorithm More...
 
int nolds
 number of old updates kept More...
 
int nkept
 number of directions kept More...
 
int nsamp_comp
 number of samples to do in correlated sampling part More...
 
RealType omega_shift
 the shift to use when targeting an excited state More...
 
bool block_first
 whether to do the first part of block lm More...
 
bool block_second
 whether to do the second part of block lm More...
 
bool block_third
 whether to do the third part of block lm More...
 
std::string MinMethod
 
OptimizerType previous_optimizer_type_
 
OptimizerType current_optimizer_type_
 
bool doHybrid
 
bool doGradientTest
 
bool do_output_matrices_
 
bool output_matrices_initialized_
 
OutputMatrix output_hamiltonian_
 
OutputMatrix output_overlap_
 
bool freeze_parameters_
 
std::vector< RealTypeoptdir
 
std::vector< RealTypeoptparam
 
int NumOfVMCWalkers
 total number of VMC walkers More...
 
int Max_iterations
 Number of iterations maximum before generating new configurations. More...
 
std::unique_ptr< QMCCostFunctionBaseoptTarget
 target cost function to optimize More...
 
std::unique_ptr< QMCDrivervmcEngine
 vmc engine More...
 
xmlNodePtr wfNode
 xml node to be dumped More...
 
RealType param_tol
 
NewTimergenerate_samples_timer_
 
NewTimerinitialize_timer_
 
NewTimereigenvalue_timer_
 
NewTimerinvolvmat_timer_
 
NewTimerline_min_timer_
 
NewTimercost_function_timer_
 
Timer t1
 

Additional Inherited Members

- Public Types inherited from QMCDriver
enum  { QMC_UPDATE_MODE, QMC_MULTIPLE, QMC_OPTIMIZE, QMC_WARMUP }
 enumeration coupled with QMCMode More...
 
using Walker_t = MCWalkerConfiguration::Walker_t
 
using Buffer_t = Walker_t::Buffer_t
 
using FullPrecRealType = QMCTraits::FullPrecRealType
 
- Public Types inherited from QMCDriverInterface
using BranchEngineType = SimpleFixedNodeBranch
 
using FullPrecRealType = QMCTraits::FullPrecRealType
 
- Public Types inherited from QMCTraits
enum  { DIM = OHMMS_DIM, DIM_VGL = OHMMS_DIM + 2 }
 
using QTBase = QMCTypes< OHMMS_PRECISION, DIM >
 
using QTFull = QMCTypes< OHMMS_PRECISION_FULL, DIM >
 
using RealType = QTBase::RealType
 
using ComplexType = QTBase::ComplexType
 
using ValueType = QTBase::ValueType
 
using PosType = QTBase::PosType
 
using GradType = QTBase::GradType
 
using TensorType = QTBase::TensorType
 
using IndexType = OHMMS_INDEXTYPE
 define other types More...
 
using FullPrecRealType = QTFull::RealType
 
using FullPrecValueType = QTFull::ValueType
 
using PropertySetType = RecordNamedProperty< FullPrecRealType >
 define PropertyList_t More...
 
using PtclGrpIndexes = std::vector< std::pair< int, int > >
 
- Public Types inherited from MPIObjectBase
using mpi_comm_type = Communicate::mpi_comm_type
 
- Static Public Member Functions inherited from LinearMethod
static Real selectEigenvalue (std::vector< Real > &eigenvals, Matrix< Real > &eigenvectors, Real zerozero, std::vector< Real > &ev)
 Select eigenvalue and return corresponding scaled eigenvector. More...
 
static Real getLowestEigenvector_Inv (Matrix< Real > &A, Matrix< Real > &B, std::vector< Real > &ev)
 Solve the generalized eigenvalue problem and return a scaled eigenvector corresponding to the selected eigenvalue. More...
 
static Real getLowestEigenvector_Gen (Matrix< Real > &A, Matrix< Real > &B, std::vector< Real > &ev)
 Solve the generalized eigenvalue problem and return a scaled eigenvector corresponding to the selected eigenvalue. More...
 
- Public Attributes inherited from QMCDriver
std::bitset< QMC_MODE_MAXqmc_driver_mode
 bits to classify QMCDriver More...
 
bool allow_traces
 whether to allow traces More...
 
xmlNodePtr traces_xml
 traces xml More...
 
bool allow_walker_logs
 whether to allow traces More...
 
xmlNodePtr walker_logs_xml
 traces xml More...
 
EstimatorManagerBaseEstimators
 Observables manager. More...
 
std::unique_ptr< TraceManagerTraces
 Traces manager. More...
 
std::unique_ptr< WalkerLogManagerwlog_manager_
 Traces manager. More...
 
- Protected Member Functions inherited from QMCDriver
bool putQMCInfo (xmlNodePtr cur)
 Parses the xml input file for parameter definitions for a single qmc simulation. More...
 
void addWalkers (int nwalkers)
 Add walkers to the end of the ensemble of walkers. More...
 
void recordBlock (int block) override
 record the state of the block More...
 
bool finalize (int block, bool dumpwalkers=true)
 finalize a qmc section More...
 
std::string getRotationName (std::string RootName)
 
std::string getLastRotationName (std::string RootName)
 
const std::string & get_root_name () const override
 
- Protected Attributes inherited from QMCDriver
const ProjectDataproject_data_
 top-level project data information More...
 
std::unique_ptr< BranchEngineTypebranchEngine
 branch engine More...
 
DriftModifierBaseDriftModifier
 drift modifer More...
 
bool ResetRandom
 randomize it More...
 
bool AppendRun
 flag to append or restart the run More...
 
bool DumpConfig
 flag to turn off dumping configurations More...
 
bool IsQMCDriver
 true, if it is a real QMC engine More...
 
int MyCounter
 the number of times this QMCDriver is executed More...
 
int kDelay
 the number to delay updates by More...
 
int Period4CheckPoint
 period of dumping walker configurations and everything else for restart More...
 
int Period4CheckProperties
 period of dumping walker positions and IDs for Forward Walking More...
 
int Period4WalkerDump
 period of recording walker configurations More...
 
int Period4ConfigDump
 period of recording walker positions and IDs for forward walking afterwards More...
 
IndexType CurrentStep
 current step More...
 
IndexType nBlocks
 maximum number of blocks More...
 
IndexType nSteps
 maximum number of steps More...
 
IndexType nSubSteps
 number of steps between a step: VMCs do not evaluate energies More...
 
IndexType nWarmupSteps
 number of warmup steps More...
 
IndexType nAccept
 counter for number of moves accepted More...
 
IndexType nReject
 counter for number of moves /rejected More...
 
IndexType nBlocksBetweenRecompute
 the number of blocks between recomptePsi More...
 
IndexType nTargetWalkers
 the number of walkers More...
 
IndexType nTargetSamples
 the number of saved samples More...
 
IndexType nStepsBetweenSamples
 alternate method of setting QMC run parameters More...
 
RealType nSamplesPerThread
 samples per thread More...
 
RealType nTargetPopulation
 target population More...
 
RealType Tau
 timestep More...
 
int MaxCPUSecs
 maximum cpu in secs More...
 
RealType m_oneover2tau
 Time-step factor $ 1/(2\tau)$. More...
 
RealType m_sqrttau
 Time-step factor $ \sqrt{\tau}$. More...
 
xmlNodePtr qmcNode
 pointer to qmc node in xml file More...
 
const std::string QMCType
 type of QMC driver More...
 
std::string h5FileRoot
 the root of h5File More...
 
std::string RootName
 root of all the output files More...
 
ParameterSet m_param
 store any parameter that has to be read from a file More...
 
MCWalkerConfigurationW
 walker ensemble More...
 
TrialWaveFunctionPsi
 trial function More...
 
QMCHamiltonianH
 Hamiltonian. More...
 
std::unique_ptr< HDFWalkerOutputwOut
 record engine for walkers More...
 
std::vector< TrialWaveFunction * > Psi1
 a list of TrialWaveFunctions for multiple method More...
 
std::vector< QMCHamiltonian * > H1
 a list of QMCHamiltonians for multiple method More...
 
UPtrVector< RandomBase< FullPrecRealType > > Rng
 Random number generators. More...
 
std::vector< xmlNodePtr > mcwalkerNodePtr
 a list of mcwalkerset element More...
 
ParticleSet::ParticlePos drift
 temporary storage for drift More...
 
ParticleSet::ParticlePos deltaR
 temporary storage for random displacement More...
 
RealType SpinMass
 spin mass for spinor calcs More...
 
int rotation
 
- Protected Attributes inherited from MPIObjectBase
CommunicatemyComm
 pointer to Communicate More...
 
std::string ClassName
 class Name More...
 
std::string myName
 name of the object More...
 

Constructor & Destructor Documentation

◆ QMCFixedSampleLinearOptimize()

QMCFixedSampleLinearOptimize ( const ProjectData project_data,
MCWalkerConfiguration w,
TrialWaveFunction psi,
QMCHamiltonian h,
Communicate comm 
)

Constructor.

Definition at line 48 of file QMCFixedSampleLinearOptimize.cpp.

References ParameterSet::add(), qmcplusplus::app_log(), QMCFixedSampleLinearOptimize::bigChange, QMCFixedSampleLinearOptimize::block_lmStr, QMCFixedSampleLinearOptimize::cost_increase_tol, QMCFixedSampleLinearOptimize::exp0, QMCDriver::IsQMCDriver, QMCDriver::m_param, QMCFixedSampleLinearOptimize::Max_iterations, QMCFixedSampleLinearOptimize::max_param_change, QMCFixedSampleLinearOptimize::max_relative_cost_change, QMCFixedSampleLinearOptimize::MinMethod, QMCFixedSampleLinearOptimize::nblocks, QMCFixedSampleLinearOptimize::nkept, QMCFixedSampleLinearOptimize::nolds, NONE, QMCFixedSampleLinearOptimize::nsamp_comp, QMCFixedSampleLinearOptimize::nstabilizers, QMCFixedSampleLinearOptimize::num_shifts, QMCFixedSampleLinearOptimize::omega_shift, QMCFixedSampleLinearOptimize::param_tol, QMCDriver::qmc_driver_mode, QMCDriver::QMC_OPTIMIZE, QMCDriver::RootName, QMCFixedSampleLinearOptimize::shift_i_input, QMCFixedSampleLinearOptimize::shift_s_input, QMCFixedSampleLinearOptimize::stabilizerScale, QMCFixedSampleLinearOptimize::target_shift_i, and QMCFixedSampleLinearOptimize::targetExcitedStr.

53  : QMCDriver(project_data, w, psi, h, comm, "QMCFixedSampleLinearOptimize"),
54 #ifdef HAVE_LMY_ENGINE
55  vdeps(1, std::vector<double>()),
56 #endif
57  nstabilizers(3),
58  stabilizerScale(2.0),
59  bigChange(50),
60  exp0(-16),
61  stepsize(0.25),
62  StabilizerMethod("best"),
63  bestShift_i(-1.0),
64  bestShift_s(-1.0),
65  shift_i_input(0.01),
66  shift_s_input(1.00),
67  accept_history(3),
68  shift_s_base(4.0),
69  num_shifts(3),
71  max_param_change(0.3),
72  cost_increase_tol(0.0),
73  target_shift_i(-1.0),
74  targetExcitedStr("no"),
75  targetExcited(false),
76  block_lmStr("no"),
77  block_lm(false),
78  nblocks(1),
79  nolds(1),
80  nkept(1),
81  nsamp_comp(0),
82  omega_shift(0.0),
83  block_first(true),
84  block_second(false),
85  block_third(false),
86  MinMethod("OneShiftOnly"),
89  do_output_matrices_(false),
91  freeze_parameters_(false),
92  Max_iterations(1),
93  wfNode(NULL),
94  param_tol(1e-4),
95  generate_samples_timer_(createGlobalTimer("QMCLinearOptimize::generateSamples", timer_level_medium)),
96  initialize_timer_(createGlobalTimer("QMCLinearOptimize::Initialize", timer_level_medium)),
97  eigenvalue_timer_(createGlobalTimer("QMCLinearOptimize::EigenvalueSolve", timer_level_medium)),
98  involvmat_timer_(createGlobalTimer("QMCLinearOptimize::invertOverlapMat", timer_level_medium)),
99  line_min_timer_(createGlobalTimer("QMCLinearOptimize::Line_Minimization", timer_level_medium)),
100  cost_function_timer_(createGlobalTimer("QMCLinearOptimize::CostFunction", timer_level_medium))
101 {
102  IsQMCDriver = false;
103  //set the optimization flag
105  //read to use vmc output (just in case)
106  RootName = "pot";
107  m_param.add(Max_iterations, "max_its");
108  m_param.add(nstabilizers, "nstabilizers");
109  m_param.add(stabilizerScale, "stabilizerscale");
110  m_param.add(bigChange, "bigchange");
111  m_param.add(MinMethod, "MinMethod");
112  m_param.add(exp0, "exp0");
113  m_param.add(targetExcitedStr, "targetExcited");
114  m_param.add(block_lmStr, "block_lm");
115  m_param.add(nblocks, "nblocks");
116  m_param.add(nolds, "nolds");
117  m_param.add(nkept, "nkept");
118  m_param.add(nsamp_comp, "nsamp_comp");
119  m_param.add(omega_shift, "omega");
120  m_param.add(max_relative_cost_change, "max_relative_cost_change");
121  m_param.add(max_param_change, "max_param_change");
122  m_param.add(shift_i_input, "shift_i");
123  m_param.add(shift_s_input, "shift_s");
124  m_param.add(num_shifts, "num_shifts");
125  m_param.add(cost_increase_tol, "cost_increase_tol");
126  m_param.add(target_shift_i, "target_shift_i");
127  m_param.add(param_tol, "alloweddifference");
128 
129 #ifdef HAVE_LMY_ENGINE
130  //app_log() << "construct QMCFixedSampleLinearOptimize" << endl;
131  std::vector<double> shift_scales(3, 1.0);
132  EngineObj = new cqmc::engine::LMYEngine<ValueType>(&vdeps,
133  false, // exact sampling
134  true, // ground state?
135  false, // variance correct,
136  true,
137  true, // print matrices,
138  true, // build matrices
139  false, // spam
140  false, // use var deps?
141  true, // chase lowest
142  false, // chase closest
143  false, // eom
144  false,
145  false, // eom related
146  false, // eom related
147  false, // use block?
148  120000, // number of samples
149  0, // number of parameters
150  60, // max krylov iter
151  0, // max spam inner iter
152  1, // spam appro degree
153  0, // eom related
154  0, // eom related
155  0, // eom related
156  0.0, // omega
157  0.0, // var weight
158  1.0e-6, // convergence threshold
159  0.99, // minimum S singular val
160  0.0, 0.0,
161  10.0, // max change allowed
162  1.00, // identity shift
163  1.00, // overlap shift
164  0.3, // max parameter change
165  shift_scales, app_log());
166 #endif
167 
168 
169  // stale parameters
170  // m_param.add(eigCG,"eigcg");
171  // m_param.add(TotalCGSteps,"cgsteps");
172  // m_param.add(w_beta,"beta");
173  // quadstep=-1.0;
174  // m_param.add(quadstep,"quadstep");
175  // m_param.add(stepsize,"stepsize");
176  // m_param.add(exp1,"exp1");
177  // m_param.add(StabilizerMethod,"StabilizerMethod");
178  // m_param.add(LambdaMax,"LambdaMax");
179  //Set parameters for line minimization:
180 }
bool targetExcited
whether we are targeting an excited state
bool block_first
whether to do the first part of block lm
std::bitset< 2 > accept_history
accept history, remember the last 2 iterations, value 00, 01, 10, 11
RealType max_param_change
max amount a parameter may change relative to current wave function weight
bool block_lm
whether we are doing block algorithm
QMCDriver(const ProjectData &project_data, MCWalkerConfiguration &w, TrialWaveFunction &psi, QMCHamiltonian &h, Communicate *comm, const std::string &QMC_driver_type, bool enable_profiling=false)
Constructor.
Definition: QMCDriver.cpp:44
std::string RootName
root of all the output files
Definition: QMCDriver.h:317
std::ostream & app_log()
Definition: OutputManager.h:65
RealType max_relative_cost_change
the maximum relative change in the cost function for the adaptive three-shift scheme ...
bool block_second
whether to do the second part of block lm
int nsamp_comp
number of samples to do in correlated sampling part
std::string block_lmStr
whether we are doing block algorithm
RealType bestShift_i
the previous best identity shift
bool block_third
whether to do the third part of block lm
ParameterSet m_param
store any parameter that has to be read from a file
Definition: QMCDriver.h:320
RealType shift_i_input
current shift_i, shift_s input values
std::bitset< QMC_MODE_MAX > qmc_driver_mode
bits to classify QMCDriver
Definition: QMCDriver.h:93
NewTimer & createGlobalTimer(const std::string &myname, timer_levels mylevel)
bool IsQMCDriver
true, if it is a real QMC engine
Definition: QMCDriver.h:228
void add(PDT &aparam, const std::string &aname_in, std::vector< PDT > candidate_values={}, TagStatus status=TagStatus::OPTIONAL)
add a new parameter corresponding to an xmlNode <parameter>
RealType omega_shift
the shift to use when targeting an excited state
RealType cost_increase_tol
the tolerance to cost function increases when choosing the best shift in the adaptive shift method ...
std::string targetExcitedStr
whether we are targeting an excited state
int nblocks
number of blocks used in block algorithm
RealType target_shift_i
the shift_i value that the adaptive shift method should aim for
int Max_iterations
Number of iterations maximum before generating new configurations.
RealType bestShift_s
the previous best overlap shift

◆ ~QMCFixedSampleLinearOptimize()

Destructor.

Clean up the vector.

Definition at line 183 of file QMCFixedSampleLinearOptimize.cpp.

184 {
185 #ifdef HAVE_LMY_ENGINE
186  delete EngineObj;
187 #endif
188 }

Member Function Documentation

◆ adaptive_three_shift_run()

bool adaptive_three_shift_run ( )
private

◆ descent_run()

bool descent_run ( )
private

◆ finish()

void finish ( )
private

common operation to finish optimization, used by the derived classes

Definition at line 1582 of file QMCFixedSampleLinearOptimize.cpp.

References qmcplusplus::app_log(), MCWalkerConfiguration::createWalkers(), WalkerConfigurations::destroyWalkers(), Timer::elapsed(), WalkerConfigurations::getActiveWalkers(), QMCDriver::MyCounter, QMCFixedSampleLinearOptimize::NumOfVMCWalkers, QMCFixedSampleLinearOptimize::optTarget, QMCFixedSampleLinearOptimize::t1, and QMCDriver::W.

Referenced by QMCFixedSampleLinearOptimize::run(), and QMCFixedSampleLinearOptimize::test_run().

1583 {
1584  MyCounter++;
1585  app_log() << " Execution time = " << std::setprecision(4) << t1.elapsed() << std::endl;
1586  app_log() << " </log>" << std::endl;
1587 
1588  if (optTarget->reportH5)
1589  optTarget->reportParametersH5();
1590  optTarget->reportParameters();
1591 
1592 
1593  int nw_removed = W.getActiveWalkers() - NumOfVMCWalkers;
1594  app_log() << " Restore the number of walkers to " << NumOfVMCWalkers << ", removing " << nw_removed << " walkers."
1595  << std::endl;
1596  if (nw_removed > 0)
1597  W.destroyWalkers(nw_removed);
1598  else
1599  W.createWalkers(-nw_removed);
1600  app_log() << "</opt>" << std::endl;
1601  app_log() << "</optimization-report>" << std::endl;
1602 }
double elapsed() const
Definition: Timer.h:30
size_t getActiveWalkers() const
return the number of active walkers
std::unique_ptr< QMCCostFunctionBase > optTarget
target cost function to optimize
std::ostream & app_log()
Definition: OutputManager.h:65
iterator destroyWalkers(iterator first, iterator last)
destroy Walkers from itstart to itend
MCWalkerConfiguration & W
walker ensemble
Definition: QMCDriver.h:323
void createWalkers(int numWalkers)
create numWalkers Walkers
int MyCounter
the number of times this QMCDriver is executed
Definition: QMCDriver.h:235

◆ Func()

Definition at line 190 of file QMCFixedSampleLinearOptimize.cpp.

References QMCFixedSampleLinearOptimize::optdir, QMCFixedSampleLinearOptimize::optparam, and QMCFixedSampleLinearOptimize::optTarget.

191 {
192  for (int i = 0; i < optparam.size(); i++)
193  optTarget->Params(i) = optparam[i] + dl * optdir[i];
194  RealType c = optTarget->Cost(false);
195  //only allow this to go false if it was true. If false, stay false
196  // if (validFuncVal)
197  validFuncVal = optTarget->IsValid;
198  return c;
199 }
std::unique_ptr< QMCCostFunctionBase > optTarget
target cost function to optimize
QMCTraits::RealType RealType

◆ generateSamples()

void generateSamples ( )
private

Definition at line 1604 of file QMCFixedSampleLinearOptimize.cpp.

References qmcplusplus::app_log(), QMCDriver::branchEngine, Timer::elapsed(), QMCDriver::h5FileRoot, QMCDriver::nBlocks, QMCDriver::QMC_OPTIMIZE, QMCDriver::QMC_WARMUP, Timer::restart(), QMCDriver::RootName, QMCFixedSampleLinearOptimize::t1, and QMCFixedSampleLinearOptimize::vmcEngine.

1605 {
1606  app_log() << "<optimization-report>" << std::endl;
1607  vmcEngine->qmc_driver_mode.set(QMC_WARMUP, 1);
1608  // vmcEngine->run();
1609  // vmcEngine->setValue("blocks",nBlocks);
1610  // app_log() << " Execution time = " << std::setprecision(4) << t1.elapsed() << std::endl;
1611  // app_log() << "</vmc>" << std::endl;
1612  //}
1613  // if (W.getActiveWalkers()>NumOfVMCWalkers)
1614  // {
1615  // W.destroyWalkers(W.getActiveWalkers()-NumOfVMCWalkers);
1616  // app_log() << " QMCFixedSampleLinearOptimize::generateSamples removed walkers." << std::endl;
1617  // app_log() << " Number of Walkers per node " << W.getActiveWalkers() << std::endl;
1618  // }
1619  vmcEngine->qmc_driver_mode.set(QMC_OPTIMIZE, 1);
1620  vmcEngine->qmc_driver_mode.set(QMC_WARMUP, 0);
1621  //vmcEngine->setValue("recordWalkers",1);//set record
1622  vmcEngine->setValue("current", 0); //reset CurrentStep
1623  app_log() << R"(<vmc stage="main" blocks=")" << nBlocks << "\">" << std::endl;
1624  t1.restart();
1625  // W.reset();
1626  branchEngine->flush(0);
1627  branchEngine->reset();
1628  vmcEngine->run();
1629  app_log() << " Execution time = " << std::setprecision(4) << t1.elapsed() << std::endl;
1630  app_log() << "</vmc>" << std::endl;
1631  h5FileRoot = RootName;
1632 }
std::unique_ptr< QMCDriver > vmcEngine
vmc engine
std::string h5FileRoot
the root of h5File
Definition: QMCDriver.h:315
double elapsed() const
Definition: Timer.h:30
void restart()
Definition: Timer.h:29
std::string RootName
root of all the output files
Definition: QMCDriver.h:317
std::ostream & app_log()
Definition: OutputManager.h:65
std::unique_ptr< BranchEngineType > branchEngine
branch engine
Definition: QMCDriver.h:218
IndexType nBlocks
maximum number of blocks
Definition: QMCDriver.h:266

◆ getRunType()

QMCRunType getRunType ( )
inlineoverridevirtual

◆ is_best_cost()

bool is_best_cost ( const int  ii,
const std::vector< RealType > &  cv,
const std::vector< double > &  sh,
const RealType  ic 
) const
private

◆ one_shift_run()

bool one_shift_run ( )
private

◆ prepare_shifts()

std::vector<double> prepare_shifts ( const double  central_shift) const
private

◆ print_cost_summary()

void print_cost_summary ( const double  si,
const double  ss,
const RealType  mc,
const RealType  cv,
const int  ind,
const int  bi,
const bool  gu 
)
private

◆ print_cost_summary_header()

void print_cost_summary_header ( )
private

◆ processOptXML()

bool processOptXML ( xmlNodePtr  cur,
const std::string &  vmcMove,
bool  reportH5 
)

process xml node value (parameters for both VMC and OPT) for the actual optimization

Definition at line 560 of file QMCFixedSampleLinearOptimize.cpp.

References qmcplusplus::ADAPTIVE, QMCDriver::addWalkers(), qmcplusplus::app_log(), QMCDriver::AppendRun, Communicate::barrier_and_abort(), QMCFixedSampleLinearOptimize::bestShift_i, QMCFixedSampleLinearOptimize::bestShift_s, QMCFixedSampleLinearOptimize::block_lm, QMCFixedSampleLinearOptimize::block_lmStr, RandomNumberControl::Children, OHMMS::Controller, QMCFixedSampleLinearOptimize::cost_increase_tol, QMCFixedSampleLinearOptimize::current_optimizer_type_, qmcplusplus::DESCENT, QMCFixedSampleLinearOptimize::descentEngineObj, QMCFixedSampleLinearOptimize::doHybrid, WalkerConfigurations::getActiveWalkers(), QMCDriver::H, QMCDriver::h5FileRoot, qmcplusplus::lowerCase(), QMCDriver::m_param, QMCFixedSampleLinearOptimize::max_param_change, QMCFixedSampleLinearOptimize::max_relative_cost_change, QMCDriver::mcwalkerNodePtr, QMCFixedSampleLinearOptimize::MinMethod, MPIObjectBase::myComm, QMCFixedSampleLinearOptimize::NumOfVMCWalkers, omp_get_max_threads(), qmcplusplus::ONESHIFTONLY, qmcplusplus::OptimizerNames, QMCFixedSampleLinearOptimize::optTarget, QMCFixedSampleLinearOptimize::previous_optimizer_type_, QMCDriver::project_data_, QMCDriver::Psi, ParameterSet::put(), Communicate::rank(), QMCDriver::RootName, QMCFixedSampleLinearOptimize::shift_i_input, QMCFixedSampleLinearOptimize::shift_s_input, QMCFixedSampleLinearOptimize::targetExcited, QMCFixedSampleLinearOptimize::targetExcitedStr, QMCFixedSampleLinearOptimize::vmcEngine, and QMCDriver::W.

Referenced by QMCFixedSampleLinearOptimize::put().

561 {
562  m_param.put(opt_xml);
564  targetExcited = (targetExcitedStr == "yes");
565 
567  block_lm = (block_lmStr == "yes");
568 
569  auto iter = OptimizerNames.find(MinMethod);
570  if (iter == OptimizerNames.end())
571  throw std::runtime_error("Unknown MinMethod!\n");
574 
576  {
577  if (!descentEngineObj)
578  {
579  descentEngineObj = std::make_unique<DescentEngine>(myComm, opt_xml);
580  }
581 
582  else
583  {
584  descentEngineObj->processXML(opt_xml);
585  }
586  }
587 
588 
589  // sanity check
592  myComm->barrier_and_abort(R"(targetExcited = "yes" requires that MinMethod = "adaptive or descent)");
593 
594 #ifdef _OPENMP
596  {
597  // throw std::runtime_error("OpenMP threading not enabled with AdaptiveThreeShift optimizer. Use MPI for parallelism instead, and set OMP_NUM_THREADS to 1.");
598  app_log() << "test version of OpenMP threading with AdaptiveThreeShift optimizer" << std::endl;
599  }
600 #endif
601 
602  // check parameter change sanity
603  if (max_param_change <= 0.0)
604  throw std::runtime_error("max_param_change must be positive in QMCFixedSampleLinearOptimize::put");
605 
606  // check cost change sanity
607  if (max_relative_cost_change <= 0.0)
608  throw std::runtime_error("max_relative_cost_change must be positive in QMCFixedSampleLinearOptimize::put");
609 
610  // check shift sanity
611  if (shift_i_input <= 0.0)
612  throw std::runtime_error("shift_i must be positive in QMCFixedSampleLinearOptimize::put");
613  if (shift_s_input <= 0.0)
614  throw std::runtime_error("shift_s must be positive in QMCFixedSampleLinearOptimize::put");
615 
616  // check cost increase tolerance sanity
617  if (cost_increase_tol < 0.0)
618  throw std::runtime_error("cost_increase_tol must be non-negative in QMCFixedSampleLinearOptimize::put");
619 
620  // if this is the first time this function has been called, set the initial shifts
625  if (bestShift_s < 0.0)
627 
628  xmlNodePtr qsave = opt_xml;
629  xmlNodePtr cur = qsave->children;
630  int pid = OHMMS::Controller->rank();
631  while (cur != NULL)
632  {
633  std::string cname((const char*)(cur->name));
634  if (cname == "mcwalkerset")
635  {
636  mcwalkerNodePtr.push_back(cur);
637  }
638  cur = cur->next;
639  }
640  // no walkers exist, add 10
641  if (W.getActiveWalkers() == 0)
644 
645  // Destroy old object to stop timer to correctly order timer with object lifetime scope
646  vmcEngine.reset(nullptr);
647  vmcEngine = std::make_unique<VMC>(project_data_, W, Psi, H, RandomNumberControl::Children, myComm, false);
648  vmcEngine->setUpdateMode(vmcMove[0] == 'p');
649 
650 
651  vmcEngine->setStatus(RootName, h5FileRoot, AppendRun);
652  vmcEngine->process(qsave);
653 
654  bool success = true;
655  //allways reset optTarget
656  optTarget = std::make_unique<QMCCostFunction>(W, Psi, H, myComm);
657  optTarget->setStream(&app_log());
658  if (reportH5)
659  optTarget->reportH5 = true;
660  success = optTarget->put(qsave);
661 
662  return success;
663 }
664 
665 ///////////////////////////////////////////////////////////////////////////////////////////////////
666 /// \brief returns a vector of three shift values centered around the provided shift.
667 ///
668 /// \param[in] central_shift the central shift
669 ///
670 ///////////////////////////////////////////////////////////////////////////////////////////////////
671 std::vector<double> QMCFixedSampleLinearOptimize::prepare_shifts(const double central_shift) const
672 {
673  std::vector<double> retval(num_shifts);
674 
675  // check to see whether the number of shifts is odd
676  if (num_shifts % 2 == 0)
677  throw std::runtime_error("number of shifts must be odd in QMCFixedSampleLinearOptimize::prepare_shifts");
678 
679  // decide the central shift index
680  int central_index = num_shifts / 2;
681 
682  for (int i = 0; i < num_shifts; i++)
683  {
684  if (i < central_index)
685  retval.at(i) = central_shift / (4.0 * (central_index - i));
686  else if (i > central_index)
687  retval.at(i) = central_shift * (4.0 * (i - central_index));
688  else if (i == central_index)
689  retval.at(i) = central_shift;
690  //retval.at(i) = central_shift
691  //retval.at(0) = central_shift * 4.0;
692  //retval.at(1) = central_shift;
693  //retval.at(2) = central_shift / 4.0;
694  }
695  return retval;
696 }
697 
698 ///////////////////////////////////////////////////////////////////////////////////////////////////
699 /// \brief prints a header for the summary of each shift's result
700 ///
701 ///////////////////////////////////////////////////////////////////////////////////////////////////
703 {
704  app_log() << " " << std::right << std::setw(12) << "shift_i";
705  app_log() << " " << std::right << std::setw(12) << "shift_s";
706  app_log() << " " << std::right << std::setw(20) << "max param change";
707  app_log() << " " << std::right << std::setw(20) << "cost function value";
708  app_log() << std::endl;
709  app_log() << " " << std::right << std::setw(12) << "------------";
710  app_log() << " " << std::right << std::setw(12) << "------------";
711  app_log() << " " << std::right << std::setw(20) << "--------------------";
712  app_log() << " " << std::right << std::setw(20) << "--------------------";
713  app_log() << std::endl;
714 }
715 
716 ///////////////////////////////////////////////////////////////////////////////////////////////////
717 /// \brief prints a summary of the computed cost for the given shift
718 ///
719 /// \param[in] si the identity shift
720 /// \param[in] ss the overlap shift
721 /// \param[in] mc the maximum parameter change
722 /// \param[in] cv the cost function value
723 /// \param[in] ind the shift index: -1 (for initial state), 0, 1, or 2
724 /// \param[in] bi index of the best shift
725 /// \param[in] gu flag telling whether it was a good update
726 ///
727 ///////////////////////////////////////////////////////////////////////////////////////////////////
729  const double ss,
730  const RealType mc,
731  const RealType cv,
732  const int ind,
733  const int bi,
734  const bool gu)
735 {
736  if (ind >= 0)
737  {
738  if (gu)
739  {
740  app_log() << " " << std::scientific << std::right << std::setw(12) << std::setprecision(4) << si;
741  app_log() << " " << std::scientific << std::right << std::setw(12) << std::setprecision(4) << ss;
742  app_log() << " " << std::scientific << std::right << std::setw(20) << std::setprecision(4) << mc;
743  app_log() << " " << std::fixed << std::right << std::setw(20) << std::setprecision(12) << cv;
744  //app_log() << " " << std::right << std::setw(12) << ( ind == 0 ? "big shift" : ( ind == 1 ? "medium shift" : "small shift" ) );
745  }
746  else
747  {
748  app_log() << " " << std::right << std::setw(12) << "N/A";
749  app_log() << " " << std::right << std::setw(12) << "N/A";
750  app_log() << " " << std::right << std::setw(20) << "N/A";
751  app_log() << " " << std::right << std::setw(20) << "N/A";
752  app_log() << " " << std::right << std::setw(12) << "bad update";
753  }
754  }
755  else
756  {
757  app_log() << " " << std::right << std::setw(12) << "N/A";
758  app_log() << " " << std::right << std::setw(12) << "N/A";
759  app_log() << " " << std::right << std::setw(20) << "N/A";
760  app_log() << " " << std::fixed << std::right << std::setw(20) << std::setprecision(12) << cv;
761  app_log() << " " << std::right << std::setw(12) << "initial";
762  }
763  if (ind == bi)
764  app_log() << " <--";
765  app_log() << std::endl;
766 }
767 
768 ///////////////////////////////////////////////////////////////////////////////////////////////////
769 /// \brief Returns whether the proposed new cost is the best compared to the others.
770 ///
771 /// \param[in] ii index of the proposed best cost
772 /// \param[in] cv vector of new costs
773 /// \param[in] sh vector of identity shifts (shift_i values)
774 /// \param[in] ic the initial cost
775 ///
776 ///////////////////////////////////////////////////////////////////////////////////////////////////
778  const std::vector<RealType>& cv,
779  const std::vector<double>& sh,
780  const RealType ic) const
781 {
782  //app_log() << "determining best cost with cost_increase_tol = " << cost_increase_tol << " and target_shift_i = " << target_shift_i << std::endl;
783 
784  // initialize return value
785  bool retval = true;
786 
787  //app_log() << "retval = " << retval << std::endl;
788 
789  // compare to other costs
790  for (int i = 0; i < cv.size(); i++)
791  {
792  // don't compare to yourself
793  if (i == ii)
794  continue;
795 
796  // we only worry about the other value if it is within the maximum relative change threshold and not too high
797  const bool other_is_valid = ((ic == 0.0 ? 0.0 : std::abs((cv.at(i) - ic) / ic)) < max_relative_cost_change &&
798  cv.at(i) < ic + cost_increase_tol);
799  if (other_is_valid)
800  {
801  // if we are using a target shift and the cost is not too much higher, then prefer this cost if its shift is closer to the target shift
802  if (target_shift_i > 0.0)
803  {
804  const bool closer_to_target = (std::abs(sh.at(ii) - target_shift_i) < std::abs(sh.at(i) - target_shift_i));
805  const bool cost_is_similar = (std::abs(cv.at(ii) - cv.at(i)) < cost_increase_tol);
806  const bool cost_is_much_lower = (!cost_is_similar && cv.at(ii) < cv.at(i) - cost_increase_tol);
807  if (cost_is_much_lower || (closer_to_target && cost_is_similar))
808  retval = (retval && true);
809  else
810  retval = false;
811 
812  // if we are not using a target shift, then prefer this cost if it is lower
813  }
814  else
815  {
816  retval = (retval && cv.at(ii) <= cv.at(i));
817  }
818  }
819 
820  //app_log() << "cv.at(ii) = " << std::fixed << std::right << std::setw(20) << std::setprecision(12) << cv.at(ii) << " <= "
821  // << "cv.at(i) = " << std::fixed << std::right << std::setw(20) << std::setprecision(12) << cv.at(i) << " ?" << std::endl;
822  //app_log() << "retval = " << retval << std::endl;
823  }
824 
825  // new cost can only be the best cost if it is less than (or not too much higher than) the initial cost
826  retval = (retval && cv.at(ii) < ic + cost_increase_tol);
827  //app_log() << "cv.at(ii) = " << std::fixed << std::right << std::setw(20) << std::setprecision(12) << cv.at(ii) << " <= "
828  // << "ic = " << std::fixed << std::right << std::setw(20) << std::setprecision(12) << ic << " ?" << std::endl;
829  //app_log() << "retval = " << retval << std::endl;
830 
831  // new cost is only best if it's relative change from the initial cost is not too large ( or if the initial cost is exactly zero )
832  retval = (retval && (ic == 0.0 ? 0.0 : std::abs((cv.at(ii) - ic) / ic)) < max_relative_cost_change);
833  //app_log() << "std::abs( ( cv.at(ii) - ic ) / ic ) = " << std::fixed << std::right << std::setw(20) << std::setprecision(12)
834  // << std::abs( ( cv.at(ii) - ic ) / ic ) << " <= " << this->max_relative_cost_change << " ? " << std::endl;
835  //app_log() << "retval = " << retval << std::endl;
836  //app_log() << std::endl;
837 
838  // return whether the proposed cost is actually the best
839  return retval;
840 }
841 
842 ///////////////////////////////////////////////////////////////////////////////////////////////////
843 /// \brief For each set of shifts, solves the linear method eigenproblem by building and
844 /// diagonalizing the matrices.
845 ///
846 /// \param[in] shfits_i vector of identity shifts
847 /// \param[in] shfits_s vector of overlap shifts
848 /// \param[out] parameterDirections on exit, the update directions for the different shifts
849 ///
850 ///////////////////////////////////////////////////////////////////////////////////////////////////
851 void QMCFixedSampleLinearOptimize::solveShiftsWithoutLMYEngine(const std::vector<double>& shifts_i,
852  const std::vector<double>& shifts_s,
853  std::vector<std::vector<RealType>>& parameterDirections)
854 {
855  // get number of shifts to solve
856  const int nshifts = shifts_i.size();
857 
858  // get number of optimizable parameters
859  size_t numParams = optTarget->getNumParams();
860 
861  // get dimension of the linear method matrices
862  size_t N = numParams + 1;
863 
864  // prepare vectors to hold the parameter updates
865  parameterDirections.resize(nshifts);
866  for (int i = 0; i < parameterDirections.size(); i++)
867  parameterDirections.at(i).assign(N, 0.0);
868 
869  // allocate the matrices we will need
870  Matrix<RealType> ovlMat(N, N);
871  ovlMat = 0.0;
872  Matrix<RealType> hamMat(N, N);
873  hamMat = 0.0;
874  Matrix<RealType> invMat(N, N);
875  invMat = 0.0;
876  Matrix<RealType> sftMat(N, N);
877  sftMat = 0.0;
878  Matrix<RealType> prdMat(N, N);
879  prdMat = 0.0;
880 
881  // build the overlap and hamiltonian matrices
882  optTarget->fillOverlapHamiltonianMatrices(hamMat, ovlMat);
883 
884  // Output Hamiltonian and Overlap matrices
886  {
887  output_overlap_.output(ovlMat);
888  output_hamiltonian_.output(hamMat);
889  }
890 
891  // compute the inverse of the overlap matrix
892  invMat.copy(ovlMat);
893  invert_matrix(invMat, false);
894 
895  // compute the update for each shift
896  for (int shift_index = 0; shift_index < nshifts; shift_index++)
897  {
898  // prepare to shift the hamiltonain matrix
899  sftMat.copy(hamMat);
900 
901  // apply the identity shift
902  for (int i = 1; i < N; i++)
903  sftMat(i, i) += shifts_i.at(shift_index);
904 
905  // apply the overlap shift
906  for (int i = 1; i < N; i++)
907  for (int j = 1; j < N; j++)
908  sftMat(i, j) += shifts_s.at(shift_index) * ovlMat(i, j);
909 
910  // multiply the shifted hamiltonian matrix by the inverse of the overlap matrix
911  qmcplusplus::MatrixOperators::product(invMat, sftMat, prdMat);
912 
913  // transpose the result (why?)
914  for (int i = 0; i < N; i++)
915  for (int j = i + 1; j < N; j++)
916  std::swap(prdMat(i, j), prdMat(j, i));
917 
918  // compute the lowest eigenvalue of the product matrix and the corresponding eigenvector
919  getLowestEigenvector(prdMat, parameterDirections.at(shift_index));
920 
921  // compute the scaling constant to apply to the update
922  Lambda = getNonLinearRescale(parameterDirections.at(shift_index), ovlMat, *optTarget);
923 
924  // scale the update by the scaling constant
925  for (int i = 0; i < numParams; i++)
926  parameterDirections.at(shift_index).at(i + 1) *= Lambda;
927  }
928 }
929 
930 ///////////////////////////////////////////////////////////////////////////////////////////////////
931 /// \brief Performs one iteration of the linear method using an adaptive scheme that tries three
932 /// different shift magnitudes and picks the best one.
933 /// The scheme is adaptive in that it saves the best shift to use as a starting point
934 /// in the next iteration.
935 /// Note that the best shift is chosen based on a different sample than that used to
936 /// construct the linear method matrices in order to avoid over-optimizing on a particular
937 /// sample.
938 ///
939 /// \return ???
940 ///
941 ///////////////////////////////////////////////////////////////////////////////////////////////////
942 #ifdef HAVE_LMY_ENGINE
944 {
945  // remember what the cost function grads flag was
946  const bool saved_grads_flag = optTarget->getneedGrads();
947 
948  // remember the initial number of samples
949  const int init_num_samp = optTarget->getNumSamples();
950 
951  // the index of central shift
952  const int central_index = num_shifts / 2;
953 
954  // get number of optimizable parameters
955  size_t numParams = optTarget->getNumParams();
956 
957  // prepare the shifts that we will try
958  const std::vector<double> shifts_i = prepare_shifts(bestShift_i);
959  const std::vector<double> shifts_s = prepare_shifts(bestShift_s);
960  std::vector<double> shift_scales(shifts_i.size(), 1.0);
961  for (int i = 0; i < shift_scales.size(); i++)
962  shift_scales.at(i) = shifts_i.at(i) / shift_i_input;
963 
964  // ensure the cost function is set to compute derivative vectors
965  optTarget->setneedGrads(true);
966 
967  // prepare previous updates
968  int count = 0;
969  while (block_lm && previous_update.size() < nolds)
970  {
971  previous_update.push_back(formic::ColVec<double>(numParams));
972  for (int i = 0; i < numParams; i++)
973  previous_update.at(count).at(i) = 2.0 * (formic::random_number<double>() - 0.5);
974  count++;
975  }
976 
977  if (!EngineObj->full_init())
978  {
979  // prepare a variable dependency object with no dependencies
980  formic::VarDeps real_vdeps(numParams, std::vector<double>());
981  vdeps = real_vdeps;
982  EngineObj->get_param(&vdeps,
983  false, // exact sampling
984  !targetExcited,
985  false, // variable deps use?
986  false, // eom
987  false, // ssquare
988  block_lm, 12000, numParams, omega_shift, max_relative_cost_change, shifts_i.at(central_index),
989  shifts_s.at(central_index), max_param_change, shift_scales);
990  }
991 
992  // update shift
993  EngineObj->shift_update(shift_scales);
994 
995  // turn on wavefunction update mode
996  EngineObj->turn_on_update();
997 
998  // initialize the engine if we do not use block lm or it's the first part of block lm
999  EngineObj->initialize(nblocks, 0, nkept, previous_update, false);
1000 
1001  // reset the engine
1002  EngineObj->reset();
1003 
1004  // generate samples and compute weights, local energies, and derivative vectors
1005  engine_start(EngineObj, *descentEngineObj, MinMethod);
1006 
1007  // get dimension of the linear method matrices
1008  size_t N = numParams + 1;
1009 
1010  // have the cost function prepare derivative vectors
1011  EngineObj->energy_target_compute();
1012  const RealType starting_cost = EngineObj->target_value();
1013  const RealType init_energy = EngineObj->energy_mean();
1014 
1015  // print out the initial energy
1016  app_log() << std::endl
1017  << "*************************************************************************************************"
1018  << std::endl
1019  << "Solving the linear method equations on the initial sample with initial energy" << std::setw(20)
1020  << std::setprecision(12) << init_energy << std::endl
1021  << "*************************************************************************************************"
1022  << std::endl
1023  << std::endl;
1024  //const Return_t starting_cost = this->optTarget->LMYEngineCost(true);
1025 
1026  // prepare wavefunction update which does nothing if we do not use block lm
1027  EngineObj->wfn_update_prep();
1028 
1029  if (block_lm)
1030  {
1031  optTarget->setneedGrads(true);
1032 
1033  int numOptParams = optTarget->getNumParams();
1034 
1035  // reset the engine object
1036  EngineObj->reset();
1037 
1038  // finish last sample
1039  finish();
1040 
1041  // take sample
1042  engine_start(EngineObj, *descentEngineObj, MinMethod);
1043  }
1044 
1045  // say what we are doing
1046  app_log() << std::endl
1047  << "*********************************************************" << std::endl
1048  << "Solving the linear method equations on the initial sample" << std::endl
1049  << "*********************************************************" << std::endl
1050  << std::endl;
1051 
1052  // for each set of shifts, solve the linear method equations for the parameter update direction
1053  std::vector<std::vector<RealType>> parameterDirections;
1054 #ifdef HAVE_LMY_ENGINE
1055  // call the engine to perform update
1056  EngineObj->wfn_update_compute();
1057 #else
1058  solveShiftsWithoutLMYEngine(shifts_i, shifts_s, parameterDirections);
1059 #endif
1060 
1061  // size update direction vector correctly
1062  parameterDirections.resize(shifts_i.size());
1063  for (int i = 0; i < shifts_i.size(); i++)
1064  {
1065  parameterDirections.at(i).assign(N, 0.0);
1066  if (true)
1067  {
1068  for (int j = 0; j < N; j++)
1069  parameterDirections.at(i).at(j) = std::real(EngineObj->wfn_update().at(i * N + j));
1070  }
1071  else
1072  parameterDirections.at(i).at(0) = 1.0;
1073  }
1074 
1075  // now that we are done with them, prevent further computation of derivative vectors
1076  optTarget->setneedGrads(false);
1077 
1078  // prepare vectors to hold the initial and current parameters
1079  std::vector<RealType> currParams(numParams, 0.0);
1080 
1081  // initialize the initial and current parameter vectors
1082  for (int i = 0; i < numParams; i++)
1083  currParams.at(i) = optTarget->Params(i);
1084 
1085  // create a vector telling which updates are within our constraints
1086  std::vector<bool> good_update(parameterDirections.size(), true);
1087 
1088  // compute the largest parameter change for each shift, and zero out updates that have too-large changes
1089  std::vector<RealType> max_change(parameterDirections.size(), 0.0);
1090  for (int k = 0; k < parameterDirections.size(); k++)
1091  {
1092  for (int i = 0; i < numParams; i++)
1093  max_change.at(k) =
1094  std::max(max_change.at(k), std::abs(parameterDirections.at(k).at(i + 1) / parameterDirections.at(k).at(0)));
1095  good_update.at(k) = (good_update.at(k) && max_change.at(k) <= max_param_change);
1096  }
1097 
1098  // prepare to use the middle shift's update as the guiding function for a new sample
1099  for (int i = 0; i < numParams; i++)
1100  optTarget->Params(i) = currParams.at(i) + parameterDirections.at(central_index).at(i + 1);
1101 
1102  // say what we are doing
1103  app_log() << std::endl
1104  << "************************************************************" << std::endl
1105  << "Updating the guiding function with the middle shift's update" << std::endl
1106  << "************************************************************" << std::endl
1107  << std::endl;
1108 
1109  // generate the new sample on which we will compare the different shifts
1110 
1111  finish();
1112  app_log() << std::endl
1113  << "*************************************************************" << std::endl
1114  << "Generating a new sample based on the updated guiding function" << std::endl
1115  << "*************************************************************" << std::endl
1116  << std::endl;
1117 
1118  std::string old_name = vmcEngine->getCommunicator()->getName();
1119  vmcEngine->getCommunicator()->setName(old_name + ".middleShift");
1120  start();
1121  vmcEngine->getCommunicator()->setName(old_name);
1122 
1123  // say what we are doing
1124  app_log() << std::endl
1125  << "******************************************************************" << std::endl
1126  << "Comparing different shifts' cost function values on updated sample" << std::endl
1127  << "******************************************************************" << std::endl
1128  << std::endl;
1129 
1130  // update the current parameters to those of the new guiding function
1131  for (int i = 0; i < numParams; i++)
1132  currParams.at(i) = optTarget->Params(i);
1133 
1134  // compute cost function for the initial parameters (by subtracting the middle shift's update back off)
1135  for (int i = 0; i < numParams; i++)
1136  optTarget->Params(i) = currParams.at(i) - parameterDirections.at(central_index).at(i + 1);
1137  optTarget->IsValid = true;
1138  const RealType initCost = optTarget->LMYEngineCost(false, EngineObj);
1139 
1140  // compute the update directions for the smaller and larger shifts relative to that of the middle shift
1141  for (int i = 0; i < numParams; i++)
1142  {
1143  for (int j = 0; j < parameterDirections.size(); j++)
1144  {
1145  if (j != central_index)
1146  parameterDirections.at(j).at(i + 1) -= parameterDirections.at(central_index).at(i + 1);
1147  }
1148  }
1149 
1150  // prepare a vector to hold the cost function value for each different shift
1151  std::vector<RealType> costValues(num_shifts, 0.0);
1152 
1153  // compute the cost function value for each shift and make sure the change is within our constraints
1154  for (int k = 0; k < parameterDirections.size(); k++)
1155  {
1156  for (int i = 0; i < numParams; i++)
1157  optTarget->Params(i) = currParams.at(i) + (k == central_index ? 0.0 : parameterDirections.at(k).at(i + 1));
1158  optTarget->IsValid = true;
1159  costValues.at(k) = optTarget->LMYEngineCost(false, EngineObj);
1160  good_update.at(k) =
1161  (good_update.at(k) && std::abs((initCost - costValues.at(k)) / initCost) < max_relative_cost_change);
1162  if (!good_update.at(k))
1163  costValues.at(k) = std::abs(1.5 * initCost) + 1.0;
1164  }
1165 
1166  // find the best shift and the corresponding update direction
1167  const std::vector<RealType>* bestDirection = 0;
1168  int best_shift = -1;
1169  for (int k = 0; k < costValues.size() && std::abs((initCost - initCost) / initCost) < max_relative_cost_change; k++)
1170  if (is_best_cost(k, costValues, shifts_i, initCost) && good_update.at(k))
1171  {
1172  best_shift = k;
1173  bestDirection = &parameterDirections.at(k);
1174  }
1175 
1176  // print the results for each shift
1177  app_log() << std::endl;
1179  print_cost_summary(0.0, 0.0, 0.0, initCost, -1, best_shift, true);
1180  for (int k = 0; k < good_update.size(); k++)
1181  print_cost_summary(shifts_i.at(k), shifts_s.at(k), max_change.at(k), costValues.at(k), k, best_shift,
1182  good_update.at(k));
1183 
1184  // if any of the shifts produced a good update, apply the best such update and remember those shifts for next time
1185  if (bestDirection)
1186  {
1187  bestShift_i = shifts_i.at(best_shift);
1188  bestShift_s = shifts_s.at(best_shift);
1189  for (int i = 0; i < numParams; i++)
1190  optTarget->Params(i) = currParams.at(i) + (best_shift == central_index ? 0.0 : bestDirection->at(i + 1));
1191  app_log() << std::endl
1192  << "*****************************************************************************" << std::endl
1193  << "Applying the update for shift_i = " << std::scientific << std::right << std::setw(12)
1194  << std::setprecision(4) << bestShift_i << " and shift_s = " << std::scientific << std::right
1195  << std::setw(12) << std::setprecision(4) << bestShift_s << std::endl
1196  << "*****************************************************************************" << std::endl
1197  << std::endl;
1198 
1199  // otherwise revert to the old parameters and set the next shift to be larger
1200  }
1201  else
1202  {
1203  bestShift_i *= 10.0;
1204  bestShift_s *= 10.0;
1205  for (int i = 0; i < numParams; i++)
1206  optTarget->Params(i) = currParams.at(i) - parameterDirections.at(central_index).at(i + 1);
1207  app_log() << std::endl
1208  << "***********************************************************" << std::endl
1209  << "Reverting to old parameters and increasing shift magnitudes" << std::endl
1210  << "***********************************************************" << std::endl
1211  << std::endl;
1212  }
1213 
1214  // save the update for future linear method iterations
1215  if (block_lm && bestDirection)
1216  {
1217  // save the difference between the updated and old variables
1218  formic::ColVec<RealType> update_dirs(numParams, 0.0);
1219  for (int i = 0; i < numParams; i++)
1220  // take the real part since blocked LM currently does not support complex parameter optimization
1221  update_dirs.at(i) = std::real(bestDirection->at(i + 1) + parameterDirections.at(central_index).at(i + 1));
1222  previous_update.insert(previous_update.begin(), update_dirs);
1223 
1224  // eliminate the oldest saved update if necessary
1225  while (previous_update.size() > nolds)
1226  previous_update.pop_back();
1227  }
1228 
1229  // return the cost function grads flag to what it was
1230  optTarget->setneedGrads(saved_grads_flag);
1231 
1232  // perform some finishing touches for this linear method iteration
1233  finish();
1234 
1235  // set the number samples to be initial one
1236  optTarget->setNumSamples(init_num_samp);
1237  nTargetSamples = init_num_samp;
1238 
1239  //app_log() << "block first second third end " << block_first << block_second << block_third << endl;
1240  // return whether the cost function's report counter is positive
1241  return (optTarget->getReportCounter() > 0);
1242 }
1243 #endif
1244 
1246 {
1247  // ensure the cost function is set to compute derivative vectors
1248  optTarget->setneedGrads(true);
1249 
1250  // generate samples and compute weights, local energies, and derivative vectors
1251  start();
1252 
1253  // get number of optimizable parameters
1254  size_t numParams = optTarget->getNumParams();
1255 
1256  // get dimension of the linear method matrices
1257  size_t N = numParams + 1;
1258 
1259  // prepare vectors to hold the initial and current parameters
1260  std::vector<RealType> currentParameters(numParams, 0.0);
1261 
1262  // initialize the initial and current parameter vectors
1263  for (int i = 0; i < numParams; i++)
1264  currentParameters.at(i) = std::real(optTarget->Params(i));
1265 
1266  // prepare vectors to hold the parameter update directions for each shift
1267  std::vector<RealType> parameterDirections;
1268  parameterDirections.assign(N, 0.0);
1269 
1270  // compute the initial cost
1271  const RealType initCost = optTarget->computedCost();
1272 
1273  // say what we are doing
1274  app_log() << std::endl
1275  << "*****************************************" << std::endl
1276  << "Building overlap and Hamiltonian matrices" << std::endl
1277  << "*****************************************" << std::endl;
1278 
1279  // allocate the matrices we will need
1280  Matrix<RealType> ovlMat(N, N);
1281  ovlMat = 0.0;
1282  Matrix<RealType> hamMat(N, N);
1283  hamMat = 0.0;
1284  Matrix<RealType> invMat(N, N);
1285  invMat = 0.0;
1286  Matrix<RealType> prdMat(N, N);
1287  prdMat = 0.0;
1288 
1289  // build the overlap and hamiltonian matrices
1290  optTarget->fillOverlapHamiltonianMatrices(hamMat, ovlMat);
1291  invMat.copy(ovlMat);
1292 
1293  if (do_output_matrices_)
1294  {
1295  output_overlap_.output(ovlMat);
1296  output_hamiltonian_.output(hamMat);
1297  }
1298 
1299  // apply the identity shift
1300  for (int i = 1; i < N; i++)
1301  {
1302  hamMat(i, i) += bestShift_i;
1303  if (invMat(i, i) == 0)
1304  invMat(i, i) = bestShift_i * bestShift_s;
1305  }
1306 
1307  // compute the inverse of the overlap matrix
1308  {
1310  invert_matrix(invMat, false);
1311  }
1312 
1313  // apply the overlap shift
1314  for (int i = 1; i < N; i++)
1315  for (int j = 1; j < N; j++)
1316  hamMat(i, j) += bestShift_s * ovlMat(i, j);
1317 
1318  // multiply the shifted hamiltonian matrix by the inverse of the overlap matrix
1319  qmcplusplus::MatrixOperators::product(invMat, hamMat, prdMat);
1320 
1321  // transpose the result (why?)
1322  for (int i = 0; i < N; i++)
1323  for (int j = i + 1; j < N; j++)
1324  std::swap(prdMat(i, j), prdMat(j, i));
1325 
1326  // compute the lowest eigenvalue of the product matrix and the corresponding eigenvector
1327  {
1329  getLowestEigenvector(prdMat, parameterDirections);
1330  }
1331 
1332  // compute the scaling constant to apply to the update
1333  Lambda = getNonLinearRescale(parameterDirections, ovlMat, *optTarget);
1334 
1335  // scale the update by the scaling constant
1336  for (int i = 0; i < numParams; i++)
1337  parameterDirections.at(i + 1) *= Lambda;
1338 
1339  // now that we are done building the matrices, prevent further computation of derivative vectors
1340  optTarget->setneedGrads(false);
1341 
1342  // prepare to use the middle shift's update as the guiding function for a new sample
1343  if (!freeze_parameters_)
1344  {
1345  for (int i = 0; i < numParams; i++)
1346  optTarget->Params(i) = currentParameters.at(i) + parameterDirections.at(i + 1);
1347  }
1348 
1349  RealType largestChange(0);
1350  int max_element = 0;
1351  for (int i = 0; i < numParams; i++)
1352  if (std::abs(parameterDirections.at(i + 1)) > largestChange)
1353  {
1354  largestChange = std::abs(parameterDirections.at(i + 1));
1355  max_element = i;
1356  }
1357  app_log() << std::endl
1358  << "Among totally " << numParams << " optimized parameters, "
1359  << "largest LM parameter change : " << largestChange << " at parameter " << max_element << std::endl;
1360 
1361  // compute the new cost
1362  optTarget->IsValid = true;
1363  const RealType newCost = optTarget->Cost(false);
1364 
1365  app_log() << std::endl
1366  << "******************************************************************************" << std::endl
1367  << "Init Cost = " << std::scientific << std::right << std::setw(12) << std::setprecision(4) << initCost
1368  << " New Cost = " << std::scientific << std::right << std::setw(12) << std::setprecision(4) << newCost
1369  << " Delta Cost = " << std::scientific << std::right << std::setw(12) << std::setprecision(4)
1370  << newCost - initCost << std::endl
1371  << "******************************************************************************" << std::endl;
1372 
1373  if (!optTarget->IsValid || qmcplusplus::isnan(newCost))
1374  {
1375  app_log() << std::endl << "The new set of parameters is not valid. Revert to the old set!" << std::endl;
1376  for (int i = 0; i < numParams; i++)
1377  optTarget->Params(i) = currentParameters.at(i);
1379  if (accept_history[0] == true && accept_history[1] == false) // rejected the one before last and accepted the last
1380  {
1382  app_log() << "Update shift_s_base to " << shift_s_base << std::endl;
1383  }
1384  accept_history <<= 1;
1385  }
1386  else
1387  {
1388  if (bestShift_s > 1.0e-2)
1390  // say what we are doing
1391  app_log() << std::endl << "The new set of parameters is valid. Updating the trial wave function!" << std::endl;
1392  accept_history <<= 1;
1393  accept_history.set(0, true);
1394  }
1395 
1396  app_log() << std::endl
1397  << "*****************************************************************************" << std::endl
1398  << "Applying the update for shift_i = " << std::scientific << std::right << std::setw(12)
1399  << std::setprecision(4) << bestShift_i << " and shift_s = " << std::scientific << std::right
1400  << std::setw(12) << std::setprecision(4) << bestShift_s << std::endl
1401  << "*****************************************************************************" << std::endl;
1402 
1403  // perform some finishing touches for this linear method iteration
1404  finish();
1405 
1406  // return whether the cost function's report counter is positive
1407  return (optTarget->getReportCounter() > 0);
1408 }
1409 
1410 #ifdef HAVE_LMY_ENGINE
1411 //Function for optimizing using gradient descent
1413 {
1414  const bool saved_grads_flag = optTarget->getneedGrads();
1415 
1416  //Make sure needGrads is true before engine_checkConfigurations is called
1417  optTarget->setneedGrads(true);
1418 
1419  //Compute Lagrangian derivatives needed for parameter updates with engine_checkConfigurations, which is called inside engine_start
1420  engine_start(EngineObj, *descentEngineObj, MinMethod);
1421 
1422 
1423  int descent_num = descentEngineObj->getDescentNum();
1424 
1425  if (descent_num == 0)
1426  descentEngineObj->setupUpdate(optTarget->getOptVariables());
1427 
1428  //Store the derivatives and then compute parameter updates
1429  descentEngineObj->storeDerivRecord();
1430 
1431  descentEngineObj->updateParameters();
1432 
1433 
1434  std::vector<ValueType> results = descentEngineObj->retrieveNewParams();
1435 
1436 
1437  for (int i = 0; i < results.size(); i++)
1438  {
1439  optTarget->Params(i) = std::real(results[i]);
1440  }
1441 
1442  //If descent is being run as part of a hybrid optimization, need to check if a vector of
1443  //parameter differences should be stored.
1444  if (doHybrid)
1445  {
1446  int store_num = descentEngineObj->retrieveStoreFrequency();
1447  bool store = hybridEngineObj->queryStore(store_num, OptimizerType::DESCENT);
1448  if (store)
1449  {
1450  descentEngineObj->storeVectors(results);
1451  }
1452  }
1453 
1454 
1455  finish();
1456  return (optTarget->getReportCounter() > 0);
1457 }
1458 #endif
1459 
1460 
1461 //Function for controlling the alternation between sections of descent optimization and Blocked LM optimization.
1462 #ifdef HAVE_LMY_ENGINE
1463 bool QMCFixedSampleLinearOptimize::hybrid_run()
1464 {
1465  app_log() << "This is methodName: " << MinMethod << std::endl;
1466 
1467  //Either the adaptive BLM or descent optimization is run
1468 
1470  {
1471  //If the optimization just switched to using the BLM, need to transfer a set
1472  //of vectors to the BLM engine.
1474  {
1475  descentEngineObj->resetStorageCount();
1476  std::vector<std::vector<ValueType>> hybridBLM_Input = descentEngineObj->retrieveHybridBLM_Input();
1477 #if !defined(QMC_COMPLEX)
1478  //FIXME once complex is fixed in BLM engine
1479  EngineObj->setHybridBLM_Input(hybridBLM_Input);
1480 #endif
1481  }
1483 
1484  app_log() << "Update descent engine parameter values after Blocked LM step" << std::endl;
1485  for (int i = 0; i < optTarget->getNumParams(); i++)
1486  {
1487  RealType val = optTarget->Params(i);
1488  descentEngineObj->setParamVal(i, val);
1489  }
1490  }
1491 
1493  descent_run();
1494 
1495  app_log() << "Finished a hybrid step" << std::endl;
1496  return (optTarget->getReportCounter() > 0);
1497 }
1498 #endif
1499 
1501 {
1502  {
1503  //generate samples
1505  generateSamples();
1506  //store active number of walkers
1508  }
1509 
1510  app_log() << "<opt stage=\"setup\">" << std::endl;
1511  app_log() << " <log>" << std::endl;
1512  //reset the rootname
1513  optTarget->setRootName(RootName);
1514  optTarget->setWaveFunctionNode(wfNode);
1515  app_log() << " Reading configurations from h5FileRoot " << h5FileRoot << std::endl;
1516  {
1517  //get configuration from the previous run
1519  Timer t2;
1520  optTarget->getConfigurations(h5FileRoot);
1521  optTarget->setRng(vmcEngine->getRngRefs());
1522 
1523  // Compute wfn parameter derivatives
1524  NullEngineHandle handle;
1525  optTarget->checkConfigurations(handle);
1526 
1527  // check recomputed variance against VMC
1528  auto sigma2_vmc = vmcEngine->getBranchEngine()->vParam[SimpleFixedNodeBranch::SBVP::SIGMA2];
1529  auto sigma2_check = optTarget->getVariance();
1530  if (optTarget->getNumSamples() > 1 && (sigma2_check > 2.0 * sigma2_vmc || sigma2_check < 0.5 * sigma2_vmc))
1531  throw std::runtime_error(
1532  "Safeguard failure: checkConfigurations variance out of [0.5, 2.0] * reference! Please report this bug.\n");
1533  app_log() << " Execution time = " << std::setprecision(4) << t2.elapsed() << std::endl;
1534  }
1535  app_log() << " </log>" << std::endl;
1536  app_log() << "</opt>" << std::endl;
1537  app_log() << R"(<opt stage="main" walkers=")" << optTarget->getNumSamples() << "\">" << std::endl;
1538  app_log() << " <log>" << std::endl;
1539  t1.restart();
1540 }
bool targetExcited
whether we are targeting an excited state
std::unique_ptr< QMCDriver > vmcEngine
vmc engine
MatrixA::value_type invert_matrix(MatrixA &M, bool getdet=true)
invert a matrix
std::string h5FileRoot
the root of h5File
Definition: QMCDriver.h:315
void finish()
common operation to finish optimization, used by the derived classes
std::bitset< 2 > accept_history
accept history, remember the last 2 iterations, value 00, 01, 10, 11
void restart()
Definition: Timer.h:29
RealType max_param_change
max amount a parameter may change relative to current wave function weight
QMCTraits::RealType real
bool block_lm
whether we are doing block algorithm
int rank() const
return the rank
Definition: Communicate.h:116
const std::map< std::string, OptimizerType > OptimizerNames
size_t getActiveWalkers() const
return the number of active walkers
std::unique_ptr< QMCCostFunctionBase > optTarget
target cost function to optimize
std::string RootName
root of all the output files
Definition: QMCDriver.h:317
MakeReturn< UnaryNode< FnFabs, typename CreateLeaf< Vector< T1, C1 > >::Leaf_t > >::Expression_t abs(const Vector< T1, C1 > &l)
std::ostream & app_log()
Definition: OutputManager.h:65
RealType max_relative_cost_change
the maximum relative change in the cost function for the adaptive three-shift scheme ...
ScopeGuard< NewTimer > ScopedTimer
Definition: NewTimer.h:257
std::string block_lmStr
whether we are doing block algorithm
RealType bestShift_i
the previous best identity shift
bool AppendRun
flag to append or restart the run
Definition: QMCDriver.h:224
Communicate * Controller
Global Communicator for a process.
Definition: Communicate.cpp:35
bool put(std::istream &is) override
read from std::istream
Definition: ParameterSet.h:42
ParameterSet m_param
store any parameter that has to be read from a file
Definition: QMCDriver.h:320
RealType shift_i_input
current shift_i, shift_s input values
omp_int_t omp_get_max_threads()
Definition: OpenMP.h:26
void product(const Matrix< T > &A, const Matrix< T > &B, Matrix< T > &C)
static function to perform C=AB for real matrices
std::vector< double > prepare_shifts(const double central_shift) const
Real getLowestEigenvector(Matrix< Real > &A, std::vector< Real > &ev) const
Communicate * myComm
pointer to Communicate
Definition: MPIObjectBase.h:62
std::string lowerCase(const std::string_view s)
++17
QMCHamiltonian & H
Hamiltonian.
Definition: QMCDriver.h:329
MCWalkerConfiguration & W
walker ensemble
Definition: QMCDriver.h:323
static UPtrVector< RandomBase< FullPrecRealType > > Children
void start()
common operation to start optimization, used by the derived classes
void solveShiftsWithoutLMYEngine(const std::vector< double > &shifts_i, const std::vector< double > &shiffts_s, std::vector< std::vector< RealType >> &parameterDirections)
void output(Matrix< RealType > &mat)
Print matrix to text-formatted scalar.dat file.
MakeReturn< UnaryNode< FnSqrt, typename CreateLeaf< Vector< T1, C1 > >::Leaf_t > >::Expression_t sqrt(const Vector< T1, C1 > &l)
QMCTraits::RealType RealType
RealType omega_shift
the shift to use when targeting an excited state
IndexType nTargetSamples
the number of saved samples
Definition: QMCDriver.h:289
RealType cost_increase_tol
the tolerance to cost function increases when choosing the best shift in the adaptive shift method ...
std::string targetExcitedStr
whether we are targeting an excited state
int nblocks
number of blocks used in block algorithm
TrialWaveFunction & Psi
trial function
Definition: QMCDriver.h:326
std::vector< xmlNodePtr > mcwalkerNodePtr
a list of mcwalkerset element
Definition: QMCDriver.h:344
RealType target_shift_i
the shift_i value that the adaptive shift method should aim for
void print_cost_summary(const double si, const double ss, const RealType mc, const RealType cv, const int ind, const int bi, const bool gu)
const ProjectData & project_data_
top-level project data information
Definition: QMCDriver.h:216
void addWalkers(int nwalkers)
Add walkers to the end of the ensemble of walkers.
Definition: QMCDriver.cpp:338
void barrier_and_abort(const std::string &msg) const
RealType bestShift_s
the previous best overlap shift
Real getNonLinearRescale(std::vector< Real > &dP, Matrix< Real > &S, const QMCCostFunctionBase &optTarget) const
bool is_best_cost(const int ii, const std::vector< RealType > &cv, const std::vector< double > &sh, const RealType ic) const
bool isnan(float a)
return true if the value is NaN.
Definition: math.cpp:18

◆ put()

bool put ( xmlNodePtr  q)
overridevirtual

preprocess xml node

Parses the xml input file for parameter definitions for the wavefunction optimization.

Parameters
qcurrent xmlNode
Returns
true if successful

Implements QMCDriverInterface.

Definition at line 489 of file QMCFixedSampleLinearOptimize.cpp.

References OhmmsAttributeSet::add(), ParameterSet::add(), qmcplusplus::app_log(), qmcplusplus::app_warning(), QMCFixedSampleLinearOptimize::do_output_matrices_, QMCFixedSampleLinearOptimize::doGradientTest, QMCFixedSampleLinearOptimize::doHybrid, QMCFixedSampleLinearOptimize::freeze_parameters_, getXMLAttributeValue(), QMCFixedSampleLinearOptimize::hybridEngineObj, QMCDriver::m_param, QMCFixedSampleLinearOptimize::MinMethod, MPIObjectBase::myComm, processChildren(), QMCFixedSampleLinearOptimize::processOptXML(), ParameterSet::put(), OhmmsAttributeSet::put(), GradientTestInput::readXML(), and QMCFixedSampleLinearOptimize::testEngineObj.

490 {
491  std::string vmcMove("pbyp");
492  std::string ReportToH5("no");
493  std::string OutputMatrices("no");
494  std::string FreezeParameters("no");
495  OhmmsAttributeSet oAttrib;
496  oAttrib.add(vmcMove, "move");
497  oAttrib.add(ReportToH5, "hdf5");
498 
499  m_param.add(OutputMatrices, "output_matrices_csv");
500  m_param.add(FreezeParameters, "freeze_parameters");
501 
502  oAttrib.put(q);
503  m_param.put(q);
504 
505  do_output_matrices_ = (OutputMatrices != "no");
506  freeze_parameters_ = (FreezeParameters != "no");
507 
508  // Use freeze_parameters with output_matrices to generate multiple lines in the output with
509  // the same parameters so statistics can be computed in post-processing.
510 
511  if (freeze_parameters_)
512  {
513  app_log() << std::endl;
514  app_warning() << " The option 'freeze_parameters' is enabled. Variational parameters will not be updated. This "
515  "run will not perform variational parameter optimization!"
516  << std::endl;
517  app_log() << std::endl;
518  }
519 
520  doGradientTest = false;
521  processChildren(q, [&](const std::string& cname, const xmlNodePtr element) {
522  if (cname == "optimize")
523  {
524  const std::string att(getXMLAttributeValue(element, "method"));
525  if (!att.empty() && att == "gradient_test")
526  {
527  GradientTestInput test_grad_input;
528  test_grad_input.readXML(element);
529  if (!testEngineObj)
530  testEngineObj = std::make_unique<GradientTest>(std::move(test_grad_input));
531  doGradientTest = true;
532  MinMethod = "gradient_test";
533  }
534  else
535  {
536  std::stringstream error_msg;
537  app_log() << "Unknown or missing 'method' attribute in optimize tag: " << att << "\n";
538  throw UniformCommunicateError(error_msg.str());
539  }
540  }
541  });
542 
543 
544  doHybrid = false;
545 
546  if (MinMethod == "hybrid")
547  {
548  doHybrid = true;
549  if (!hybridEngineObj)
550  hybridEngineObj = std::make_unique<HybridEngine>(myComm, q);
551 
552  hybridEngineObj->incrementStepCounter();
553 
554  return processOptXML(hybridEngineObj->getSelectedXML(), vmcMove, ReportToH5 == "yes");
555  }
556  else
557  return processOptXML(q, vmcMove, ReportToH5 == "yes");
558 }
std::ostream & app_warning()
Definition: OutputManager.h:69
std::ostream & app_log()
Definition: OutputManager.h:65
bool put(xmlNodePtr cur)
assign attributes to the set
Definition: AttributeSet.h:55
bool put(std::istream &is) override
read from std::istream
Definition: ParameterSet.h:42
ParameterSet m_param
store any parameter that has to be read from a file
Definition: QMCDriver.h:320
Communicate * myComm
pointer to Communicate
Definition: MPIObjectBase.h:62
class to handle a set of attributes of an xmlNode
Definition: AttributeSet.h:24
std::string getXMLAttributeValue(const xmlNodePtr cur, const std::string_view name)
get the value string for attribute name if name is unfound in cur you get an empty string back this i...
void add(PDT &aparam, const std::string &aname_in, std::vector< PDT > candidate_values={}, TagStatus status=TagStatus::OPTIONAL)
add a new parameter corresponding to an xmlNode <parameter>
void processChildren(const xmlNodePtr cur, const F &functor)
process through all the children of an XML element F is a lambda or functor void F/[](const std::stri...
Definition: libxmldefs.h:175
bool processOptXML(xmlNodePtr cur, const std::string &vmcMove, bool reportH5)
process xml node value (parameters for both VMC and OPT) for the actual optimization ...
void add(PDT &aparam, const std::string &aname, std::vector< PDT > candidate_values={}, TagStatus status=TagStatus::OPTIONAL)
add a new attribute
Definition: AttributeSet.h:42

◆ run()

bool run ( )
overridevirtual

Run the Optimization algorithm.

Implements QMCDriverInterface.

Definition at line 213 of file QMCFixedSampleLinearOptimize.cpp.

References qmcplusplus::abs(), qmcplusplus::ADAPTIVE, QMCFixedSampleLinearOptimize::adaptive_three_shift_run(), qmcplusplus::app_log(), Communicate::barrier_and_abort(), QMCFixedSampleLinearOptimize::bigChange, Matrix< T, Alloc >::copy(), QMCFixedSampleLinearOptimize::cost_function_timer_, QMCFixedSampleLinearOptimize::current_optimizer_type_, qmcplusplus::DESCENT, QMCFixedSampleLinearOptimize::descent_run(), QMCFixedSampleLinearOptimize::do_output_matrices_, QMCFixedSampleLinearOptimize::doGradientTest, QMCFixedSampleLinearOptimize::doHybrid, qmcplusplus::Units::charge::e, QMCFixedSampleLinearOptimize::eigenvalue_timer_, qmcplusplus::exp(), QMCFixedSampleLinearOptimize::exp0, QMCFixedSampleLinearOptimize::finish(), QMCDriver::get_root_name(), LinearMethod::getLowestEigenvector(), LinearMethod::getNonLinearRescale(), OutputMatrix::init_file(), qmcplusplus::invert_matrix(), QMCFixedSampleLinearOptimize::involvmat_timer_, QMCFixedSampleLinearOptimize::line_min_timer_, QMCFixedSampleLinearOptimize::Max_iterations, QMCFixedSampleLinearOptimize::MinMethod, MPIObjectBase::myComm, qmcplusplus::Units::force::N, QMCFixedSampleLinearOptimize::nstabilizers, QMCFixedSampleLinearOptimize::one_shift_run(), qmcplusplus::ONESHIFTONLY, QMCFixedSampleLinearOptimize::optdir, QMCFixedSampleLinearOptimize::optparam, QMCFixedSampleLinearOptimize::optTarget, QMCFixedSampleLinearOptimize::output_hamiltonian_, QMCFixedSampleLinearOptimize::output_matrices_initialized_, QMCFixedSampleLinearOptimize::output_overlap_, QMCFixedSampleLinearOptimize::param_tol, qmcplusplus::MatrixOperators::product(), QMCFixedSampleLinearOptimize::stabilizerScale, TimerType< CLOCK >::start(), QMCFixedSampleLinearOptimize::start(), QMCFixedSampleLinearOptimize::stepsize, TimerType< CLOCK >::stop(), QMCFixedSampleLinearOptimize::test_run(), and QMCFixedSampleLinearOptimize::ValidCostFunction().

214 {
216  {
217  size_t numParams = optTarget->getNumParams();
218  size_t N = numParams + 1;
222  }
223 
224  if (doGradientTest)
225  {
226  app_log() << "Doing gradient test run" << std::endl;
227  return test_run();
228  }
229 
230 #ifdef HAVE_LMY_ENGINE
231  if (doHybrid)
232  {
233 #if !defined(QMC_COMPLEX)
234  app_log() << "Doing hybrid run" << std::endl;
235  return hybrid_run();
236 #else
237  myComm->barrier_and_abort(" Error: Hybrid method does not work with QMC_COMPLEX=1. \n");
238 #endif
239  }
240 
242 #if !defined(QMC_COMPLEX)
243  return descent_run();
244 #else
245  myComm->barrier_and_abort(" Error: Descent method does not work with QMC_COMPLEX=1. \n");
246 #endif
247 
248 
249  // if requested, perform the update via the adaptive three-shift or single-shift method
251  return adaptive_three_shift_run();
252 
253 
254 #endif
255 
257  return one_shift_run();
258 
259  start();
260  bool Valid(true);
261  int Total_iterations(0);
262  //size of matrix
263  size_t numParams = optTarget->getNumParams();
264  size_t N = numParams + 1;
265  // where we are and where we are pointing
266  std::vector<RealType> currentParameterDirections(N, 0);
267  std::vector<RealType> currentParameters(numParams, 0);
268  std::vector<RealType> bestParameters(numParams, 0);
269  for (int i = 0; i < numParams; i++)
270  bestParameters[i] = currentParameters[i] = std::real(optTarget->Params(i));
271  // proposed direction and new parameters
272  optdir.resize(numParams, 0);
273  optparam.resize(numParams, 0);
274 
275  while (Total_iterations < Max_iterations)
276  {
277  Total_iterations += 1;
278  app_log() << "Iteration: " << Total_iterations << "/" << Max_iterations << std::endl;
279  if (!ValidCostFunction(Valid))
280  continue;
281  //this is the small amount added to the diagonal to stabilize the eigenvalue equation. 10^stabilityBase
282  RealType stabilityBase(exp0);
283  // reset params if necessary
284  for (int i = 0; i < numParams; i++)
285  optTarget->Params(i) = currentParameters[i];
287  RealType lastCost(optTarget->Cost(true));
289  // if cost function is currently invalid continue
290  Valid = optTarget->IsValid;
291  if (!ValidCostFunction(Valid))
292  continue;
293  RealType newCost(lastCost);
294  RealType startCost(lastCost);
295  Matrix<RealType> Left(N, N);
296  Matrix<RealType> Right(N, N);
297  Matrix<RealType> S(N, N);
298  // stick in wrong matrix to reduce the number of matrices we need by 1.( Left is actually stored in Right, & vice-versa)
299  optTarget->fillOverlapHamiltonianMatrices(Right, Left);
300  S.copy(Left);
301  bool apply_inverse(true);
302  if (apply_inverse)
303  {
304  Matrix<RealType> RightT(Left);
305  {
307  invert_matrix(RightT, false);
308  }
309  Left = 0;
310  product(RightT, Right, Left);
311  // Now the left matrix is the Hamiltonian with the inverse of the overlap applied ot it.
312  }
313  //Find largest off-diagonal element compared to diagonal element.
314  //This gives us an idea how well conditioned it is, used to stabilize.
315  RealType od_largest(0);
316  for (int i = 0; i < N; i++)
317  for (int j = 0; j < N; j++)
318  od_largest = std::max(std::max(od_largest, std::abs(Left(i, j)) - std::abs(Left(i, i))),
319  std::abs(Left(i, j)) - std::abs(Left(j, j)));
320  app_log() << "od_largest " << od_largest << std::endl;
321  //if(od_largest>0)
322  // od_largest = std::log(od_largest);
323  //else
324  // od_largest = -1e16;
325  //if (od_largest<stabilityBase)
326  // stabilityBase=od_largest;
327  //else
328  // stabilizerScale = std::max( 0.2*(od_largest-stabilityBase)/nstabilizers, stabilizerScale);
329  app_log() << " stabilityBase " << stabilityBase << std::endl;
330  app_log() << " stabilizerScale " << stabilizerScale << std::endl;
331  int failedTries(0);
332  bool acceptedOneMove(false);
333  for (int stability = 0; stability < nstabilizers; stability++)
334  {
335  bool goodStep(true);
336  // store the Hamiltonian matrix in Right
337  for (int i = 0; i < N; i++)
338  for (int j = 0; j < N; j++)
339  Right(i, j) = Left(j, i);
340  RealType XS(stabilityBase + stabilizerScale * (failedTries + stability));
341  for (int i = 1; i < N; i++)
342  Right(i, i) += std::exp(XS);
343  app_log() << " Using XS:" << XS << " " << failedTries << " " << stability << std::endl;
344 
345  {
347  getLowestEigenvector(Right, currentParameterDirections);
348  Lambda = getNonLinearRescale(currentParameterDirections, S, *optTarget);
349  }
350  // biggest gradient in the parameter direction vector
351  RealType bigVec(0);
352  for (int i = 0; i < numParams; i++)
353  bigVec = std::max(bigVec, std::abs(currentParameterDirections[i + 1]));
354  // this can be overwritten during the line minimization
355  RealType evaluated_cost(startCost);
356  if (MinMethod == "rescale")
357  {
358  if (std::abs(Lambda * bigVec) > bigChange)
359  {
360  goodStep = false;
361  app_log() << " Failed Step. Magnitude of largest parameter change: " << std::abs(Lambda * bigVec)
362  << std::endl;
363  if (stability == 0)
364  {
365  failedTries++;
366  stability--;
367  }
368  else
369  stability = nstabilizers;
370  }
371  for (int i = 0; i < numParams; i++)
372  optTarget->Params(i) = currentParameters[i] + Lambda * currentParameterDirections[i + 1];
373  optTarget->IsValid = true;
374  }
375  else
376  {
377  for (int i = 0; i < numParams; i++)
378  optparam[i] = currentParameters[i];
379  for (int i = 0; i < numParams; i++)
380  optdir[i] = currentParameterDirections[i + 1];
381  TOL = param_tol / bigVec;
382  AbsFuncTol = true;
383  largeQuarticStep = bigChange / bigVec;
384  LambdaMax = 0.5 * Lambda;
386  if (MinMethod == "quartic")
387  {
388  int npts(7);
389  quadstep = stepsize * Lambda;
390  largeQuarticStep = bigChange / bigVec;
391  Valid = lineoptimization3(npts, evaluated_cost);
392  }
393  else
394  Valid = lineoptimization2();
396  RealType biggestParameterChange = bigVec * std::abs(Lambda);
397  if (biggestParameterChange > bigChange)
398  {
399  goodStep = false;
400  failedTries++;
401  app_log() << " Failed Step. Largest LM parameter change:" << biggestParameterChange << std::endl;
402  if (stability == 0)
403  stability--;
404  else
405  stability = nstabilizers;
406  }
407  else
408  {
409  for (int i = 0; i < numParams; i++)
410  optTarget->Params(i) = optparam[i] + Lambda * optdir[i];
411  app_log() << " Good Step. Largest LM parameter change:" << biggestParameterChange << std::endl;
412  }
413  }
414 
415  if (goodStep)
416  {
417  // this may have been evaluated already
418  // newCost=evaluated_cost;
419  //get cost at new minimum
420  newCost = optTarget->Cost(false);
421  app_log() << " OldCost: " << lastCost << " NewCost: " << newCost << " Delta Cost:" << (newCost - lastCost)
422  << std::endl;
423  optTarget->printEstimates();
424  // quit if newcost is greater than lastcost. E(Xs) looks quadratic (between steepest descent and parabolic)
425  // mmorales
426  Valid = optTarget->IsValid;
427  //if (MinMethod!="rescale" && !ValidCostFunction(Valid))
428  if (!ValidCostFunction(Valid))
429  {
430  goodStep = false;
431  app_log() << " Good Step, but cost function invalid" << std::endl;
432  failedTries++;
433  if (stability > 0)
434  stability = nstabilizers;
435  else
436  stability--;
437  }
438  if (newCost < lastCost && goodStep)
439  {
440  //Move was acceptable
441  for (int i = 0; i < numParams; i++)
442  bestParameters[i] = std::real(optTarget->Params(i));
443  lastCost = newCost;
444  acceptedOneMove = true;
445  if (std::abs(newCost - lastCost) < 1e-4)
446  {
447  failedTries++;
448  stability = nstabilizers;
449  continue;
450  }
451  }
452  else if (stability > 0)
453  {
454  failedTries++;
455  stability = nstabilizers;
456  continue;
457  }
458  }
459  app_log().flush();
460  if (failedTries > 20)
461  break;
462  //APP_ABORT("QMCFixedSampleLinearOptimize::run TOO MANY FAILURES");
463  }
464 
465  if (acceptedOneMove)
466  {
467  app_log() << "Setting new Parameters" << std::endl;
468  for (int i = 0; i < numParams; i++)
469  optTarget->Params(i) = bestParameters[i];
470  }
471  else
472  {
473  app_log() << "Reverting to old Parameters" << std::endl;
474  for (int i = 0; i < numParams; i++)
475  optTarget->Params(i) = currentParameters[i];
476  }
477  app_log().flush();
478  }
479 
480  finish();
481  return (optTarget->getReportCounter() > 0);
482 }
MatrixA::value_type invert_matrix(MatrixA &M, bool getdet=true)
invert a matrix
void finish()
common operation to finish optimization, used by the derived classes
QMCTraits::RealType real
std::unique_ptr< QMCCostFunctionBase > optTarget
target cost function to optimize
MakeReturn< UnaryNode< FnFabs, typename CreateLeaf< Vector< T1, C1 > >::Leaf_t > >::Expression_t abs(const Vector< T1, C1 > &l)
std::ostream & app_log()
Definition: OutputManager.h:65
ScopeGuard< NewTimer > ScopedTimer
Definition: NewTimer.h:257
const std::string & get_root_name() const override
Definition: QMCDriver.h:378
void product(const Matrix< T > &A, const Matrix< T > &B, Matrix< T > &C)
static function to perform C=AB for real matrices
Real getLowestEigenvector(Matrix< Real > &A, std::vector< Real > &ev) const
Communicate * myComm
pointer to Communicate
Definition: MPIObjectBase.h:62
MakeReturn< UnaryNode< FnExp, typename CreateLeaf< Vector< T1, C1 > >::Leaf_t > >::Expression_t exp(const Vector< T1, C1 > &l)
void start()
common operation to start optimization, used by the derived classes
QMCTraits::RealType RealType
void barrier_and_abort(const std::string &msg) const
int Max_iterations
Number of iterations maximum before generating new configurations.
void init_file(const std::string &root_name, const std::string &name, int N)
Open a text-formatted scalar.dat file and print the header line.
Real getNonLinearRescale(std::vector< Real > &dP, Matrix< Real > &S, const QMCCostFunctionBase &optTarget) const

◆ setWaveFunctionNode()

void setWaveFunctionNode ( xmlNodePtr  cur)
inline

◆ solveShiftsWithoutLMYEngine()

void solveShiftsWithoutLMYEngine ( const std::vector< double > &  shifts_i,
const std::vector< double > &  shiffts_s,
std::vector< std::vector< RealType >> &  parameterDirections 
)
private

◆ start()

void start ( )
private

common operation to start optimization, used by the derived classes

Referenced by QMCFixedSampleLinearOptimize::run(), and QMCFixedSampleLinearOptimize::test_run().

◆ test_run()

bool test_run ( )
private

Definition at line 201 of file QMCFixedSampleLinearOptimize.cpp.

References QMCFixedSampleLinearOptimize::finish(), QMCDriver::get_root_name(), QMCFixedSampleLinearOptimize::optTarget, QMCFixedSampleLinearOptimize::start(), and QMCFixedSampleLinearOptimize::testEngineObj.

Referenced by QMCFixedSampleLinearOptimize::run().

202 {
203  // generate samples and compute weights, local energies, and derivative vectors
204  start();
205 
207 
208  finish();
209 
210  return true;
211 }
void finish()
common operation to finish optimization, used by the derived classes
std::unique_ptr< QMCCostFunctionBase > optTarget
target cost function to optimize
const std::string & get_root_name() const override
Definition: QMCDriver.h:378
void start()
common operation to start optimization, used by the derived classes

◆ ValidCostFunction()

bool ValidCostFunction ( bool  valid)
inlineprivate

Definition at line 70 of file QMCFixedSampleLinearOptimize.h.

References qmcplusplus::app_log().

Referenced by QMCFixedSampleLinearOptimize::run().

71  {
72  if (!valid)
73  app_log() << " Cost Function is Invalid. If this frequently, try reducing the step size of the line minimization "
74  "or reduce the number of cycles. "
75  << std::endl;
76  return valid;
77  }
std::ostream & app_log()
Definition: OutputManager.h:65

Member Data Documentation

◆ accept_history

std::bitset<2> accept_history
private

accept history, remember the last 2 iterations, value 00, 01, 10, 11

Definition at line 152 of file QMCFixedSampleLinearOptimize.h.

◆ bestShift_i

RealType bestShift_i
private

the previous best identity shift

Definition at line 146 of file QMCFixedSampleLinearOptimize.h.

Referenced by QMCFixedSampleLinearOptimize::processOptXML().

◆ bestShift_s

RealType bestShift_s
private

the previous best overlap shift

Definition at line 148 of file QMCFixedSampleLinearOptimize.h.

Referenced by QMCFixedSampleLinearOptimize::processOptXML().

◆ bigChange

◆ block_first

bool block_first
private

whether to do the first part of block lm

Definition at line 184 of file QMCFixedSampleLinearOptimize.h.

◆ block_lm

bool block_lm
private

whether we are doing block algorithm

Definition at line 172 of file QMCFixedSampleLinearOptimize.h.

Referenced by QMCFixedSampleLinearOptimize::processOptXML().

◆ block_lmStr

std::string block_lmStr
private

◆ block_second

bool block_second
private

whether to do the second part of block lm

Definition at line 186 of file QMCFixedSampleLinearOptimize.h.

◆ block_third

bool block_third
private

whether to do the third part of block lm

Definition at line 188 of file QMCFixedSampleLinearOptimize.h.

◆ cost_function_timer_

NewTimer& cost_function_timer_
private

Definition at line 248 of file QMCFixedSampleLinearOptimize.h.

Referenced by QMCFixedSampleLinearOptimize::run().

◆ cost_increase_tol

RealType cost_increase_tol
private

the tolerance to cost function increases when choosing the best shift in the adaptive shift method

Definition at line 162 of file QMCFixedSampleLinearOptimize.h.

Referenced by QMCFixedSampleLinearOptimize::processOptXML(), and QMCFixedSampleLinearOptimize::QMCFixedSampleLinearOptimize().

◆ current_optimizer_type_

OptimizerType current_optimizer_type_
private

◆ descentEngineObj

std::unique_ptr<DescentEngine> descentEngineObj
private

◆ do_output_matrices_

bool do_output_matrices_
private

◆ doGradientTest

bool doGradientTest
private

◆ doHybrid

◆ eigCG

int eigCG
private

number of previous steps to orthogonalize to.

Definition at line 142 of file QMCFixedSampleLinearOptimize.h.

◆ eigenvalue_timer_

NewTimer& eigenvalue_timer_
private

Definition at line 245 of file QMCFixedSampleLinearOptimize.h.

Referenced by QMCFixedSampleLinearOptimize::run().

◆ exp0

◆ exp1

RealType exp1
private

Definition at line 138 of file QMCFixedSampleLinearOptimize.h.

◆ freeze_parameters_

bool freeze_parameters_
private

Definition at line 216 of file QMCFixedSampleLinearOptimize.h.

Referenced by QMCFixedSampleLinearOptimize::put().

◆ generate_samples_timer_

NewTimer& generate_samples_timer_
private

Definition at line 243 of file QMCFixedSampleLinearOptimize.h.

◆ hybridEngineObj

std::unique_ptr<HybridEngine> hybridEngineObj
private

Definition at line 118 of file QMCFixedSampleLinearOptimize.h.

Referenced by QMCFixedSampleLinearOptimize::put().

◆ initialize_timer_

NewTimer& initialize_timer_
private

Definition at line 244 of file QMCFixedSampleLinearOptimize.h.

◆ involvmat_timer_

NewTimer& involvmat_timer_
private

Definition at line 246 of file QMCFixedSampleLinearOptimize.h.

Referenced by QMCFixedSampleLinearOptimize::run().

◆ line_min_timer_

NewTimer& line_min_timer_
private

Definition at line 247 of file QMCFixedSampleLinearOptimize.h.

Referenced by QMCFixedSampleLinearOptimize::run().

◆ Max_iterations

int Max_iterations
private

Number of iterations maximum before generating new configurations.

Definition at line 222 of file QMCFixedSampleLinearOptimize.h.

Referenced by QMCFixedSampleLinearOptimize::QMCFixedSampleLinearOptimize(), and QMCFixedSampleLinearOptimize::run().

◆ max_param_change

RealType max_param_change
private

max amount a parameter may change relative to current wave function weight

Definition at line 160 of file QMCFixedSampleLinearOptimize.h.

Referenced by QMCFixedSampleLinearOptimize::processOptXML(), and QMCFixedSampleLinearOptimize::QMCFixedSampleLinearOptimize().

◆ max_relative_cost_change

RealType max_relative_cost_change
private

the maximum relative change in the cost function for the adaptive three-shift scheme

Definition at line 158 of file QMCFixedSampleLinearOptimize.h.

Referenced by QMCFixedSampleLinearOptimize::processOptXML(), and QMCFixedSampleLinearOptimize::QMCFixedSampleLinearOptimize().

◆ MinMethod

◆ nblocks

int nblocks
private

number of blocks used in block algorithm

Definition at line 174 of file QMCFixedSampleLinearOptimize.h.

Referenced by QMCFixedSampleLinearOptimize::QMCFixedSampleLinearOptimize().

◆ nkept

int nkept
private

number of directions kept

Definition at line 178 of file QMCFixedSampleLinearOptimize.h.

Referenced by QMCFixedSampleLinearOptimize::QMCFixedSampleLinearOptimize().

◆ nolds

int nolds
private

number of old updates kept

Definition at line 176 of file QMCFixedSampleLinearOptimize.h.

Referenced by QMCFixedSampleLinearOptimize::QMCFixedSampleLinearOptimize().

◆ nsamp_comp

int nsamp_comp
private

number of samples to do in correlated sampling part

Definition at line 180 of file QMCFixedSampleLinearOptimize.h.

Referenced by QMCFixedSampleLinearOptimize::QMCFixedSampleLinearOptimize().

◆ nstabilizers

◆ num_shifts

int num_shifts
private

number of shifts we will try

Definition at line 156 of file QMCFixedSampleLinearOptimize.h.

Referenced by QMCFixedSampleLinearOptimize::QMCFixedSampleLinearOptimize().

◆ NumOfVMCWalkers

int NumOfVMCWalkers
private

◆ omega_shift

RealType omega_shift
private

the shift to use when targeting an excited state

Definition at line 182 of file QMCFixedSampleLinearOptimize.h.

Referenced by QMCFixedSampleLinearOptimize::QMCFixedSampleLinearOptimize().

◆ optdir

std::vector<RealType> optdir
private

◆ optparam

std::vector<RealType> optparam
private

◆ optTarget

◆ output_hamiltonian_

OutputMatrix output_hamiltonian_
private

Definition at line 212 of file QMCFixedSampleLinearOptimize.h.

Referenced by QMCFixedSampleLinearOptimize::run().

◆ output_matrices_initialized_

bool output_matrices_initialized_
private

Definition at line 210 of file QMCFixedSampleLinearOptimize.h.

Referenced by QMCFixedSampleLinearOptimize::run().

◆ output_overlap_

OutputMatrix output_overlap_
private

Definition at line 213 of file QMCFixedSampleLinearOptimize.h.

Referenced by QMCFixedSampleLinearOptimize::run().

◆ param_tol

◆ previous_optimizer_type_

OptimizerType previous_optimizer_type_
private

◆ savedQuadstep

RealType savedQuadstep
private

Definition at line 138 of file QMCFixedSampleLinearOptimize.h.

◆ shift_i_input

RealType shift_i_input
private

◆ shift_s_base

RealType shift_s_base
private

Shift_s adjustment base.

Definition at line 154 of file QMCFixedSampleLinearOptimize.h.

◆ shift_s_input

◆ StabilizerMethod

std::string StabilizerMethod
private

Definition at line 139 of file QMCFixedSampleLinearOptimize.h.

◆ stabilizerScale

◆ stepsize

RealType stepsize
private

Definition at line 138 of file QMCFixedSampleLinearOptimize.h.

Referenced by QMCFixedSampleLinearOptimize::run().

◆ t1

◆ target_shift_i

RealType target_shift_i
private

the shift_i value that the adaptive shift method should aim for

Definition at line 164 of file QMCFixedSampleLinearOptimize.h.

Referenced by QMCFixedSampleLinearOptimize::QMCFixedSampleLinearOptimize().

◆ targetExcited

bool targetExcited
private

whether we are targeting an excited state

Definition at line 168 of file QMCFixedSampleLinearOptimize.h.

Referenced by QMCFixedSampleLinearOptimize::processOptXML().

◆ targetExcitedStr

std::string targetExcitedStr
private

whether we are targeting an excited state

Definition at line 166 of file QMCFixedSampleLinearOptimize.h.

Referenced by QMCFixedSampleLinearOptimize::processOptXML(), and QMCFixedSampleLinearOptimize::QMCFixedSampleLinearOptimize().

◆ testEngineObj

std::unique_ptr<GradientTest> testEngineObj
private

◆ TotalCGSteps

int TotalCGSteps
private

total number of cg steps per iterations

Definition at line 144 of file QMCFixedSampleLinearOptimize.h.

◆ vmcEngine

std::unique_ptr<QMCDriver> vmcEngine
private

◆ w_beta

RealType w_beta
private

Definition at line 140 of file QMCFixedSampleLinearOptimize.h.

◆ wfNode

xmlNodePtr wfNode
private

xml node to be dumped

Definition at line 228 of file QMCFixedSampleLinearOptimize.h.

Referenced by QMCFixedSampleLinearOptimize::setWaveFunctionNode().