QMCPACK
QMCCostFunctionBase.h
Go to the documentation of this file.
1 //////////////////////////////////////////////////////////////////////////////////////
2 // This file is distributed under the University of Illinois/NCSA Open Source License.
3 // See LICENSE file in top directory for details.
4 //
5 // Copyright (c) 2016 Jeongnim Kim and QMCPACK developers.
6 //
7 // File developed by: Ken Esler, kpesler@gmail.com, University of Illinois at Urbana-Champaign
8 // Miguel Morales, moralessilva2@llnl.gov, Lawrence Livermore National Laboratory
9 // Jeremy McMinnis, jmcminis@gmail.com, University of Illinois at Urbana-Champaign
10 // Jeongnim Kim, jeongnim.kim@gmail.com, University of Illinois at Urbana-Champaign
11 // Mark A. Berrill, berrillma@ornl.gov, Oak Ridge National Laboratory
12 //
13 // File created by: Jeongnim Kim, jeongnim.kim@gmail.com, University of Illinois at Urbana-Champaign
14 //////////////////////////////////////////////////////////////////////////////////////
15 
16 
17 #ifndef QMCPLUSPLUS_COSTFUNCTIONBASE_H
18 #define QMCPLUSPLUS_COSTFUNCTIONBASE_H
19 
20 #include "Configuration.h"
21 #include "Optimize/OptimizeBase.h"
24 #include "Message/MPIObjectBase.h"
25 
26 #ifdef HAVE_LMY_ENGINE
27 #include "formic/utils/matrix.h"
28 #include "formic/utils/lmyengine/engine.h"
29 #endif
30 
31 #include "EngineHandle.h"
32 
33 #include <memory>
34 
35 namespace qmcplusplus
36 {
37 class DescentEngine;
38 
39 /** @ingroup QMCDrivers
40  * @brief Implements wave-function optimization
41  *
42  * Optimization by correlated sampling method with configurations
43  * generated from VMC.
44  */
45 
46 class QMCCostFunctionBase : public CostFunctionBase<QMCTraits::RealType>, public MPIObjectBase
47 {
48 public:
50  {
57  };
59  {
69  };
70 
73  ///Constructor.
75 
76  ///Destructor
77  ~QMCCostFunctionBase() override;
78 
79  ///process xml node
80  bool put(xmlNodePtr cur);
81  void resetCostFunction(std::vector<xmlNodePtr>& cset);
82  ///Save opt parameters to HDF5
83  bool reportH5;
84  bool CI_Opt;
85  ///Path and name of the HDF5 prefix where CI coeffs are saved
86  std::string newh5;
87  ///assign optimization parameter i
88  Return_rt& Params(int i) override { return OptVariables[i]; }
89  ///return optimization parameter i
90  Return_t Params(int i) const override { return OptVariables[i]; }
91  int getType(int i) const { return OptVariables.getType(i); }
92  ///return the cost value for CGMinimization
93  Return_rt Cost(bool needGrad = true) override;
94 
95  ///return the cost value for CGMinimization
96  Return_rt computedCost();
97  void printEstimates();
98  ///return the gradient of cost value for CGMinimization
99  void GradCost(std::vector<Return_rt>& PGradient,
100  const std::vector<Return_rt>& PM,
101  Return_rt FiniteDiff = 0) override{};
102  ///return the number of optimizable parameters
103  inline int getNumParams() const override { return OptVariables.size(); }
104  ///return the global number of samples
105  inline int getNumSamples() const { return NumSamples; }
106  inline void setNumSamples(int newNumSamples) { NumSamples = newNumSamples; }
107  ///reset the wavefunction
108  virtual void resetPsi(bool final_reset = false) = 0;
109 
110  inline void getParameterTypes(std::vector<int>& types) const
111  {
113  }
114 
115  ///dump the current parameters and other report
116  void Report() override;
117  ///report parameters at the end
118  void reportParameters();
119 
120  ///report parameters in HDF5 at the end
121  void reportParametersH5();
122  ///return the counter which keeps track of optimization steps
123  inline int getReportCounter() const { return ReportCounter; }
124 
125  void setWaveFunctionNode(xmlNodePtr cur) { m_wfPtr = cur; }
126 
127  void setTargetEnergy(Return_rt et);
128 
129  void setRootName(const std::string& aroot) { RootName = aroot; }
130 
131  void setStream(std::ostream* os) { msg_stream = os; }
132 
133  void addCoefficients(xmlXPathContextPtr acontext, const char* cname);
134 
135  void printCJParams(xmlNodePtr cur, std::string& rname);
136 
137  void addCJParams(xmlXPathContextPtr acontext, const char* cname);
138 
139  virtual Return_rt fillOverlapHamiltonianMatrices(Matrix<Return_rt>& Left, Matrix<Return_rt>& Right) = 0;
140 
141 #ifdef HAVE_LMY_ENGINE
142  Return_rt LMYEngineCost(const bool needDeriv, cqmc::engine::LMYEngine<Return_t>* EngineObj);
143 #endif
144 
145  virtual void getConfigurations(const std::string& aroot) = 0;
146 
147  //Legacy drivers currently use both checkConfigurations and engine_checkConfigurations with duplicated code
148  //Providing an EngineHandle object to the batched drivers allows both cases to be handled in one function
149  virtual void checkConfigurations(EngineHandle& handle) = 0;
150 #ifdef HAVE_LMY_ENGINE
151  virtual void engine_checkConfigurations(cqmc::engine::LMYEngine<Return_t>* EngineObj,
152  DescentEngine& descentEngineObj,
153  const std::string& MinMethod) = 0;
154 
155 #endif
156 
158 
159  inline bool getneedGrads() const { return needGrads; }
160 
161  inline void setneedGrads(bool tf) { needGrads = tf; }
162  inline void setDMC() { vmc_or_dmc = 1.0; }
163 
164  inline std::string getParamName(int i) const override { return OptVariables.name(i); }
165 
166  inline const opt_variables_type& getOptVariables() const { return OptVariables; }
167 
168  /// return variance after checkConfigurations
169  inline Return_rt getVariance() const
170  {
171  return SumValue[SUM_ESQ_WGT] / SumValue[SUM_WGT] -
173  }
174 
175 protected:
176  ///Particle set
178 
179  ///Trial function
181 
182  ///Hamiltonian
184 
185  ///if true, do not write the *.opt.#.xml
187  /** |E-E_T|^PowerE is used for the cost function
188  *
189  * default PowerE=1
190  */
191  int PowerE;
192  ///number of times cost function evaluated
194  /// global number of samples to use in correlated sampling
196  ///total number of optimizable variables
198  ///counter for output
200  ///weights for energy and variance in the cost function
201  Return_rt w_en, w_var, w_abs, w_w;
202  ///value of the cost function
203  Return_rt CostValue;
204  ///target energy
205  Return_rt Etarget;
206  ///real target energy with the Correlation Factor
207  Return_rt EtargetEff;
208  ///fraction of the number of walkers below which the costfunction becomes invalid
209  Return_rt MinNumWalkers;
210  ///maximum weight beyond which the weight is set to 1
211  Return_rt MaxWeight;
212  ///current Average
213  Return_rt curAvg;
214  ///current Variance
215  Return_rt curVar;
216  ///current weighted average (correlated sampling)
217  Return_rt curAvg_w;
218  ///current weighted variance (correlated sampling)
219  Return_rt curVar_w;
220  ///current variance of SUM_ABSE_WGT/SUM_WGT
221  Return_rt curVar_abs;
222 
223  Return_rt w_beta;
224  Return_rt vmc_or_dmc;
225  bool needGrads;
226  ///whether we are targeting an excited state
227  std::string targetExcitedStr;
228  ///whether we are targeting an excited state
230  ///the shift to use when targeting an excited state
231  double omega_shift;
232 
233  ///list of optimizables
235  /** full list of optimizables
236  *
237  * The size of OptVariablesForPsi is equal to or larger than
238  * that of OptVariables due to the dependent variables.
239  * This is used for TrialWaveFunction::resetParameters and
240  * is normally the same as OptVariables.
241  */
243  // unchanged initial checked-in variables
245  /** index mapping for <equal> constraints
246  *
247  * - equalVarMap[i][0] : index in OptVariablesForPsi
248  * - equalVarMap[i][1] : index in OptVariables
249  */
250  std::vector<TinyVector<int, 2>> equalVarMap;
251  /** index mapping for <negate> constraints
252  *
253  * - negateVarMap[i][0] : index in OptVariablesForPsi
254  * - negateVarMap[i][1] : index in OptVariables
255  */
256  ///index mapping for <negative> constraints
257  std::vector<TinyVector<int, 2>> negateVarMap;
258  ///stream to which progress is sent
259  std::ostream* msg_stream;
260  ///xml node to be dumped
261  xmlNodePtr m_wfPtr;
262  ///document node to be dumped
263  xmlDocPtr m_doc_out;
264  ///parameters to be updated`
265  std::map<std::string, xmlNodePtr> paramNodes;
266  ///coefficients to be updated
267  std::map<std::string, xmlNodePtr> coeffNodes;
268  ///attributes to be updated
269  std::map<std::string, std::pair<xmlNodePtr, std::string>> attribNodes;
270  ///string for the file root
271  std::string RootName;
272 
273  ///Random number generators
275  std::vector<RandomBase<FullPrecRealType>*> MoverRng;
276 
277  /// optimized parameter names
278  std::vector<std::string> variational_subset_names;
279 
280  /** Sum of energies and weights for averages
281  *
282  * SumValues[k] where k is one of SumIndex_opt
283  */
284  std::vector<Return_rt> SumValue;
285  /** Saved properties of all the walkers
286  *
287  * Records(iw,field_id) returns the field_id value of the iw-th walker
288  * field_id is one of FieldIndex_opt
289  */
291  ///** Saved derivative properties and Hderivative properties of all the walkers
292  //*/
293  //vector<std::vector<vector<Return_t> >* > DerivRecords;
294  //vector<std::vector<vector<Return_t> >* > HDerivRecords;
295 
298  ///** Fixed Gradients , \f$\nabla\ln\Psi\f$, components */
299  std::vector<ParticleGradient*> dLogPsi;
300  ///** Fixed Laplacian , \f$\nabla^2\ln\Psi\f$, components */
301  std::vector<ParticleLaplacian*> d2LogPsi;
302  ///stream for debug
303  std::unique_ptr<std::ostream> debug_stream;
304 
305  bool checkParameters();
306  void updateXmlNodes();
307 
308  /// Flag on whether the variational parameter override is output to the new wavefunction
310 
311  /** run correlated sampling
312  * return effective walkers (\sum_i w_i)^2/(Nw * \sum_i w^2_i)
313  */
314  virtual EffectiveWeight correlatedSampling(bool needGrad = true) = 0;
315 
316  /// check the validity of the effective weight calculated by correlatedSampling
317  bool isEffectiveWeightValid(EffectiveWeight effective_weight) const;
318 
319  /// survey all the optimizable objects
321 
322  void resetOptimizableObjects(TrialWaveFunction& psi, const opt_variables_type& opt_variables) const;
323 
324 #ifdef HAVE_LMY_ENGINE
325  virtual Return_rt LMYEngineCost_detail(cqmc::engine::LMYEngine<Return_t>* EngineObj)
326  {
327  APP_ABORT("NOT IMPLEMENTED");
328  return 0;
329  }
330 #endif
331 };
332 } // namespace qmcplusplus
333 #endif
bool targetExcited
whether we are targeting an excited state
std::vector< TinyVector< int, 2 > > negateVarMap
index mapping for <negate> constraints
bool Write2OneXml
if true, do not write the *.opt.#.xml
Return_rt CostValue
value of the cost function
Return_rt Cost(bool needGrad=true) override
return the cost value for CGMinimization
bool reportH5
Save opt parameters to HDF5.
std::vector< ParticleLaplacian * > d2LogPsi
Fixed Laplacian , , components.
Base class for any object which needs to know about a MPI communicator.
Definition: MPIObjectBase.h:26
std::vector< std::string > variational_subset_names
optimized parameter names
helper functions for EinsplineSetBuilder
Definition: Configuration.h:43
Return_rt computedCost()
return the cost value for CGMinimization
int NumSamples
global number of samples to use in correlated sampling
std::string getParamName(int i) const override
std::ostream * msg_stream
stream to which progress is sent
Matrix< Return_rt > Records
Saved properties of all the walkers.
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
std::string RootName
string for the file root
void setRootName(const std::string &aroot)
virtual void checkConfigurations(EngineHandle &handle)=0
std::vector< TinyVector< int, 2 > > equalVarMap
index mapping for <equal> constraints
Return_t Params(int i) const override
return optimization parameter i
void addCJParams(xmlXPathContextPtr acontext, const char *cname)
Return_rt MinNumWalkers
fraction of the number of walkers below which the costfunction becomes invalid
int NumOptimizables
total number of optimizable variables
void setNumSamples(int newNumSamples)
Collection of Local Energy Operators.
ParticleAttrib< QTFull::ValueType > ParticleLaplacian
Definition: Configuration.h:96
QMCTraits::QTFull::RealType EffectiveWeight
Return_rt curAvg_w
current weighted average (correlated sampling)
xmlNodePtr m_wfPtr
xml node to be dumped
opt_variables_type OptVariables
list of optimizables
std::vector< std::unique_ptr< T > > UPtrVector
std::map< std::string, std::pair< xmlNodePtr, std::string > > attribNodes
attributes to be updated
declaration of MPIObjectBase
UPtrVector< RandomBase< FullPrecRealType > > RngSaved
Random number generators.
ParticleSet::ParticleLaplacian ParticleLaplacian
ParticleSet::ParticleGradient ParticleGradient
Saved derivative properties and Hderivative properties of all the walkers.
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
virtual void getConfigurations(const std::string &aroot)=0
Wrapping information on parallelism.
Definition: Communicate.h:68
std::string newh5
Path and name of the HDF5 prefix where CI coeffs are saved.
bool put(xmlNodePtr cur)
process xml node
Specialized paritlce class for atomistic simulations.
Definition: ParticleSet.h:55
std::vector< ParticleGradient * > dLogPsi
Fixed Gradients , , components.
const opt_variables_type & getOptVariables() const
void getParameterTypes(std::vector< int > &types) const
int getReportCounter() const
return the counter which keeps track of optimization steps
std::map< std::string, xmlNodePtr > paramNodes
parameters to be updated`
Return_rt curAvg
current Average
opt_variables_type OptVariablesForPsi
full list of optimizables
class to handle a set of variables that can be modified during optimizations
Definition: VariableSet.h:49
void setRng(RefVector< RandomBase< FullPrecRealType >> r)
QMCTraits::FullPrecRealType FullPrecRealType
QMCHamiltonian & H
Hamiltonian.
Return_rt w_en
weights for energy and variance in the cost function
int getType(int i) const
get the i-th parameter&#39;s type
Definition: VariableSet.h:204
#define APP_ABORT(msg)
Widely used but deprecated fatal error macros from legacy code.
Definition: AppAbort.h:27
Implements wave-function optimization.
ParticleSet & W
Particle set.
bool isEffectiveWeightValid(EffectiveWeight effective_weight) const
check the validity of the effective weight calculated by correlatedSampling
Return_rt & Params(int i) override
assign optimization parameter i
size_type size() const
return the size
Definition: VariableSet.h:88
virtual Return_rt fillOverlapHamiltonianMatrices(Matrix< Return_rt > &Left, Matrix< Return_rt > &Right)=0
std::unique_ptr< std::ostream > debug_stream
stream for debug
void getParameterTypeList(std::vector< int > &types) const
Definition: VariableSet.h:159
Declaration of a TrialWaveFunction.
int ReportCounter
counter for output
void printCJParams(xmlNodePtr cur, std::string &rname)
std::vector< std::reference_wrapper< T > > RefVector
xmlDocPtr m_doc_out
document node to be dumped
Class to represent a many-body trial wave function.
UniqueOptObjRefs extractOptimizableObjects(TrialWaveFunction &psi) const
survey all the optimizable objects
virtual EffectiveWeight correlatedSampling(bool needGrad=true)=0
run correlated sampling return effective walkers ( w_i)^2/(Nw * w^2_i)
std::string targetExcitedStr
whether we are targeting an excited state
int getNumSamples() const
return the global number of samples
Precision RealType
Definition: QMCTypes.h:37
std::vector< Return_rt > SumValue
Sum of energies and weights for averages.
Return_rt getVariance() const
return variance after checkConfigurations
const std::string & name(int i) const
return the name of i-th variable
Definition: VariableSet.h:189
void resetOptimizableObjects(TrialWaveFunction &psi, const opt_variables_type &opt_variables) const
TrialWaveFunction & Psi
Trial function.
int getNumParams() const override
return the number of optimizable parameters
Return_rt curVar_abs
current variance of SUM_ABSE_WGT/SUM_WGT
ParticleAttrib< QTFull::GradType > ParticleGradient
Definition: Configuration.h:95
Return_rt MaxWeight
maximum weight beyond which the weight is set to 1
void addCoefficients(xmlXPathContextPtr acontext, const char *cname)
add coefficient or coefficients
QTFull::RealType FullPrecRealType
Definition: Configuration.h:66
bool checkParameters()
Apply constraints on the optimizables.
void reportParametersH5()
report parameters in HDF5 at the end
QMCCostFunctionBase(ParticleSet &w, TrialWaveFunction &psi, QMCHamiltonian &h, Communicate *comm)
Constructor.
int PowerE
|E-E_T|^PowerE is used for the cost function
void setWaveFunctionNode(xmlNodePtr cur)
void Report() override
dump the current parameters and other report
Return_rt curVar
current Variance
Return_rt curVar_w
current weighted variance (correlated sampling)
void resetCostFunction(std::vector< xmlNodePtr > &cset)
BareKineticEnergy::Return_t Return_t
double omega_shift
the shift to use when targeting an excited state
void reportParameters()
report parameters at the end
Declaration of QMCHamiltonian.
std::map< std::string, xmlNodePtr > coeffNodes
coefficients to be updated
Return_rt EtargetEff
real target energy with the Correlation Factor
~QMCCostFunctionBase() override
Destructor.
std::vector< RandomBase< FullPrecRealType > * > MoverRng
virtual void resetPsi(bool final_reset=false)=0
reset the wavefunction