Scine::Readuct  5.0.0
This is the SCINE module ReaDuct.
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Pages
SinglePointTask.h
Go to the documentation of this file.
1 
7 #ifndef READUCT_SINGLEPOINTTASK_H_
8 #define READUCT_SINGLEPOINTTASK_H_
9 
10 /* Readuct */
11 #include "Tasks/Task.h"
12 /* Scine */
14 #include <Utils/CalculatorBasics.h>
16 #include <Utils/IO/Yaml.h>
17 #include <Utils/Settings.h>
19 /* External */
20 #include "boost/exception/diagnostic_information.hpp"
21 #include <boost/filesystem.hpp>
22 /* std c++ */
23 #include <algorithm>
24 #include <cstdio>
25 #include <fstream>
26 #include <iomanip>
27 #include <iostream>
28 #include <numeric>
29 #include <random>
30 #include <vector>
31 
32 namespace Scine {
33 namespace Readuct {
34 
35 class SinglePointTask : public Task {
36  public:
43  SinglePointTask(std::vector<std::string> input, std::vector<std::string> output, std::shared_ptr<Core::Log> logger = nullptr)
44  : Task(std::move(input), std::move(output), std::move(logger)) {
45  }
46 
47  std::string name() const override {
48  return "Single Point Calculation";
49  }
50 
51  bool run(SystemsMap& systems, Utils::UniversalSettings::ValueCollection taskSettings, bool testRunOnly = false,
52  std::vector<std::function<void(const int&, const Utils::AtomCollection&, const Utils::Results&, const std::string&)>>
53  observers = {}) const final {
56 
57  // Read and delete special settings
58  bool stopOnError = stopOnErrorExtraction(taskSettings);
59  bool requireCharges = taskSettings.extract("require_charges", true);
60  bool requireGradients = taskSettings.extract("require_gradients", false);
61  bool requireStressTensor = taskSettings.extract("require_stress_tensor", false);
62  bool requireBondOrders = taskSettings.extract("require_bond_orders", false);
63  bool requireOrbitalEnergies = taskSettings.extract("orbital_energies", false);
64  bool silentCalculator = taskSettings.extract("silent_stdout_calculator", true);
65  int spinPropensityCheck = taskSettings.extract("spin_propensity_check", 0);
66  if (!taskSettings.empty()) {
67  std::string keyListing = "\n";
68  auto keys = taskSettings.getKeys();
69  for (const auto& key : keys) {
70  keyListing += "'" + key + "'\n";
71  }
72  throw std::logic_error("Specified one or more task settings that are not available for this task:" + keyListing);
73  }
74  if (observers.size() > 0) {
75  throw std::logic_error("SinglePointTask does not feature algorithm accepting observers, yet one was given");
76  }
77 
78  if (testRunOnly) {
79  return true; // leave out rest in case of task chaining
80  }
81 
82  // Note: _input is guaranteed not to be empty by Task constructor
83  auto calc = copyCalculator(systems, _input.front(), name());
84  Utils::CalculationRoutines::setLog(*calc, true, true, !silentCalculator);
85  // Check for available properties
86  bool chargesAvailable = calc->possibleProperties().containsSubSet(Utils::Property::AtomicCharges);
87  bool gradientsAvailable = calc->possibleProperties().containsSubSet(Utils::Property::Gradients);
88  bool stressTensorAvailable = calc->possibleProperties().containsSubSet(Utils::Property::StressTensor);
89  bool orbitalEnergiesAvailable = calc->possibleProperties().containsSubSet(Utils::Property::OrbitalEnergies);
90  bool bondOrdersAvailable = calc->possibleProperties().containsSubSet(Utils::Property::BondOrderMatrix);
91  if (requireCharges && !chargesAvailable) {
92  throw std::logic_error("Charges required, but chosen calculator does not provide them.\n"
93  "If you do not need charges, set 'require_charges' to 'false' in the task settings");
94  }
95  if (requireGradients && !gradientsAvailable) {
96  throw std::logic_error("Gradients required, but chosen calculator does not provide them.");
97  }
98  if (requireStressTensor && !stressTensorAvailable) {
99  throw std::logic_error("Stress tensor required, but chosen calculator does not provide it.");
100  }
101  if (requireOrbitalEnergies && !orbitalEnergiesAvailable) {
102  throw std::logic_error("Orbital energies required, but chosen calculator does not provide them.");
103  }
104  if (requireBondOrders && !bondOrdersAvailable) {
105  throw std::logic_error("Bond orders required, but chosen calculator does not provide them.");
106  }
107  // Calculate energy, and possibly atomic charges and/or gradients
108  Utils::PropertyList requiredProperties = Utils::Property::Energy;
109  if (requireCharges) {
110  requiredProperties.addProperty(Utils::Property::AtomicCharges);
111  }
112  if (requireGradients) {
113  requiredProperties.addProperty(Utils::Property::Gradients);
114  }
115  if (requireStressTensor) {
116  requiredProperties.addProperty(Utils::Property::StressTensor);
117  }
118  if (requireOrbitalEnergies) {
119  requiredProperties.addProperty(Utils::Property::OrbitalEnergies);
120  }
121  if (requireBondOrders) {
122  requiredProperties.addProperty(Utils::Property::BondOrderMatrix);
123  }
124 
125  try {
126  calc->setRequiredProperties(requiredProperties);
127  calc->calculate(name());
128  if (!calc->results().get<Utils::Property::SuccessfulCalculation>()) {
129  throw std::runtime_error(name() + " was not successful");
130  }
131  }
132  catch (...) {
133  if (stopOnError) {
134  throw;
135  }
136  _logger->error
137  << " " + name() + " was not successful with error:\n " + boost::current_exception_diagnostic_information()
138  << Core::Log::endl;
139  return false;
140  }
141 
142  if (spinPropensityCheck != 0) {
143  if (!calc->settings().valueExists(Utils::SettingsNames::spinMultiplicity)) {
144  _logger->warning << "Warning: " << calc->name()
145  << " does not allow multiplicity changes, skipping spin propensity check" << Core::Log::endl;
146  }
147  else {
148  calc = Utils::CalculationRoutines::spinPropensity(*calc, *_logger, spinPropensityCheck);
149  }
150  // some calculators are lazy and don't copy properties, hence we recalculate if necessary
151  if (!calc->getRequiredProperties().containsSubSet(requiredProperties)) {
152  try {
153  calc->setRequiredProperties(requiredProperties);
154  calc->calculate(name());
155  if (!calc->results().get<Utils::Property::SuccessfulCalculation>()) {
156  throw std::runtime_error(name() + " was not successful");
157  }
158  }
159  catch (...) {
160  if (stopOnError) {
161  throw;
162  }
163  _logger->error
164  << " " + name() + " was not successful with error:\n " + boost::current_exception_diagnostic_information()
165  << Core::Log::endl;
166  return false;
167  }
168  }
169  }
170 
171  // Store result
172  if (!_output.empty()) {
173  systems[_output[0]] = calc;
174  }
175  else {
176  systems[_input[0]] = calc;
177  }
178 
179  auto energy = calc->results().get<Utils::Property::Energy>();
180 
181  // Print energy
182  auto cout = _logger->output;
183  cout.printf(" The (electronic) energy is: %+16.9f hartree\n\n", energy);
184  // Print electronic temperature
185  if (calc->settings().valueExists(Utils::SettingsNames::electronicTemperature)) {
186  auto etemp = calc->settings().getDouble(Utils::SettingsNames::electronicTemperature);
187  cout.printf(" The (electronic) temperature was: %+10.3f K\n\n", etemp);
188  }
189  // Print charges
190  if (requireCharges) {
191  auto charges = calc->results().get<Utils::Property::AtomicCharges>();
192  auto atomColl = calc->getStructure();
193  auto elements = atomColl->getElements();
194  cout << " Atomic Partial Charges:\n\n";
195  for (size_t i = 0; i < charges.size(); i++) {
196  cout.printf(" %5d %-6s: %+11.6f\n", i, Utils::ElementInfo::symbol(elements[i]).c_str(), charges[i]);
197  }
198  }
199  cout << Core::Log::nl;
200  // Print gradients
201  if (requireGradients) {
202  auto gradients = calc->results().get<Utils::Property::Gradients>();
203  cout << " Gradients (hartree / bohr):\n\n";
204  cout << [&gradients](std::ostream& os) { Utils::matrixPrettyPrint(os, gradients); };
205  cout << Core::Log::nl;
206  }
207  // Print stress tensor
208  if (requireStressTensor) {
209  Eigen::Matrix3d stressTensor = calc->results().get<Utils::Property::StressTensor>();
210  cout << " Stress tensor (hartree / bohr^3):\n\n";
211  cout << [&stressTensor](std::ostream& os) { Utils::matrixPrettyPrint(os, stressTensor); };
212  cout << Core::Log::nl;
213  }
214  // Print bond orders
215  if (requireBondOrders) {
216  cout << " Atom#1 Atom#2 Bond Order\n\n";
217  auto bos = calc->results().get<Utils::Property::BondOrderMatrix>();
218  const auto& mat = bos.getMatrix();
219  for (int i = 0; i < mat.outerSize(); i++) {
220  for (typename Eigen::SparseMatrix<double>::InnerIterator it(mat, i); it; ++it) {
221  if (it.value() > 0.3 && it.row() < it.col()) {
222  cout.printf(" %6d %6d %+16.9f\n", it.row(), it.col(), it.value());
223  }
224  }
225  }
226  cout << Core::Log::nl << Core::Log::endl;
227  }
228  // Print orbital energies
229  if (requireOrbitalEnergies) {
230  Utils::SingleParticleEnergies orbitalEnergies = calc->results().get<Utils::Property::OrbitalEnergies>();
231 
232  cout << " Orbital Energies:\n\n";
233 
234  if (orbitalEnergies.isRestricted()) {
235  const auto restrictedEnergies = orbitalEnergies.getRestrictedEnergies();
236 
237  std::cout << std::setw(20) << "Index" << std::setw(20) << "Energy / Hartree" << std::endl;
238  for (unsigned int i = 0; i < restrictedEnergies.size(); ++i) {
239  std::cout << std::setprecision(7) << std::scientific << std::right << std::setw(5) << i << std::setw(5)
240  << restrictedEnergies[i] << std::endl;
241  }
242  }
243  else {
244  const auto alphaEnergies = orbitalEnergies.getAlphaEnergies();
245  const auto betaEnergies = orbitalEnergies.getBetaEnergies();
246 
247  cout << " Alpha spin:\n\n";
248  std::cout << std::setw(5) << " Index" << std::setw(20) << "Energy / Hartree" << std::endl;
249  for (unsigned int i = 0; i < alphaEnergies.size(); ++i) {
250  std::cout << std::setprecision(7) << std::scientific << std::right << std::setw(5) << i << std::setw(22)
251  << alphaEnergies[i] << std::endl;
252  }
253 
254  cout << "\n\n Beta spin:\n\n";
255  std::cout << std::setw(5) << " Index" << std::setw(20) << "Energy / Hartree" << std::endl;
256  for (unsigned int i = 0; i < betaEnergies.size(); ++i) {
257  std::cout << std::setprecision(7) << std::scientific << std::right << std::setw(5) << i << std::setw(22)
258  << betaEnergies[i] << std::endl;
259  }
260  }
261  }
262 
263  cout << Core::Log::nl << Core::Log::endl;
264  return true;
265  }
266 };
267 
268 } // namespace Readuct
269 } // namespace Scine
270 
271 #endif // READUCT_SINGLEPOINTTASK_H_
SinglePointTask(std::vector< std::string > input, std::vector< std::string > output, std::shared_ptr< Core::Log > logger=nullptr)
Construct a new SinglePointTask.
Definition: SinglePointTask.h:43
std::string name() const override
Getter for the tasks name.
Definition: SinglePointTask.h:47
void warningIfMultipleOutputsGiven() const
Warn if more than one output system was specified.
Definition: Task.h:104
bool run(SystemsMap &systems, Utils::UniversalSettings::ValueCollection taskSettings, bool testRunOnly=false, std::vector< std::function< void(const int &, const Utils::AtomCollection &, const Utils::Results &, const std::string &)>> observers={}) const final
Executes the actual task represented by this class.
Definition: SinglePointTask.h:51
Definition: SinglePointTask.h:35
static std::ostream & endl(std::ostream &os)
const std::vector< std::string > & input() const
Getter for the expected names of the input systems.
Definition: Task.h:82
static std::ostream & nl(std::ostream &os)
void warningIfMultipleInputsGiven() const
Warn if more than one input system was specified.
Definition: Task.h:95
const std::vector< std::string > & output() const
Getter for the names of the output systems generated by this task.
Definition: Task.h:89
The base class for all tasks in Readuct.
Definition: Task.h:28
static std::string symbol(ElementType e)