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