Debian Codegraph @

avogadro/quantumio/gaussianfchk.cpp

raw
1 /******************************************************************************
2 This source file is part of the Avogadro project.
3 This source code is released under the 3-Clause BSD License, (see "LICENSE").
4 ******************************************************************************/
5
6 #include "gaussianfchk.h"
7
8 #include <avogadro/core/gaussianset.h>
9 #include <avogadro/core/molecule.h>
10 #include <avogadro/core/utilities.h>
11
12 #include <algorithm>
13 #include <cstddef>
14 #include <iostream>
15 #include <limits>
16
17 using std::cout;
18 using std::endl;
19 using std::string;
20 using std::vector;
21
22 namespace Avogadro::QuantumIO {
23
24 using Core::Atom;
25 using Core::BasisSet;
26 using Core::GaussianSet;
27 using Core::Rhf;
28 using Core::Rohf;
29 using Core::Uhf;
30
31 namespace {
32 constexpr size_t kMaxFchkArrayEntries = 16ull * 1024 * 1024; // 16M entries
33 constexpr size_t kMaxFchkMatrixElements = 32ull * 1024 * 1024; // 32M elements
34
35 bool hasMinimumRemainingBytes(std::istream& in, size_t minBytes)
36 {
37 if (minBytes == 0)
38 return true;
39
40 auto pos = in.tellg();
41 if (pos == std::streampos(-1))
42 return true;
43
44 in.clear();
45 in.seekg(0, std::ios::end);
46 auto end = in.tellg();
47 in.seekg(pos);
48 if (end == std::streampos(-1))
49 return true;
50
51 const size_t remaining = static_cast<size_t>(end - pos);
52 return remaining >= minBytes;
53 }
54 } // namespace
55
56 // https://physics.nist.gov/cgi-bin/cuu/Value?hrev
57 const double hartreeToEV = 27.211386245981;
58
59 GaussianFchk::GaussianFchk() : m_scftype(Rhf) {}
60
61 GaussianFchk::~GaussianFchk() {}
62
63 std::vector<std::string> GaussianFchk::fileExtensions() const
64 {
65 std::vector<std::string> extensions;
66 extensions.emplace_back("fchk");
67 return extensions;
68 }
69
70 std::vector<std::string> GaussianFchk::mimeTypes() const
71 {
72 return std::vector<std::string>();
73 }
74
75 bool GaussianFchk::read(std::istream& in, Core::Molecule& molecule)
76 {
77 // Read the log file line by line, most sections are terminated by an empty
78 // line, so they should be retained.
79 while (!in.eof())
80 processLine(in);
81
82 if (!error().empty())
83 return false;
84
85 const size_t posCount = m_aPos.size() / 3;
86 const size_t numCount = m_aNums.size();
87 size_t atomCount = std::min(posCount, numCount);
88 if (m_numAtoms > 0) {
89 atomCount = std::min(atomCount, static_cast<size_t>(m_numAtoms));
90 }
91 if (atomCount == 0) {
92 appendError("Could not find any atomic coordinates! Are you sure this is a "
93 "Gaussian formatted checkpoint file?");
94 return false;
95 }
96
97 auto* basis = new GaussianSet;
98 for (size_t i = 0; i < atomCount; ++i) {
99 Atom a = molecule.addAtom(static_cast<unsigned char>(m_aNums[i]));
100 const size_t offset = i * 3;
101 a.setPosition3d(Vector3(m_aPos[offset] * BOHR_TO_ANGSTROM,
102 m_aPos[offset + 1] * BOHR_TO_ANGSTROM,
103 m_aPos[offset + 2] * BOHR_TO_ANGSTROM));
104 }
105
106 if (m_frequencies.size() > 0 &&
107 m_frequencies.size() == m_vibDisplacements.size() &&
108 m_frequencies.size() == m_IRintensities.size()) {
109 molecule.setVibrationFrequencies(m_frequencies);
110 molecule.setVibrationIRIntensities(m_IRintensities);
111 molecule.setVibrationLx(m_vibDisplacements);
112 if (m_RamanIntensities.size())
113 molecule.setVibrationRamanIntensities(m_RamanIntensities);
114 }
115
116 // set the total charge
117 molecule.setData("totalCharge", m_charge);
118 // set the spin multiplicity
119 molecule.setData("totalSpinMultiplicity", m_spin);
120 // dipole moment
121 Core::Variant dipole(m_dipoleMoment.x(), m_dipoleMoment.y(),
122 m_dipoleMoment.z());
123 molecule.setData("dipoleMoment", dipole);
124
125 // Do simple bond perception.
126 molecule.perceiveBondsSimple();
127 molecule.perceiveBondOrders();
128 molecule.setBasisSet(basis);
129 basis->setMolecule(&molecule);
130 load(basis);
131
132 // partial charges
133 if (m_mullikenCharges.size() == m_aNums.size()) {
134 Eigen::MatrixXd charges(m_aNums.size(), 1);
135 charges.setZero();
136
137 for (unsigned int i = 0; i < m_aNums.size(); ++i) {
138 charges(i, 0) = m_mullikenCharges[i];
139 }
140 molecule.setPartialCharges("Mulliken", charges);
141 }
142
143 return true;
144 }
145
146 void GaussianFchk::processLine(std::istream& in)
147 {
148 // First truncate the line, remove trailing white space and check any line of
149 // the required length. We are looking for keyword lines of the form,
150 // Charge I 0
151 // If we are in any other kind of block that is not known skip through until
152 // we find a recognized block.
153 string line;
154 if (!getline(in, line) || line.size() < 44)
155 return;
156
157 string key = line.substr(0, 42);
158
159 // cout << "Key:\t" << key << endl;
160 key = Core::trimmed(key);
161
162 string tmp = line.substr(43);
163 vector<string> list = Core::split(tmp, ' ');
164 std::vector<double> tmpVec;
165
166 // Big switch statement checking for various things we are interested in
167 if (Core::contains(key, "RHF")) {
168 m_scftype = Rhf;
169 } else if (Core::contains(key, "UHF")) {
170 m_scftype = Uhf;
171 } else if (key == "Number of atoms" && list.size() > 1) {
172 m_numAtoms = Core::lexicalCast<int>(list[1]).value_or(0);
173 } else if (key == "Charge" && list.size() > 1) {
174 m_charge = Core::lexicalCast<int>(list[1]).value_or(0);
175 } else if (key == "Multiplicity" && list.size() > 1) {
176 m_spin = Core::lexicalCast<int>(list[1]).value_or(1);
177 } else if (key == "Dipole Moment" && list.size() > 2) {
178 vector<double> dipole =
179 readArrayD(in, Core::lexicalCast<int>(list[2]).value_or(0));
180 m_dipoleMoment = Vector3(dipole[0], dipole[1], dipole[2]);
181 // convert from au
182 m_dipoleMoment *= 2.541746;
183 } else if (key == "Number of electrons" && list.size() > 1) {
184 m_electrons = Core::lexicalCast<int>(list[1]).value_or(0);
185 } else if (key == "Number of alpha electrons" && list.size() > 1) {
186 m_electronsAlpha = Core::lexicalCast<int>(list[1]).value_or(0);
187 } else if (key == "Number of beta electrons" && list.size() > 1) {
188 m_electronsBeta = Core::lexicalCast<int>(list[1]).value_or(0);
189 } else if (key == "Number of basis functions" && list.size() > 1) {
190 m_numBasisFunctions = Core::lexicalCast<int>(list[1]).value_or(0);
191 // cout << "Number of basis functions = " << m_numBasisFunctions << endl;
192 } else if (key == "Atomic numbers" && list.size() > 2) {
193 m_aNums = readArrayI(in, Core::lexicalCast<int>(list[2]).value_or(0));
194 if (static_cast<int>(m_aNums.size()) != Core::lexicalCast<int>(list[2]))
195 cout << "Reading atomic numbers failed.\n";
196 }
197 // Now we get to the meat of it - coordinates of the atoms
198 else if (key == "Current cartesian coordinates" && list.size() > 2) {
199 m_aPos = readArrayD(in, Core::lexicalCast<int>(list[2]).value_or(0), 16);
200 } else if (key == "Mulliken Charges" && list.size() > 2) {
201 m_mullikenCharges =
202 readArrayD(in, Core::lexicalCast<int>(list[2]).value_or(0), 16);
203 }
204 // The real meat is here - basis sets etc!
205 else if (key == "Shell types" && list.size() > 2) {
206 m_shellTypes = readArrayI(in, Core::lexicalCast<int>(list[2]).value_or(0));
207 } else if (key == "Number of primitives per shell" && list.size() > 2) {
208 m_shellNums = readArrayI(in, Core::lexicalCast<int>(list[2]).value_or(0));
209 } else if (key == "Shell to atom map" && list.size() > 2) {
210 m_shelltoAtom = readArrayI(in, Core::lexicalCast<int>(list[2]).value_or(0));
211 }
212 // Now to get the exponents and coefficients(
213 else if (key == "Primitive exponents" && list.size() > 2) {
214 m_a = readArrayD(in, Core::lexicalCast<int>(list[2]).value_or(0), 16);
215 } else if (key == "Contraction coefficients" && list.size() > 2) {
216 m_c = readArrayD(in, Core::lexicalCast<int>(list[2]).value_or(0), 16);
217 } else if (key == "P(S=P) Contraction coefficients" && list.size() > 2) {
218 m_csp = readArrayD(in, Core::lexicalCast<int>(list[2]).value_or(0), 16);
219 } else if (key == "Alpha Orbital Energies" || key == "orbital energies") {
220 if (m_scftype == Rhf) {
221 m_orbitalEnergy = readArrayD(
222 in, Core::lexicalCast<int>(list[2]).value_or(0), 16, hartreeToEV);
223 } else if (m_scftype == Uhf) {
224 m_alphaOrbitalEnergy = readArrayD(
225 in, Core::lexicalCast<int>(list[2]).value_or(0), 16, hartreeToEV);
226 }
227 } else if (key == "Beta Orbital Energies") {
228 if (m_scftype != Uhf) {
229 m_scftype = Uhf;
230 m_alphaOrbitalEnergy = m_orbitalEnergy;
231 m_orbitalEnergy = vector<double>();
232
233 m_alphaMOcoeffs = m_MOcoeffs;
234 m_MOcoeffs = vector<double>();
235 }
236
237 m_betaOrbitalEnergy = readArrayD(
238 in, Core::lexicalCast<int>(list[2]).value_or(0), 16, hartreeToEV);
239 } else if ((key == "Alpha MO coefficients" || key == "MO coefficients (C)") &&
240 list.size() > 2) {
241 if (m_scftype == Rhf) {
242 m_MOcoeffs =
243 readArrayD(in, Core::lexicalCast<int>(list[2]).value_or(0), 16);
244 } else if (m_scftype == Uhf) {
245 m_alphaMOcoeffs =
246 readArrayD(in, Core::lexicalCast<int>(list[2]).value_or(0), 16);
247 } else {
248 cout << "Error, alpha MO coefficients, n = " << m_MOcoeffs.size() << endl;
249 }
250 } else if (key == "Beta MO coefficients" && list.size() > 2) {
251 m_betaMOcoeffs =
252 readArrayD(in, Core::lexicalCast<int>(list[2]).value_or(0), 16);
253 } else if (key == "Total SCF Density" && list.size() > 2) {
254 if (!readDensityMatrix(in, Core::lexicalCast<int>(list[2]).value_or(0), 16))
255 cout << "Error reading in the SCF density matrix.\n";
256 } else if (key == "Spin SCF Density" && list.size() > 2) {
257 if (!readSpinDensityMatrix(in, Core::lexicalCast<int>(list[2]).value_or(0),
258 16))
259 cout << "Error reading in the SCF spin density matrix.\n";
260 } else if (key == "Number of Normal Modes" && list.size() > 1) {
261 m_normalModes = Core::lexicalCast<int>(list[1]).value_or(0);
262 } else if (key == "Vib-E2" && list.size() > 2) {
263 m_frequencies.clear();
264 m_IRintensities.clear();
265 m_RamanIntensities.clear();
266
267 unsigned threeN = m_numAtoms * 3; // degrees of freedom
268 tmpVec = readArrayD(in, Core::lexicalCast<int>(list[2]).value_or(0), 16);
269
270 // read in the first 3N-6 elements as frequencies
271 for (unsigned int i = 0; i < static_cast<unsigned int>(m_normalModes);
272 ++i) {
273 m_frequencies.push_back(tmpVec[i]);
274 }
275 // skip to after threeN elements then read IR intensities
276 for (unsigned int i = threeN;
277 i < threeN + static_cast<unsigned int>(m_normalModes); ++i) {
278 m_IRintensities.push_back(tmpVec[i]);
279 }
280 // now check if we have Raman intensities
281 if (tmpVec[threeN + m_normalModes] != 0.0) {
282 for (unsigned int i = threeN + m_normalModes;
283 i < threeN + 2 * static_cast<unsigned int>(m_normalModes); ++i) {
284 m_RamanIntensities.push_back(tmpVec[i]);
285 }
286 }
287 } else if (key == "Vib-Modes" && list.size() > 2) {
288 tmpVec = readArrayD(in, Core::lexicalCast<int>(list[2]).value_or(0), 16);
289 m_vibDisplacements.clear();
290 if (tmpVec.size() == static_cast<size_t>(m_numAtoms) * 3 *
291 static_cast<size_t>(m_normalModes)) {
292 for (unsigned int i = 0; i < static_cast<unsigned int>(m_normalModes);
293 ++i) {
294 Core::Array<Vector3> mode;
295 for (unsigned int j = 0; j < static_cast<unsigned int>(m_numAtoms);
296 ++j) {
297 Vector3 v(tmpVec[i * m_numAtoms * 3 + j * 3],
298 tmpVec[i * m_numAtoms * 3 + j * 3 + 1],
299 tmpVec[i * m_numAtoms * 3 + j * 3 + 2]);
300 mode.push_back(v);
301 }
302 m_vibDisplacements.push_back(mode);
303 }
304 }
305 }
306 }
307
308 void GaussianFchk::load(GaussianSet* basis)
309 {
310 // Now load up our basis set
311 basis->setScfType(m_scftype);
312 basis->setElectronCount(m_electrons);
313 // basis->setElectronCount(m_electronsAlpha, Core::GaussianSet::alpha);
314 // basis->setElectronCount(m_electronsBeta, Core::GaussianSet::beta);
315
316 if (m_shellTypes.empty()) {
317 cout << "GaussianFchk: no shell types found.\n";
318 return;
319 }
320 if (m_shellNums.size() != m_shellTypes.size() ||
321 m_shelltoAtom.size() != m_shellTypes.size()) {
322 cout << "GaussianFchk: inconsistent shell data sizes.\n";
323 return;
324 }
325 if (m_numAtoms <= 0) {
326 cout << "GaussianFchk: invalid atom count.\n";
327 return;
328 }
329
330 size_t totalPrimitives = 0;
331 size_t totalSpPrimitives = 0;
332 const size_t maxSize = std::numeric_limits<size_t>::max();
333 for (size_t i = 0; i < m_shellTypes.size(); ++i) {
334 const int shellNum = m_shellNums[i];
335 if (shellNum <= 0) {
336 cout << "GaussianFchk: invalid shell primitive count.\n";
337 return;
338 }
339 const int atomIndex = m_shelltoAtom[i];
340 if (atomIndex <= 0 || atomIndex > m_numAtoms) {
341 cout << "GaussianFchk: invalid shell-to-atom map.\n";
342 return;
343 }
344 const size_t shellNumU = static_cast<size_t>(shellNum);
345 if (totalPrimitives > maxSize - shellNumU) {
346 cout << "GaussianFchk: shell primitive count overflow.\n";
347 return;
348 }
349 totalPrimitives += shellNumU;
350 if (m_shellTypes[i] == -1) {
351 if (totalSpPrimitives > maxSize - shellNumU) {
352 cout << "GaussianFchk: SP primitive count overflow.\n";
353 return;
354 }
355 totalSpPrimitives += shellNumU;
356 }
357 }
358
359 if (m_a.size() < totalPrimitives || m_c.size() < totalPrimitives) {
360 cout << "GaussianFchk: insufficient primitive exponent data.\n";
361 return;
362 }
363 if (totalSpPrimitives > 0 && m_csp.size() < totalSpPrimitives) {
364 cout << "GaussianFchk: insufficient SP contraction data.\n";
365 return;
366 }
367
368 // Set up the GTO primitive counter, go through the shells and add them
369 int nGTO = 0;
370 for (unsigned int i = 0; i < m_shellTypes.size(); ++i) {
371 // Handle the SP case separately - this should possibly be a distinct type
372 if (m_shellTypes[i] == -1) {
373 // SP orbital type - actually have to add two shells
374 int s = basis->addBasis(m_shelltoAtom[i] - 1, GaussianSet::S);
375 int tmpGTO = nGTO;
376 for (unsigned int j = 0; j < static_cast<unsigned int>(m_shellNums[i]);
377 ++j) {
378 if (static_cast<size_t>(nGTO) >= m_a.size() ||
379 static_cast<size_t>(nGTO) >= m_c.size()) {
380 cout << "GaussianFchk: primitive index out of range.\n";
381 return;
382 }
383 basis->addGto(s, m_c[nGTO], m_a[nGTO]);
384 ++nGTO;
385 }
386 int p = basis->addBasis(m_shelltoAtom[i] - 1, GaussianSet::P);
387 for (unsigned int j = 0; j < static_cast<unsigned int>(m_shellNums[i]);
388 ++j) {
389 if (static_cast<size_t>(tmpGTO) >= m_a.size() ||
390 static_cast<size_t>(tmpGTO) >= m_csp.size()) {
391 cout << "GaussianFchk: SP primitive index out of range.\n";
392 return;
393 }
394 basis->addGto(p, m_csp[tmpGTO], m_a[tmpGTO]);
395 ++tmpGTO;
396 }
397 } else {
398 GaussianSet::orbital type;
399 switch (m_shellTypes[i]) {
400 case 0:
401 type = GaussianSet::S;
402 break;
403 case 1:
404 type = GaussianSet::P;
405 break;
406 case 2:
407 type = GaussianSet::D;
408 break;
409 case -2:
410 type = GaussianSet::D5;
411 break;
412 case 3:
413 type = GaussianSet::F;
414 break;
415 case -3:
416 type = GaussianSet::F7;
417 break;
418 case 4:
419 type = GaussianSet::G;
420 break;
421 case -4:
422 type = GaussianSet::G9;
423 break;
424 case 5:
425 type = GaussianSet::H;
426 break;
427 case -5:
428 type = GaussianSet::H11;
429 break;
430 case 6:
431 type = GaussianSet::I;
432 break;
433 case -6:
434 type = GaussianSet::I13;
435 break;
436 default:
437 // If we encounter GTOs we do not understand, the basis is likely
438 // invalid
439 type = GaussianSet::UU;
440 /// basis->setValid(false);
441 }
442 if (type != GaussianSet::UU) {
443 int b = basis->addBasis(m_shelltoAtom[i] - 1, type);
444 for (unsigned int j = 0; j < static_cast<unsigned int>(m_shellNums[i]);
445 ++j) {
446 if (static_cast<size_t>(nGTO) >= m_a.size() ||
447 static_cast<size_t>(nGTO) >= m_c.size()) {
448 cout << "GaussianFchk: primitive index out of range.\n";
449 return;
450 }
451 basis->addGto(b, m_c[nGTO], m_a[nGTO]);
452 ++nGTO;
453 }
454 }
455 }
456 }
457 // Now to load in the MO coefficients
458 if (basis->isValid()) {
459 if (m_MOcoeffs.size())
460 basis->setMolecularOrbitals(m_MOcoeffs);
461 else
462 cout << "Error no MO coefficients...\n";
463 if (m_alphaMOcoeffs.size())
464 basis->setMolecularOrbitals(m_alphaMOcoeffs, BasisSet::Alpha);
465 if (m_betaMOcoeffs.size())
466 basis->setMolecularOrbitals(m_betaMOcoeffs, BasisSet::Beta);
467
468 if (m_density.rows())
469 basis->setDensityMatrix(m_density);
470 if (m_spinDensity.rows())
471 basis->setSpinDensityMatrix(m_spinDensity);
472
473 if (m_orbitalEnergy.size()) // restricted calculation
474 basis->setMolecularOrbitalEnergy(m_orbitalEnergy);
475 else {
476 if (m_alphaOrbitalEnergy.size())
477 basis->setMolecularOrbitalEnergy(m_alphaOrbitalEnergy, BasisSet::Alpha);
478 if (m_betaOrbitalEnergy.size())
479 basis->setMolecularOrbitalEnergy(m_betaOrbitalEnergy, BasisSet::Beta);
480 }
481 } else {
482 cout << "Basis set is not valid!\n";
483 }
484 }
485
486 vector<int> GaussianFchk::readArrayI(std::istream& in, unsigned int n)
487 {
488 vector<int> tmp;
489 if (n == 0)
490 return tmp;
491 if (n > kMaxFchkArrayEntries) {
492 appendError("Array data exceeds supported size.");
493 return tmp;
494 }
495 const size_t nSize = static_cast<size_t>(n);
496 if (!hasMinimumRemainingBytes(in, nSize)) {
497 appendError("Invalid array data.");
498 return tmp;
499 }
500 tmp.reserve(n);
501 bool ok(false);
502 while (tmp.size() < n) {
503 if (in.eof()) {
504 cout << "GaussianFchk::readArrayI could not read all elements " << n
505 << " expected " << tmp.size() << " parsed.\n";
506 return tmp;
507 }
508 string line;
509 if (getline(in, line), line.empty())
510 return tmp;
511
512 vector<string> list = Core::split(line, ' ');
513 for (auto& i : list) {
514 if (tmp.size() >= n) {
515 cout << "Too many variables read in. File may be inconsistent. "
516 << tmp.size() << " of " << n << endl;
517 return tmp;
518 }
519 tmp.push_back(Core::lexicalCast<int>(i, ok));
520 if (!ok) {
521 cout << "Warning: problem converting string to integer: " << i
522 << " in GaussianFchk::readArrayI.\n";
523 return tmp;
524 }
525 }
526 }
527 return tmp;
528 }
529
530 vector<double> GaussianFchk::readArrayD(std::istream& in, unsigned int n,
531 int width, double factor)
532 {
533 vector<double> tmp;
534 if (n == 0)
535 return tmp;
536 if (n > kMaxFchkArrayEntries) {
537 appendError("Array data exceeds supported size.");
538 return tmp;
539 }
540 const size_t nSize = static_cast<size_t>(n);
541 const size_t maxSize = std::numeric_limits<size_t>::max();
542 const size_t minBytesPerEntry = width > 0 ? static_cast<size_t>(width) : 1ull;
543 if (minBytesPerEntry > 0 && nSize > maxSize / minBytesPerEntry) {
544 appendError("Array data exceeds supported size.");
545 return tmp;
546 }
547 if (!hasMinimumRemainingBytes(in, nSize * minBytesPerEntry)) {
548 appendError("Invalid array data.");
549 return tmp;
550 }
551 tmp.reserve(n);
552 bool ok(false);
553 while (tmp.size() < n) {
554 if (in.eof()) {
555 cout << "GaussianFchk::readArrayD could not read all elements " << n
556 << " expected " << tmp.size() << " parsed.\n";
557 return tmp;
558 }
559 string line;
560 if (getline(in, line), line.empty())
561 return tmp;
562
563 if (width == 0) { // we can split by spaces
564 vector<string> list = Core::split(line, ' ');
565 for (auto& i : list) {
566 if (tmp.size() >= n) {
567 cout << "Too many variables read in. File may be inconsistent. "
568 << tmp.size() << " of " << n << endl;
569 return tmp;
570 }
571 tmp.push_back(Core::lexicalCast<double>(i, ok) * factor);
572 if (!ok) {
573 cout << "Warning: problem converting string to integer: " << i
574 << " in GaussianFchk::readArrayD.\n";
575 return tmp;
576 }
577 }
578 } else { // Q-Chem files use 16 character fields
579 size_t maxColumns = 80 / width;
580 for (size_t i = 0; i < maxColumns; ++i) {
581 string substring = line.substr(i * width, width);
582 if (static_cast<int>(substring.length()) != width)
583 break;
584 if (tmp.size() >= n) {
585 cout << "Too many variables read in. File may be inconsistent. "
586 << tmp.size() << " of " << n << endl;
587 return tmp;
588 }
589 tmp.push_back(Core::lexicalCast<double>(substring, ok) * factor);
590 if (!ok) {
591 cout << "Warning: problem converting string to double: " << substring
592 << " in GaussianFchk::readArrayD.\n";
593 return tmp;
594 }
595 }
596 }
597 }
598 return tmp;
599 }
600
601 bool GaussianFchk::readDensityMatrix(std::istream& in, unsigned int n,
602 int width)
603 {
604 // This function reads in the lower triangular density matrix
605 if (n == 0)
606 return false;
607 if (n > kMaxFchkArrayEntries) {
608 appendError("Density matrix exceeds supported size.");
609 return false;
610 }
611 if (m_numBasisFunctions <= 0) {
612 appendError("Invalid basis function count.");
613 return false;
614 }
615 const size_t basis = static_cast<size_t>(m_numBasisFunctions);
616 const size_t maxSize = std::numeric_limits<size_t>::max();
617 if (basis > 0 && basis > maxSize / basis) {
618 appendError("Density matrix exceeds supported size.");
619 return false;
620 }
621 const size_t fullCount = basis * basis;
622 if (fullCount > kMaxFchkMatrixElements) {
623 appendError("Density matrix exceeds supported size.");
624 return false;
625 }
626 if (basis > 0 && basis > maxSize / (basis + 1)) {
627 appendError("Density matrix exceeds supported size.");
628 return false;
629 }
630 const size_t expectedLower = basis * (basis + 1) / 2;
631 if (static_cast<size_t>(n) > expectedLower) {
632 appendError("Invalid density matrix size.");
633 return false;
634 }
635 const size_t minBytesPerEntry = width > 0 ? static_cast<size_t>(width) : 1ull;
636 if (minBytesPerEntry > 0 &&
637 static_cast<size_t>(n) > maxSize / minBytesPerEntry) {
638 appendError("Density matrix exceeds supported size.");
639 return false;
640 }
641 if (!hasMinimumRemainingBytes(in,
642 static_cast<size_t>(n) * minBytesPerEntry)) {
643 appendError("Invalid density matrix data.");
644 return false;
645 }
646 m_density.resize(m_numBasisFunctions, m_numBasisFunctions);
647 unsigned int cnt = 0;
648 unsigned int i = 0, j = 0;
649 unsigned int f = 1;
650 bool ok = false;
651 while (cnt < n) {
652 if (in.eof()) {
653 cout << "GaussianFchk::readDensityMatrix could not read all elements "
654 << n << " expected " << cnt << " parsed.\n";
655 return false;
656 }
657 string line;
658 if (getline(in, line), line.empty())
659 return false;
660
661 if (width == 0) { // we can split by spaces
662 vector<string> list = Core::split(line, ' ');
663 for (auto& k : list) {
664 if (cnt >= n) {
665 cout << "Too many variables read in. File may be inconsistent. "
666 << cnt << " of " << n << endl;
667 return false;
668 }
669 // Read in lower half matrix
670 m_density(i, j) = Core::lexicalCast<double>(k, ok);
671 if (ok) { // Valid double converted, carry on
672 ++j;
673 ++cnt;
674 if (j == f) {
675 // We need to move down to the next row and increment f - lower tri
676 j = 0;
677 ++f;
678 ++i;
679 }
680 } else { // Invalid conversion of a string to double
681 cout << "Warning: problem converting string to double: " << k
682 << "\nIn GaussianFchk::readDensityMatrix.\n";
683 return false;
684 }
685 }
686 } else { // Q-Chem files use 16-character fields
687 size_t maxColumns = 80 / width;
688 for (size_t c = 0; c < maxColumns; ++c) {
689 string substring = line.substr(c * width, width);
690 if (static_cast<int>(substring.length()) != width) {
691 break;
692 } else if (cnt >= n) {
693 cout << "Too many variables read in. File may be inconsistent. "
694 << cnt << " of " << n << endl;
695 return false;
696 }
697 // Read in lower half matrix
698 m_density(i, j) = Core::lexicalCast<double>(substring, ok);
699 if (ok) { // Valid double converted, carry on
700 ++j;
701 ++cnt;
702 if (j == f) {
703 // We need to move down to the next row and increment f - lower tri
704 j = 0;
705 ++f;
706 ++i;
707 }
708 } else { // Invalid conversion of a string to double
709 cout << "Warning: problem converting string to double: " << substring
710 << "\nIn GaussianFchk::readDensityMatrix.\n";
711 return false;
712 }
713 }
714 }
715 }
716 return true;
717 }
718 bool GaussianFchk::readSpinDensityMatrix(std::istream& in, unsigned int n,
719 int width)
720 {
721 // This function reads in the lower triangular density matrix
722 if (n == 0)
723 return false;
724 if (n > kMaxFchkArrayEntries) {
725 appendError("Spin density matrix exceeds supported size.");
726 return false;
727 }
728 if (m_numBasisFunctions <= 0) {
729 appendError("Invalid basis function count.");
730 return false;
731 }
732 const size_t basis = static_cast<size_t>(m_numBasisFunctions);
733 const size_t maxSize = std::numeric_limits<size_t>::max();
734 if (basis > 0 && basis > maxSize / basis) {
735 appendError("Spin density matrix exceeds supported size.");
736 return false;
737 }
738 const size_t fullCount = basis * basis;
739 if (fullCount > kMaxFchkMatrixElements) {
740 appendError("Spin density matrix exceeds supported size.");
741 return false;
742 }
743 if (basis > 0 && basis > maxSize / (basis + 1)) {
744 appendError("Spin density matrix exceeds supported size.");
745 return false;
746 }
747 const size_t expectedLower = basis * (basis + 1) / 2;
748 if (static_cast<size_t>(n) > expectedLower) {
749 appendError("Invalid spin density matrix size.");
750 return false;
751 }
752 const size_t minBytesPerEntry = width > 0 ? static_cast<size_t>(width) : 1ull;
753 if (minBytesPerEntry > 0 &&
754 static_cast<size_t>(n) > maxSize / minBytesPerEntry) {
755 appendError("Spin density matrix exceeds supported size.");
756 return false;
757 }
758 if (!hasMinimumRemainingBytes(in,
759 static_cast<size_t>(n) * minBytesPerEntry)) {
760 appendError("Invalid spin density matrix data.");
761 return false;
762 }
763 m_spinDensity.resize(m_numBasisFunctions, m_numBasisFunctions);
764 unsigned int cnt = 0;
765 unsigned int i = 0, j = 0;
766 unsigned int f = 1;
767 bool ok = false;
768 while (cnt < n) {
769 if (in.eof()) {
770 cout << "GaussianFchk::readSpinDensityMatrix could not read all elements "
771 << n << " expected " << cnt << " parsed.\n";
772 return false;
773 }
774 string line;
775 if (getline(in, line), line.empty())
776 return false;
777
778 if (width == 0) { // we can split by spaces
779 vector<string> list = Core::split(line, ' ');
780 for (auto& k : list) {
781 if (cnt >= n) {
782 cout << "Too many variables read in. File may be inconsistent. "
783 << cnt << " of " << n << endl;
784 return false;
785 }
786 // Read in lower half matrix
787 m_spinDensity(i, j) = Core::lexicalCast<double>(k, ok);
788 if (ok) { // Valid double converted, carry on
789 ++j;
790 ++cnt;
791 if (j == f) {
792 // We need to move down to the next row and increment f - lower tri
793 j = 0;
794 ++f;
795 ++i;
796 }
797 } else { // Invalid conversion of a string to double
798 cout << "Warning: problem converting string to double: " << k
799 << "\nIn GaussianFchk::readDensityMatrix.\n";
800 return false;
801 }
802 }
803 } else { // Q-Chem files use 16-character fields
804 size_t maxColumns = 80 / width;
805 for (size_t c = 0; c < maxColumns; ++c) {
806 string substring = line.substr(c * width, width);
807 if (static_cast<int>(substring.length()) != width) {
808 break;
809 } else if (cnt >= n) {
810 cout << "Too many variables read in. File may be inconsistent. "
811 << cnt << " of " << n << endl;
812 return false;
813 }
814 // Read in lower half matrix
815 m_spinDensity(i, j) = Core::lexicalCast<double>(substring, ok);
816 if (ok) { // Valid double converted, carry on
817 ++j;
818 ++cnt;
819 if (j == f) {
820 // We need to move down to the next row and increment f - lower tri
821 j = 0;
822 ++f;
823 ++i;
824 }
825 } else { // Invalid conversion of a string to double
826 cout << "Warning: problem converting string to double: " << substring
827 << "\nIn GaussianFchk::readSpinDensityMatrix.\n";
828 return false;
829 }
830 }
831 }
832 }
833 return true;
834 }
835
836 void GaussianFchk::outputAll()
837 {
838 switch (m_scftype) {
839 case Rhf:
840 cout << "SCF type = RHF\n";
841 break;
842 case Uhf:
843 cout << "SCF type = UHF\n";
844 break;
845 case Rohf:
846 cout << "SCF type = ROHF\n";
847 break;
848 default:
849 cout << "SCF type = Unknown\n";
850 }
851 cout << "Shell mappings:\n";
852 for (unsigned int i = 0; i < m_shellTypes.size(); ++i)
853 cout << i << " : type = " << m_shellTypes.at(i)
854 << ", number = " << m_shellNums.at(i)
855 << ", atom = " << m_shelltoAtom.at(i) << endl;
856 if (m_MOcoeffs.size()) {
857 cout << "MO coefficients:\n";
858 for (double m_MOcoeff : m_MOcoeffs)
859 cout << m_MOcoeff << "\t";
860 cout << endl << endl;
861 }
862 if (m_alphaMOcoeffs.size()) {
863 cout << "Alpha MO coefficients:\n";
864 for (double m_alphaMOcoeff : m_alphaMOcoeffs)
865 cout << m_alphaMOcoeff << "\t";
866 cout << endl << endl;
867 }
868 if (m_betaMOcoeffs.size()) {
869 cout << "Beta MO coefficients:\n";
870 for (double m_betaMOcoeff : m_betaMOcoeffs)
871 cout << m_betaMOcoeff << "\t";
872 cout << endl << endl;
873 }
874 }
875 } // namespace Avogadro::QuantumIO