CASM
AClustersApproachtoStatisticalMechanics
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules
MonteIO.cc
Go to the documentation of this file.
2 #include "casm/external/gzstream/gzstream.h"
3 #include "casm/casm_io/VaspIO.hh"
6 
7 namespace CASM {
8 
11 
12  auto evaluator = [ = ](const ConstMonteCarloPtr & mc) {
13  return mc->samplers().find(prop_name)->second->mean(mc->is_equilibrated().second);
14  };
15 
16  auto validator = [ = ](const ConstMonteCarloPtr & mc) {
17  return mc->is_equilibrated().first;
18  };
19 
20  std::string header = std::string("<") + prop_name + ">";
21 
22  return GenericDatumFormatter<double, ConstMonteCarloPtr>(header, header, evaluator, validator);
23  }
24 
27 
28  auto evaluator = [ = ](const ConstMonteCarloPtr & mc) {
29  return mc->samplers().find(prop_name)->second->calculated_precision(mc->is_equilibrated().second);
30  };
31 
32  auto validator = [ = ](const ConstMonteCarloPtr & mc) {
33  return mc->is_equilibrated().first;
34  };
35 
36  std::string header = std::string("prec(<") + prop_name + ">)";
37 
38  return GenericDatumFormatter<double, ConstMonteCarloPtr>(header, header, evaluator, validator);
39  }
40 
42  auto equil = mc->is_equilibrated();
43 
44  // cov = <X*Y> - <X>*<Y>
45  const MonteSampler &sampler1 = *(mc->samplers().find(prop_name1)->second);
46  const Eigen::VectorXd &obs1 = sampler1.data().observations();
47  const Eigen::VectorXd &X = obs1.segment(equil.second, obs1.size() - equil.second);
48 
49  const MonteSampler &sampler2 = *(mc->samplers().find(prop_name2)->second);
50  const Eigen::VectorXd &obs2 = sampler2.data().observations();
51  const Eigen::VectorXd &Y = obs2.segment(equil.second, obs2.size() - equil.second);
52 
53  double Xsum = 0.0;
54  double Ysum = 0.0;
55  double XYsum = 0.0;
56  Index N = X.size();
57 
58  for(Index i = 0; i < N; ++i) {
59  Xsum += X(i);
60  Ysum += Y(i);
61  XYsum += X(i) * Y(i);
62  }
63 
64  //return X.cwiseProduct(Y).mean() - X.mean()*Y.mean();
65  return (XYsum - Xsum * Ysum / N) / N;
66  }
67 
69  GenericDatumFormatter<double, ConstMonteCarloPtr> MonteCarloCovFormatter(std::string prop_name1, std::string prop_name2) {
70 
71  auto evaluator = CovEvaluator(prop_name1, prop_name2);
72 
73  auto validator = [ = ](const ConstMonteCarloPtr & mc) {
74  return mc->is_equilibrated().first;
75  };
76 
77  std::string header = std::string("cov(") + prop_name1 + "," + prop_name2 + ")";
78 
79  return GenericDatumFormatter<double, ConstMonteCarloPtr>(header, header, evaluator, validator);
80  }
81 
84 
85  auto evaluator = [ = ](const ConstMonteCarloPtr & mc)->bool {
86  return mc->is_equilibrated().first;
87  };
88 
89  return GenericDatumFormatter<bool, ConstMonteCarloPtr>("is_equilibrated", "is_equilibrated", evaluator);
90  }
91 
94 
95  auto evaluator = [ = ](const ConstMonteCarloPtr & mc)->bool {
96  return mc->is_converged();
97  };
98 
99  return GenericDatumFormatter<bool, ConstMonteCarloPtr>("is_converged", "is_converged", evaluator);
100  }
101 
104 
105  auto evaluator = [ = ](const ConstMonteCarloPtr & mc)->unsigned long {
106  return mc->is_equilibrated().second;
107  };
108 
109  return GenericDatumFormatter<MonteSampler::size_type, ConstMonteCarloPtr>("N_equil_samples", "N_equil_samples", evaluator);
110  }
111 
114 
115  auto evaluator = [ = ](const ConstMonteCarloPtr & mc)->unsigned long {
116  return mc->sample_times().size() - mc->is_equilibrated().second;
117  };
118 
119  return GenericDatumFormatter<MonteSampler::size_type, ConstMonteCarloPtr>("N_avg_samples", "N_avg_samples", evaluator);
120  }
121 
124 
125  auto evaluator = [ = ](const std::pair<ConstMonteCarloPtr, Index> &obs) {
126  return obs.first->sample_times()[obs.second].first;
127  };
128 
130  }
131 
134 
135  auto evaluator = [ = ](const std::pair<ConstMonteCarloPtr, Index> &obs) {
136  return obs.first->sample_times()[obs.second].second;
137  };
138 
140  }
141 
144 
145  auto evaluator = [ = ](const std::pair<ConstMonteCarloPtr, Index> &obs) {
146  const MonteSampler &sampler = *(obs.first->samplers().find(prop_name)->second);
147  return sampler.data().observations()(obs.second);
148  };
149 
150  return GenericDatumFormatter<double, std::pair<ConstMonteCarloPtr, Index> >(prop_name, prop_name, evaluator);
151  }
152 
155 
156  auto evaluator = [ = ](const std::pair<ConstMonteCarloPtr, Index> &site)->int {
157  return site.first->trajectory()[site.second].occ(occ_index);
158  };
159 
160  std::string header = std::string("occ(") + std::to_string(occ_index) + ")";
161 
162  return GenericDatumFormatter<int, std::pair<ConstMonteCarloPtr, Index> >(header, header, evaluator);
163  }
164 
178 
180 
181  formatter.push_back(MonteCarloPassFormatter());
182  formatter.push_back(MonteCarloStepFormatter());
183  for(auto it = mc.samplers().cbegin(); it != mc.samplers().cend(); ++it) {
184  formatter.push_back(MonteCarloObservationFormatter(it->first));
185  }
186  return formatter;
187  }
188 
202  formatter.push_back(MonteCarloPassFormatter());
203  formatter.push_back(MonteCarloStepFormatter());
204 
205  // this is probably not the best way...
206  for(Index i = 0; i < mc.configdof().occupation().size(); ++i) {
207  formatter.push_back(MonteCarloOccFormatter(i));
208  }
209  return formatter;
210  }
211 
213  void write_observations(const MonteSettings &settings, const MonteCarlo &mc, Index cond_index, Log &_log) {
214  try {
215  if(!settings.write_observations()) {
216  return;
217  }
218 
220  fs::create_directories(dir.conditions_dir(cond_index));
221  auto formatter = make_observation_formatter(mc);
222 
223  std::vector<std::pair<ConstMonteCarloPtr, Index> > observations;
224  ConstMonteCarloPtr ptr = &mc;
225  for(MonteSampler::size_type i = 0; i < mc.sample_times().size(); ++i) {
226  observations.push_back(std::make_pair(ptr, i));
227  }
228 
229  if(settings.write_csv()) {
230  gz::ogzstream sout((dir.observations_csv(cond_index).string() + ".gz").c_str());
231  _log << "write: " << fs::path(dir.observations_csv(cond_index).string() + ".gz") << "\n";
232  sout << formatter(observations.cbegin(), observations.cend());
233  sout.close();
234  }
235 
236  if(settings.write_json()) {
237  gz::ogzstream sout((dir.observations_json(cond_index).string() + ".gz").c_str());
238  _log << "write: " << fs::path(dir.observations_json(cond_index).string() + ".gz") << "\n";
240  formatter(observations.cbegin(), observations.cend()).to_json_arrays(json);
241  sout << json;
242  sout.close();
243  }
244 
245  }
246  catch(...) {
247  std::cerr << "ERROR writing observations." << std::endl;
248  throw;
249  }
250  }
251 
269  void write_trajectory(const MonteSettings &settings, const MonteCarlo &mc, Index cond_index, Log &_log) {
270  try {
271 
272  if(!settings.write_trajectory()) {
273  return;
274  }
275 
277  fs::create_directories(dir.conditions_dir(cond_index));
278  auto formatter = make_trajectory_formatter(mc);
279  const Structure &prim = mc.primclex().get_prim();
280 
281  std::vector<std::pair<ConstMonteCarloPtr, Index> > observations;
282  ConstMonteCarloPtr ptr = &mc;
283  for(MonteSampler::size_type i = 0; i < mc.sample_times().size(); ++i) {
284  observations.push_back(std::make_pair(ptr, i));
285  }
286 
287  if(settings.write_csv()) {
288  gz::ogzstream sout((dir.trajectory_csv(cond_index).string() + ".gz").c_str());
289  _log << "write: " << fs::path(dir.trajectory_csv(cond_index).string() + ".gz") << "\n";
290  sout << formatter(observations.cbegin(), observations.cend());
291  sout.close();
292 
293  int max_allowed = 0;
294  for(int i = 0; i < prim.basis.size(); i++) {
295  if(prim.basis[i].allowed_occupants().size() > max_allowed) {
296  max_allowed = prim.basis[i].allowed_occupants().size();
297  }
298  }
299 
300  // --- Write "occupation_key.csv" ------------
301  //
302  // site_index occ_index_0 occ_index_1 ...
303  // 0 Ni Al
304  // 1 Ni -
305  // ...
306  fs::ofstream keyout(dir.occupation_key_csv());
307  _log << "write: " << dir.occupation_key_csv() << "\n";
308  keyout << "site_index";
309  for(int i = 0; i < max_allowed; i++) {
310  keyout << "\tocc_index_" << i;
311  }
312  keyout << "\n";
313 
314  for(int i = 0; i < prim.basis.size(); i++) {
315  keyout << i;
316  for(int j = 0; j < max_allowed; j++) {
317  if(j < prim.basis[i].allowed_occupants().size()) {
318  keyout << "\t" << prim.basis[i].allowed_occupants()[j];
319  }
320  else {
321  keyout << "\t-";
322  }
323  }
324  keyout << "\n";
325  }
326  keyout.close();
327 
328  }
329 
330  if(settings.write_json()) {
331 
333  json["Pass"] = jsonParser::array();
334  json["Step"] = jsonParser::array();
335  json["DoF"] = jsonParser::array();
336  for(auto it = mc.sample_times().cbegin(); it != mc.sample_times().cend(); ++it) {
337  json["Pass"].push_back(it->first);
338  json["Step"].push_back(it->second);
339  }
340  for(auto it = mc.trajectory().cbegin(); it != mc.trajectory().cend(); ++it) {
341  json["DoF"].push_back(*it);
342  }
343  gz::ogzstream sout((dir.trajectory_json(cond_index).string() + ".gz").c_str());
344  _log << "write: " << fs::path(dir.trajectory_json(cond_index).string() + ".gz") << "\n";
345  sout << json;
346  sout.close();
347 
348  // --- Write "occupation_key.json" ------------
349  //
350  // [["A", "B"],["A" "C"], ... ]
351 
353  for(int i = 0; i < prim.basis.size(); i++) {
354  key.push_back(prim.basis[i].allowed_occupants());
355  }
356  key.write(dir.occupation_key_json());
357  _log << "write: " << dir.occupation_key_json() << "\n";
358 
359  }
360 
361  }
362  catch(...) {
363  std::cerr << "ERROR writing observations." << std::endl;
364  throw;
365  }
366 
367  }
368 
372  void write_POSCAR_initial(const MonteCarlo &mc, Index cond_index, Log &_log) {
373 
375  fs::create_directories(dir.trajectory_dir(cond_index));
376 
377  // read initial_state.json
378  ConfigDoF config_dof;
379  from_json(config_dof, jsonParser(dir.initial_state_json(cond_index)));
380 
381  if(!fs::exists(dir.initial_state_json(cond_index))) {
382  throw std::runtime_error(
383  std::string("ERROR in 'write_POSCAR_initial(const MonteCarlo &mc, Index cond_index)'\n") +
384  " File not found: " + dir.initial_state_json(cond_index).string());
385  }
386 
387  // write file
388  fs::ofstream sout(dir.POSCAR_initial(cond_index));
389  _log << "write: " << dir.POSCAR_initial(cond_index) << "\n";
390  VaspIO::PrintPOSCAR p(mc.supercell(), config_dof);
391  p.sort();
392  p.print(sout);
393  return;
394  }
395 
399  void write_POSCAR_final(const MonteCarlo &mc, Index cond_index, Log &_log) {
400 
402  fs::create_directories(dir.trajectory_dir(cond_index));
403 
404  // read final_state.json
405  ConfigDoF config_dof;
406  from_json(config_dof, jsonParser(dir.final_state_json(cond_index)));
407 
408  if(!fs::exists(dir.final_state_json(cond_index))) {
409  throw std::runtime_error(
410  std::string("ERROR in 'write_POSCAR_final(const MonteCarlo &mc, Index cond_index)'\n") +
411  " File not found: " + dir.final_state_json(cond_index).string());
412  }
413 
414  // write file
415  fs::ofstream sout(dir.POSCAR_final(cond_index));
416  _log << "write: " << dir.POSCAR_final(cond_index) << "\n";
417  VaspIO::PrintPOSCAR p(mc.supercell(), config_dof);
418  p.sort();
419  p.print(sout);
420  return;
421  }
422 
427  void write_POSCAR_trajectory(const MonteCarlo &mc, Index cond_index, Log &_log) {
428 
430  fs::create_directories(dir.trajectory_dir(cond_index));
431 
432  std::vector<Index> pass;
433  std::vector<Index> step;
434  std::vector<ConfigDoF> trajectory;
435 
436  // create super structure matching supercell
437  BasicStructure<Site> primstruc = mc.supercell().get_prim();
439 
440  if(mc.settings().write_json()) {
441 
442  std::string filename = dir.trajectory_json(cond_index).string() + ".gz";
443 
444  if(!fs::exists(filename)) {
445  throw std::runtime_error(
446  std::string("ERROR in 'write_POSCAR_trajectory(const MonteCarlo &mc, Index cond_index)'\n") +
447  " File not found: " + filename);
448  }
449 
450  gz::igzstream sin(filename.c_str());
451  jsonParser json(sin);
452  for(auto it = json["Pass"].cbegin(); it != json["Pass"].cend(); ++it) {
453  pass.push_back(it->get<Index>());
454  }
455  for(auto it = json["Step"].cbegin(); it != json["Step"].cend(); ++it) {
456  step.push_back(it->get<Index>());
457  }
458  ConfigDoF config_dof;
459  for(auto it = json["DoF"].cbegin(); it != json["DoF"].cend(); ++it) {
460  from_json(config_dof, *it);
461  trajectory.push_back(config_dof);
462  }
463 
464  }
465  else if(mc.settings().write_csv()) {
466 
467  std::string filename = dir.trajectory_csv(cond_index).string() + ".gz";
468 
469  if(!fs::exists(filename)) {
470  throw std::runtime_error(
471  std::string("ERROR in 'write_POSCAR_trajectory(const MonteCarlo &mc, Index cond_index)'\n") +
472  " File not found: " + filename);
473  }
474 
475  gz::igzstream sin(filename.c_str());
476 
477  // skip the header line
478  sin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
479 
480  Index _pass, _step;
481  ConfigDoF config_dof(superstruc.basis.size());
482 
483  while(sin) {
484  sin >> _pass >> _step;
485  pass.push_back(_pass);
486  step.push_back(_step);
487  for(Index i = 0; i < superstruc.basis.size(); i++) {
488  sin >> config_dof.occ(i);
489  }
490  trajectory.push_back(config_dof);
491  }
492  }
493 
494  for(Index i = 0; i < trajectory.size(); i++) {
495 
496  // copy occupation
497  for(Index j = 0; j < trajectory[i].size(); j++) {
498  superstruc.basis[j].set_occ_value(trajectory[i].occ(j));
499  }
500 
501  // POSCAR title comment is printed with "Sample: # Pass: # Step: #"
502  std::stringstream ss;
503  ss << "Sample: " << i << " Pass: " << pass[i] << " Step: " << step[i];
504  superstruc.title = ss.str();
505 
506  // write file
507  fs::ofstream sout(dir.POSCAR_snapshot(cond_index, i));
508  _log << "write: " << dir.POSCAR_snapshot(cond_index, i) << "\n";
509  VaspIO::PrintPOSCAR p(mc.supercell(), trajectory[i]);
510  p.set_title(ss.str());
511  p.sort();
512  p.print(sout);
513  sout.close();
514  }
515 
516  return;
517  }
518 
519 
520 }
Eigen::VectorBlock< const Eigen::VectorXd > observations() const
Return all observations.
Definition: MCData.hh:44
int & occ(Index i)
Definition: ConfigDoF.hh:61
std::pair< bool, MonteSampler::size_type > is_equilibrated() const
Returns pair(true, equil_samples) if required equilibration has occured for all samplers that must co...
Definition: MonteCarlo.cc:63
void from_json(ClexDescription &desc, const jsonParser &json)
GenericDatumFormatter< double, ConstMonteCarloPtr > MonteCarloMeanFormatter(std::string prop_name)
Print mean property values:
Definition: MonteIO.cc:10
void write_POSCAR_trajectory(const MonteCarlo &mc, Index cond_index, Log &_log)
For every snapshot taken, write a POSCAR file.
Definition: MonteIO.cc:427
Index size() const
Definition: Array.hh:145
bool write_trajectory() const
Returns true if snapshots are requested.
void write(const std::string &file_name, unsigned int indent=2, unsigned int prec=12) const
Write json to file.
Definition: jsonParser.cc:191
const Structure & get_prim() const
Definition: Supercell.cc:74
Structure specifies the lattice and atomic basis of a crystal.
Definition: Structure.hh:29
bool write_observations() const
Writes all observations.
GenericDatumFormatter< double, ConstMonteCarloPtr > MonteCarloCovFormatter(std::string prop_name1, std::string prop_name2)
Print covariance: cov(prop_name1, prop_name2)
Definition: MonteIO.cc:69
BasicStructure create_superstruc(const Lattice &scel_lat, double map_tol=TOL) const
Shortcut routine to create a supercell structure and fill it with sites.
GenericDatumFormatter< bool, ConstMonteCarloPtr > MonteCarloIsConvergedFormatter()
Print if converged.
Definition: MonteIO.cc:93
GenericDatumFormatter< MonteCounter::size_type, std::pair< ConstMonteCarloPtr, Index > > MonteCarloStepFormatter()
Print Step number of observation.
Definition: MonteIO.cc:133
const Lattice & get_real_super_lattice() const
Definition: Supercell.hh:267
An abstract base class for sampling and storing data observations.
Definition: MonteSampler.hh:22
const ConfigDoF & configdof() const
const Access current microstate
Definition: MonteCarlo.hh:93
Main CASM namespace.
Definition: complete.cpp:8
std::string to_string(ENUM val)
Return string representation of enum class.
Definition: EnumIO.hh:83
const fs::path output_directory() const
Directory where output should go.
GenericDatumFormatter< double, std::pair< ConstMonteCarloPtr, Index > > MonteCarloObservationFormatter(std::string prop_name)
Print value of observation.
Definition: MonteIO.cc:143
DataFormatter< std::pair< ConstMonteCarloPtr, Index > > make_observation_formatter(const MonteCarlo &mc)
Make a observation formatter.
Definition: MonteIO.cc:177
GenericDatumFormatter< MonteCounter::size_type, std::pair< ConstMonteCarloPtr, Index > > MonteCarloPassFormatter()
Print Pass number of observation.
Definition: MonteIO.cc:123
void push_back(const BaseDatumFormatter< DataObject > &new_formatter, const std::string &args)
const SampleTimes & sample_times() const
const Access a vector of std::pair indicating when samples were taken ...
Definition: MonteCarlo.hh:158
void write_POSCAR_initial(const MonteCarlo &mc, Index cond_index, Log &_log)
For the initial state, write a POSCAR file.
Definition: MonteIO.cc:372
const Supercell & supercell() const
const Access the Supercell that *this is based on
Definition: MonteCarlo.hh:73
void write_trajectory(const MonteSettings &settings, const MonteCarlo &mc, Index cond_index, Log &_log)
Will create (and possibly overwrite) new file with all observations from run with conditions...
Definition: MonteIO.cc:269
EigenIndex Index
For long integer indexing:
void sort()
Default sort is by atom name.
Definition: VaspIO.hh:500
A container class for the different degrees of freedom a Configuration might have.
Definition: ConfigDoF.hh:27
Array< CoordType > basis
Lattice vectors that specifies periodicity of the crystal.
const MCData & data() const
const Access the raw data observation container
const PrimClex & primclex() const
const Access the PrimClex that *this is based on
Definition: MonteCarlo.hh:68
const std::vector< ConfigDoF > & trajectory() const
const Access snapshots of the Monte Carlo calculation
Definition: MonteCarlo.hh:166
DataFormatter< std::pair< ConstMonteCarloPtr, Index > > make_trajectory_formatter(const MonteCarlo &mc)
Make a trajectory formatter.
Definition: MonteIO.cc:200
Eigen::VectorXd VectorXd
GenericDatumFormatter< MonteSampler::size_type, ConstMonteCarloPtr > MonteCarloNAvgSamplesFormatter()
Print number of samples used in calculating means.
Definition: MonteIO.cc:113
void write_observations(const MonteSettings &settings, const MonteCarlo &mc, Index cond_index, Log &_log)
Will create (and possibly overwrite) new file with all observations from run with conditions...
Definition: MonteIO.cc:213
std::string title
User-specified name of this Structure.
T max(const T &A, const T &B)
Definition: CASM_math.hh:32
MCData::size_type size_type
Definition: MonteSampler.hh:26
void set_title(std::string title)
Set title.
Definition: VaspIO.hh:124
std::string prop_name2
Definition: MonteIO.hh:152
Interface base class for all types of Monte Carlo simulations (not meant to be used polymorphically) ...
Definition: MonteCarlo.hh:32
DirectoryStructure & dir
Definition: settings.cc:102
Extract data from objects of 'DataObject' class.
Print POSCAR with formating options.
Definition: VaspIO.hh:232
void write_POSCAR_final(const MonteCarlo &mc, Index cond_index, Log &_log)
For the final state, write a POSCAR file.
Definition: MonteIO.cc:399
jsonParser & push_back(const T &value)
Puts new valued element at end of array of any type T for which 'jsonParser& to_json( const T &value...
Definition: jsonParser.hh:696
Functor to help evaluate covariance.
Definition: MonteIO.hh:144
const Array< int > & occupation() const
Definition: ConfigDoF.hh:69
GenericDatumFormatter< bool, ConstMonteCarloPtr > MonteCarloIsEquilibratedFormatter()
Print if equilibrated (not counting explicitly requested equilibration)
Definition: MonteIO.cc:83
bool write_csv() const
Write csv versions of files? (csv is the default format if no 'output_format' given) ...
bool write_json() const
Write json versions of files?
GenericDatumFormatter< int, std::pair< ConstMonteCarloPtr, Index > > MonteCarloOccFormatter(Index occ_index)
Print value of a particular occupation variable.
Definition: MonteIO.cc:154
double operator()(const ConstMonteCarloPtr &mc)
Definition: MonteIO.cc:41
GenericDatumFormatter< MonteSampler::size_type, ConstMonteCarloPtr > MonteCarloNEquilSamplesFormatter()
Print number of samples used for equilibration (not counting explicitly requested equilibration) ...
Definition: MonteIO.cc:103
std::string prop_name1
Definition: MonteIO.hh:151
Settings for Monte Carlo calculations.
Definition: Log.hh:9
GenericDatumFormatter< double, ConstMonteCarloPtr > MonteCarloPrecFormatter(std::string prop_name)
Print calculated precision of property values: prec()
Definition: MonteIO.cc:26
A DatumFormatter that returns a value of specified type, via functions that may be specified at runti...
static jsonParser object()
Returns an empty json object.
Definition: jsonParser.hh:329
const SamplerMap & samplers() const
const Access sampler map
Definition: MonteCarlo.hh:153
static jsonParser array()
Returns an empty json array.
Definition: jsonParser.hh:342
const MonteSettings & settings() const
const Access settings used for construction
Definition: MonteCarlo.hh:63
const Structure & get_prim() const
const Access to primitive Structure
Definition: PrimClex.cc:260