Debian Codegraph @

avogadro/quantumio/gaussiancube.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 "gaussiancube.h"
7
8 #include <avogadro/core/cube.h>
9 #include <avogadro/core/molecule.h>
10 #include <avogadro/core/utilities.h>
11
12 #include <iomanip>
13 #include <iostream>
14 #include <limits>
15
16 namespace Avogadro::QuantumIO {
17
18 namespace {
19 constexpr int kMaxCubeDim = 1024;
20 constexpr int kMaxAtomCount = 1000000;
21 constexpr unsigned int kMaxCubeCount = 128;
22 constexpr size_t kMaxCubeValues = 64ull * 1024 * 1024; // 64M values
23 constexpr size_t kMaxTotalCubeValues = 128ull * 1024 * 1024; // 128M values
24
25 bool hasMinimumRemainingBytes(std::istream& in, size_t minBytes)
26 {
27 auto pos = in.tellg();
28 if (pos == std::streampos(-1))
29 return true;
30
31 in.clear();
32 in.seekg(0, std::ios::end);
33 auto end = in.tellg();
34 in.seekg(pos);
35 if (end == std::streampos(-1))
36 return true;
37
38 const size_t remaining = static_cast<size_t>(end - pos);
39 return remaining >= minBytes;
40 }
41 } // namespace
42
43 GaussianCube::GaussianCube() {}
44
45 GaussianCube::~GaussianCube() {}
46
47 std::vector<std::string> GaussianCube::fileExtensions() const
48 {
49 std::vector<std::string> extensions;
50 extensions.emplace_back("cube");
51 return extensions;
52 }
53
54 std::vector<std::string> GaussianCube::mimeTypes() const
55 {
56 return std::vector<std::string>();
57 }
58
59 bool GaussianCube::read(std::istream& in, Core::Molecule& molecule)
60 {
61 // Variables we will need
62 std::string line;
63 std::vector<std::string> list;
64
65 int nAtoms;
66 Vector3 min;
67 Vector3 spacing;
68 Vector3i dim;
69
70 // Gaussian Cube format is very specific
71
72 // Read and set name
73 if (!getline(in, line)) {
74 appendError("Invalid cube header.");
75 return false;
76 }
77 molecule.setData("name", line);
78
79 // Read and skip field title (we may be able to use this to setCubeType in the
80 // future)
81 if (!getline(in, line)) {
82 appendError("Invalid cube header.");
83 return false;
84 }
85
86 // Next line contains nAtoms and m_min
87 if (!(in >> nAtoms)) {
88 appendError("Invalid cube header.");
89 return false;
90 }
91 for (unsigned int i = 0; i < 3; ++i)
92 if (!(in >> min(i))) {
93 appendError("Invalid cube header.");
94 return false;
95 }
96 if (!getline(in, line)) { // capture newline before continuing
97 appendError("Invalid cube header.");
98 return false;
99 }
100
101 if (nAtoms == std::numeric_limits<int>::min()) {
102 appendError("Invalid atom count in cube file.");
103 return false;
104 }
105 const int atomCount = nAtoms < 0 ? -nAtoms : nAtoms;
106 if (atomCount > kMaxAtomCount) {
107 appendError("Invalid atom count in cube file.");
108 return false;
109 }
110
111 // Next 3 lines contains spacing and dim
112 for (unsigned int i = 0; i < 3; ++i) {
113 if (!getline(in, line)) {
114 appendError("Invalid cube header.");
115 return false;
116 }
117 line = Core::trimmed(line);
118 if (line.empty()) {
119 appendError("Invalid cube header.");
120 return false;
121 }
122 list = Core::split(line, ' ');
123 if (list.size() < 4) {
124 appendError("Invalid cube grid specification.");
125 return false;
126 }
127 dim(i) = Core::lexicalCast<int>(list[0]).value_or(0);
128 spacing(i) = Core::lexicalCast<double>(list[i + 1]).value_or(0.0);
129 if (dim(i) <= 0 || dim(i) > kMaxCubeDim) {
130 appendError("Invalid cube grid dimension.");
131 return false;
132 }
133 }
134
135 const size_t d0 = static_cast<size_t>(dim(0));
136 const size_t d1 = static_cast<size_t>(dim(1));
137 const size_t d2 = static_cast<size_t>(dim(2));
138 const size_t maxSize = std::numeric_limits<size_t>::max();
139 if (d0 == 0 || d1 == 0 || d2 == 0 || d0 > maxSize / d1 ||
140 d0 * d1 > maxSize / d2) {
141 appendError("Invalid cube data dimensions.");
142 return false;
143 }
144 const size_t valueCount = d0 * d1 * d2;
145 if (valueCount > kMaxCubeValues) {
146 appendError("Cube data exceeds supported size.");
147 return false;
148 }
149
150 // Geometry block
151 Vector3 pos;
152 for (int i = 0; i < atomCount; ++i) {
153 if (!getline(in, line)) {
154 appendError("Invalid cube atom data.");
155 return false;
156 }
157 line = Core::trimmed(line);
158 if (line.empty()) {
159 appendError("Invalid cube atom data.");
160 return false;
161 }
162 list = Core::split(line, ' ');
163 if (list.size() < 5) {
164 appendError("Invalid cube atom data.");
165 return false;
166 }
167 auto atomNum = Core::lexicalCast<short int>(list[0]).value_or(0);
168 Core::Atom a = molecule.addAtom(static_cast<unsigned char>(atomNum));
169 for (unsigned int j = 2; j < 5; ++j)
170 pos(j - 2) = Core::lexicalCast<double>(list[j]).value_or(0.0);
171 pos = pos * BOHR_TO_ANGSTROM;
172 a.setPosition3d(pos);
173 }
174
175 // If the nAtoms were negative there is another line before
176 // the data which is necessary, maybe contain 1 or more cubes
177 unsigned int nCubes = 1;
178 if (nAtoms < 0) {
179 if (!(in >> nCubes) || nCubes == 0) {
180 appendError("Invalid cube count.");
181 return false;
182 }
183 if (nCubes > kMaxCubeCount) {
184 appendError("Invalid cube count.");
185 return false;
186 }
187 if (valueCount > 0 && nCubes > kMaxTotalCubeValues / valueCount) {
188 appendError("Cube data exceeds supported size.");
189 return false;
190 }
191 std::vector<unsigned int> moList(nCubes);
192 for (unsigned int i = 0; i < nCubes; ++i)
193 if (!(in >> moList[i])) {
194 appendError("Invalid cube MO list.");
195 return false;
196 }
197 // clear buffer
198 if (!getline(in, line)) {
199 appendError("Invalid cube header.");
200 return false;
201 }
202 }
203
204 // Render molecule
205 molecule.perceiveBondsSimple();
206 molecule.perceiveBondOrders();
207
208 // Cube block, set limits and populate data
209 // min and spacing are in bohr units, convert to ANGSTROM
210 min *= BOHR_TO_ANGSTROM;
211 spacing *= BOHR_TO_ANGSTROM;
212
213 const size_t cubeCount = static_cast<size_t>(nCubes);
214 if (valueCount > 0 && cubeCount > maxSize / valueCount) {
215 appendError("Cube data exceeds supported size.");
216 return false;
217 }
218 if (!hasMinimumRemainingBytes(in, valueCount * cubeCount)) {
219 appendError("Invalid cube data.");
220 return false;
221 }
222
223 for (unsigned int i = 0; i < nCubes; ++i) {
224 // Get a cube object from molecule
225 Core::Cube* cube = molecule.addCube();
226 cube->setCubeType(Core::Cube::Type::FromFile);
227
228 cube->setLimits(min, dim, spacing);
229 auto* values = cube->data();
230 if (!values) {
231 appendError("Invalid cube data.");
232 return false;
233 }
234 if (values->size() != valueCount)
235 values->resize(valueCount);
236 for (size_t index = 0; index < valueCount; ++index) {
237 if (!(in >> (*values)[index])) {
238 appendError("Invalid cube data.");
239 return false;
240 }
241 }
242 if (!cube->setData(*values)) {
243 appendError("Invalid cube data.");
244 return false;
245 }
246 // clear buffer, if more than one cube
247 if (!getline(in, line) && i + 1 < nCubes) {
248 appendError("Invalid cube data.");
249 return false;
250 }
251 }
252
253 return true;
254 }
255
256 void writeFixedFloat(std::ostream& outStream, Real number)
257 {
258 outStream << std::setw(12) << std::fixed << std::right << std::setprecision(6)
259 << number;
260 }
261
262 void writeFixedInt(std::ostream& outStream, unsigned int number)
263 {
264 outStream << std::setw(5) << std::fixed << std::right << number;
265 }
266
267 bool GaussianCube::write(std::ostream& outStream, const Core::Molecule& mol)
268 {
269 if (mol.cubeCount() == 0)
270 return false; // no cubes to write
271
272 const Core::Cube* cube =
273 mol.cube(0); // eventually need to write all the cubes
274 Vector3 min = cube->min() * ANGSTROM_TO_BOHR;
275 Vector3 spacing = cube->spacing() * ANGSTROM_TO_BOHR;
276 Vector3i dim = cube->dimensions(); // number of points in each direction
277
278 // might be useful to use the 2nd line, but it's just a comment
279 // e.g. write out the cube type
280 outStream << "Gaussian Cube file generated by Avogadro.\n";
281 if (mol.data("name").toString().length())
282 outStream << mol.data("name").toString() << "\n";
283 else
284 outStream << "\n";
285
286 // Write out the number of atoms and the minimum coordinates
287 size_t numAtoms = mol.atomCount();
288 writeFixedInt(outStream, numAtoms);
289 writeFixedFloat(outStream, min[0]);
290 writeFixedFloat(outStream, min[1]);
291 writeFixedFloat(outStream, min[2]);
292 writeFixedInt(outStream, 1); // one value per point (i.e., not vector)
293 outStream << "\n";
294
295 // now write the size and spacing of the cube
296 writeFixedInt(outStream, dim[0]);
297 writeFixedFloat(outStream, spacing[0]);
298 writeFixedFloat(outStream, 0.0);
299 writeFixedFloat(outStream, 0.0);
300 outStream << "\n";
301
302 writeFixedInt(outStream, dim[1]);
303 writeFixedFloat(outStream, 0.0);
304 writeFixedFloat(outStream, spacing[1]);
305 writeFixedFloat(outStream, 0.0);
306 outStream << "\n";
307
308 writeFixedInt(outStream, dim[2]);
309 writeFixedFloat(outStream, 0.0);
310 writeFixedFloat(outStream, 0.0);
311 writeFixedFloat(outStream, spacing[2]);
312 outStream << "\n";
313
314 for (size_t i = 0; i < numAtoms; ++i) {
315 Core::Atom atom = mol.atom(i);
316 if (!atom.isValid()) {
317 appendError("Internal error: Atom invalid.");
318 return false;
319 }
320
321 writeFixedInt(outStream, static_cast<int>(atom.atomicNumber()));
322 writeFixedFloat(outStream, 0.0); // charge
323 writeFixedFloat(outStream, atom.position3d()[0] * ANGSTROM_TO_BOHR);
324 writeFixedFloat(outStream, atom.position3d()[1] * ANGSTROM_TO_BOHR);
325 writeFixedFloat(outStream, atom.position3d()[2] * ANGSTROM_TO_BOHR);
326 outStream << "\n";
327 }
328
329 // write the raw cube values
330 const std::vector<float>* values = cube->data();
331 for (unsigned int i = 0; i < values->size(); ++i) {
332 outStream << std::setw(13) << std::right << std::scientific
333 << std::setprecision(5) << (*values)[i];
334 if (i % 6 == 5)
335 outStream << "\n";
336 }
337
338 return true;
339 }
340
341 } // namespace Avogadro::QuantumIO