QMCPACK
QMCCostFunctionBase.cpp
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 // Ye Luo, yeluo@anl.gov, Argonne National Laboratory
12 // Mark A. Berrill, berrillma@ornl.gov, Oak Ridge National Laboratory
13 //
14 // File created by: Jeongnim Kim, jeongnim.kim@gmail.com, University of Illinois at Urbana-Champaign
15 //////////////////////////////////////////////////////////////////////////////////////
16 
17 
18 #include "QMCCostFunctionBase.h"
20 #include "OhmmsData/AttributeSet.h"
21 #include "OhmmsData/ParameterSet.h"
23 #include "Message/CommOperators.h"
25 
26 #include <array>
27 
28 //#define QMCCOSTFUNCTION_DEBUG
29 
30 
31 namespace qmcplusplus
32 {
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 }
74 
75 /** Clean up the vector */
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 }
84 
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 }
97 
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 }
121 
122 QMCCostFunctionBase::Return_rt QMCCostFunctionBase::Cost(bool needGrad)
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 }
132 
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 }
140 
141 QMCCostFunctionBase::Return_rt QMCCostFunctionBase::computedCost()
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 }
171 
172 
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 }
211 
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 
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 }
235 /** This function stores optimized CI coefficients in HDF5
236  * Other parameters (Jastors, orbitals), can also be stored to H5 from this function
237  * This function should be called before reportParameters()
238  * Since it is needed to call updateXmlNodes() and xmlSaveFormatFile()
239  * While it is possible to call updateXmlNodes() from QMCLinearOptimize.cpp
240  * It is not clean to call xmlSaveFormatFile() from QMCLinearOptimize.cpp
241  *
242  * @param OptVariables.size() OptVariables.name(i) OptVariables[i]
243  *
244  * OptVariables.size(): contains the total number of Optimized variables (not Only CI coeff)
245  * OptVariables.name(i): the tag of the optimized variable. To store we use the name of the variable
246  * OptVariables[i]: The new value of the optimized variable
247 */
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 }
284 /** Apply constraints on the optimizables.
285  *
286  * Here is where constraints should go
287  */
289 {
290  bool samesign = true;
291  //if(samesign) {
292  // paramList.pop_back();
293  // paramList.push_front(OptParams);
294  //}
295  return samesign;
296 }
297 
298 
299 /** Parses the xml input file for parameter definitions for the wavefunction optimization.
300  * @param q current xmlNode
301  * @return true if successful
302  *
303  * Must provide a list of the id's of the variables to be optimized. Other available elements
304  <ul>
305  <li> mcwalkerset->file: name of configuration file
306  <li> optimize->method: method of optimization, right now only
307  congjugate gradient
308  <li> cost->weight: either weight for the energy term, default 1.0,
309  or weight for the variance, default 1.0
310  <li> tolerance: for conjugate gradient, default 1e-8
311  <li> stepsize: for conjugate gradient, default 0.01
312  <li> epsilon: for conjugate gradient, default 1e-6
313  </ul>
314  */
315 bool QMCCostFunctionBase::put(xmlNodePtr q)
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 
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 }
509 
510 void QMCCostFunctionBase::resetCostFunction(std::vector<xmlNodePtr>& cset)
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 }
528 
529 
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 }
723 
724 /** add coefficient or coefficients
725  * @param acontext context from which xpath cname is searched
726  * @param cname xpath
727  */
728 void QMCCostFunctionBase::addCoefficients(xmlXPathContextPtr acontext, const char* cname)
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 }
769 
770 void QMCCostFunctionBase::addCJParams(xmlXPathContextPtr acontext, const char* cname)
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 }
981 
982 
983 void QMCCostFunctionBase::printCJParams(xmlNodePtr cur, std::string& rname)
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 }
1057 
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 }
1073 
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 }
1098 
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 }
1106 
1107 ///////////////////////////////////////////////////////////////////////////////////////////////////
1108 /// \brief If the LMYEngine is available, returns the cost function calculated by the engine.
1109 /// Otherwise, returns the usual cost function.
1110 ///
1111 /// \param[in] needDeriv whether derivative vectors should be computed
1112 ///
1113 ///////////////////////////////////////////////////////////////////////////////////////////////////
1114 #ifdef HAVE_LMY_ENGINE
1115 QMCCostFunctionBase::Return_rt QMCCostFunctionBase::LMYEngineCost(const bool needDeriv,
1116  cqmc::engine::LMYEngine<Return_t>* EngineObj)
1117 {
1118  // prepare local energies, weights, and possibly derivative vectors, and compute standard cost
1119  const Return_rt standardCost = this->Cost(needDeriv);
1120 
1121  // since we are using the LMYEngine, compute and return it's cost function value
1122  return this->LMYEngineCost_detail(EngineObj);
1123 }
1124 #endif
1125 
1126 } // namespace qmcplusplus
bool targetExcited
whether we are targeting an excited state
iterator find(const std::string &vname)
return the iterator of a named parameter
Definition: VariableSet.h:98
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
std::vector< ParticleLaplacian * > d2LogPsi
Fixed Laplacian , , components.
void writeToHDF(const std::string &filename, qmcplusplus::hdf_archive &hout) const
std::ostream & app_warning()
Definition: OutputManager.h:69
Base class for any object which needs to know about a MPI communicator.
Definition: MPIObjectBase.h:26
void write(T &data, const std::string &aname)
write the data to the group aname and check status runtime error is issued on I/O error ...
Definition: hdf_archive.h:259
std::vector< std::string > variational_subset_names
optimized parameter names
void delete_iter(IT first, IT last)
delete the pointers in [first,last)
QMCTraits::RealType real
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
int rank() const
return the rank
Definition: Communicate.h:116
std::ostream * msg_stream
stream to which progress is sent
const_iterator end() const
return the last const_iterator
Definition: VariableSet.h:82
std::string RootName
string for the file root
MakeReturn< UnaryNode< FnFabs, typename CreateLeaf< Vector< T1, C1 > >::Leaf_t > >::Expression_t abs(const Vector< T1, C1 > &l)
std::vector< pair_type >::iterator iterator
Definition: VariableSet.h:55
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
void addCJParams(xmlXPathContextPtr acontext, const char *cname)
Return_rt MinNumWalkers
fraction of the number of walkers below which the costfunction becomes invalid
void close()
close all the open groups and file
Definition: hdf_archive.cpp:38
int NumOptimizables
total number of optimizable variables
Collection of Local Energy Operators.
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
class to handle hdf file
Definition: hdf_archive.h:51
void disable(ForwardIterator first, ForwardIterator last, bool reindex)
deactivate variables for optimization
Definition: VariableSet.h:289
const std::string & getName() const
std::map< std::string, std::pair< xmlNodePtr, std::string > > attribNodes
attributes to be updated
UPtrVector< RandomBase< FullPrecRealType > > RngSaved
Random number generators.
void resetIndex()
reset Index
void activate(ForwardIterator first, ForwardIterator last, bool reindex)
activate variables for optimization
Definition: VariableSet.h:264
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
bool put(std::istream &is) override
read from std::istream
Definition: ParameterSet.h:42
class to handle xmlXPathObject
Definition: Libxml2Doc.h:26
UniqueOptObjRefs extractOptimizableObjectRefs()
extract underlying OptimizableObject references
Wrapping information on parallelism.
Definition: Communicate.h:68
std::string newh5
Path and name of the HDF5 prefix where CI coeffs are saved.
#define WARNMSG(msg)
Definition: OutputManager.h:90
bool put(xmlNodePtr cur)
process xml node
Specialized paritlce class for atomistic simulations.
Definition: ParticleSet.h:55
std::vector< ParticleGradient * > dLogPsi
Fixed Gradients , , components.
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
This a subclass for runtime errors that will occur on all ranks.
std::map< std::string, xmlNodePtr > paramNodes
parameters to be updated`
Return_rt curAvg
current Average
std::string lowerCase(const std::string_view s)
++17
opt_variables_type OptVariablesForPsi
full list of optimizables
const_iterator begin() const
return the first const_iterator
Definition: VariableSet.h:80
XMLNodeString convert xmlNode contents into a std::string XMLAttrString convert one xmlNode attribute...
class to handle a set of variables that can be modified during optimizations
Definition: VariableSet.h:49
void setRng(RefVector< RandomBase< FullPrecRealType >> r)
Return_rt w_en
weights for energy and variance in the cost function
#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...
bool isEffectiveWeightValid(EffectiveWeight effective_weight) const
check the validity of the effective weight calculated by correlatedSampling
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 clear()
clear the variable set
Definition: VariableSet.cpp:28
size_type size() const
return the size
Definition: VariableSet.h:88
std::unique_ptr< std::ostream > debug_stream
stream for debug
void push(const std::string &gname, bool createit=true)
push a group to the group stack
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
int ReportCounter
counter for output
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 printCJParams(xmlNodePtr cur, std::string &rname)
std::vector< std::reference_wrapper< T > > RefVector
MakeReturn< UnaryNode< FnSqrt, typename CreateLeaf< Vector< T1, C1 > >::Leaf_t > >::Expression_t sqrt(const Vector< T1, C1 > &l)
bool getContent(const T &a, xmlNodePtr cur)
write a value to a node.
Definition: libxmldefs.h:119
bool create(const std::filesystem::path &fname, unsigned flags=H5F_ACC_TRUNC)
create a file
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
std::vector< Return_rt > SumValue
Sum of energies and weights for averages.
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.
Return_rt curVar_abs
current variance of SUM_ABSE_WGT/SUM_WGT
Return_rt MaxWeight
maximum weight beyond which the weight is set to 1
void addCoefficients(xmlXPathContextPtr acontext, const char *cname)
add coefficient or coefficients
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.
void Report() override
dump the current parameters and other report
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
void print(std::ostream &os, int leftPadSpaces=0, bool printHeader=false) const
Return_rt curVar
current Variance
int getIndex(const std::string &vname) const
return the Index vaule for the named parameter
Return_rt curVar_w
current weighted variance (correlated sampling)
Declaration of a MCWalkerConfiguration.
void resetCostFunction(std::vector< xmlNodePtr > &cset)
double omega_shift
the shift to use when targeting an excited state
void reportParameters()
report parameters at the end
std::map< std::string, xmlNodePtr > coeffNodes
coefficients to be updated
Return_rt EtargetEff
real target energy with the Correlation Factor
~QMCCostFunctionBase() override
Destructor.
virtual void resetPsi(bool final_reset=false)=0
reset the wavefunction
std::vector< RandomBase< FullPrecRealType > * > MoverRng