Debian Codegraph @

avogadro/core/spacegroups.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 "spacegroups.h"
7
8 #include "crystaltools.h"
9 #include "molecule.h"
10 #include "spacegroupdata.h"
11 #include "unitcell.h"
12 #include "utilities.h"
13
14 #include <algorithm> // for std::count()
15 #include <cassert>
16 #include <cctype> // for isdigit()
17 #include <cmath> // for floor()
18 #include <iostream>
19 #include <vector>
20
21 namespace Avogadro::Core {
22
23 unsigned short SpaceGroups::hallNumber(const std::string& spaceGroup)
24 {
25 unsigned short hall = 0; // can't find anything
26 const unsigned short hall_count = 531; // 530 but first one is empty
27 // some files use " instead of = for the space group symbol
28 std::string sg = spaceGroup;
29 std::replace(sg.begin(), sg.end(), '"', '=');
30
31 // space_group_hall_symbol
32 for (unsigned short i = 0; i < hall_count; ++i) {
33 if (sg == space_group_hall_symbol[i]) {
34 return i; // found a match
35 }
36 }
37
38 // space_group_international
39 for (unsigned short i = 0; i < hall_count; ++i) {
40 if (sg == space_group_international[i]) {
41 return i; // found a match
42 }
43 }
44
45 // space_group_international_short
46 for (unsigned short i = 0; i < hall_count; ++i) {
47 if (sg == space_group_international_short[i]) {
48 return i; // found a match
49 }
50 }
51
52 // space_group_international_full
53 for (unsigned short i = 0; i < hall_count; ++i) {
54 if (sg == space_group_international_full[i]) {
55 return i; // found a match
56 }
57 }
58
59 return hall; // can't find anything
60 }
61
62 CrystalSystem SpaceGroups::crystalSystem(unsigned short hallNumber)
63 {
64 if (hallNumber == 1 || hallNumber == 2)
65 return Triclinic;
66 if (hallNumber >= 3 && hallNumber <= 107)
67 return Monoclinic;
68 if (hallNumber >= 108 && hallNumber <= 348)
69 return Orthorhombic;
70 if (hallNumber >= 349 && hallNumber <= 429)
71 return Tetragonal;
72 if (hallNumber >= 430 && hallNumber <= 461) {
73 // 14 of these are rhombohedral and the rest are trigonal
74 switch (hallNumber) {
75 case 433:
76 case 434:
77 case 436:
78 case 437:
79 case 444:
80 case 445:
81 case 450:
82 case 451:
83 case 452:
84 case 453:
85 case 458:
86 case 459:
87 case 460:
88 case 461:
89 return Rhombohedral;
90 default:
91 return Trigonal;
92 }
93 }
94 if (hallNumber >= 462 && hallNumber <= 488)
95 return Hexagonal;
96 if (hallNumber >= 489 && hallNumber <= 530)
97 return Cubic;
98 // hallNumber must be 0 or > 531
99 return None;
100 // for (unsigned short i = 0; i < hallNumberCount; ++i)
101 }
102
103 unsigned short SpaceGroups::internationalNumber(unsigned short hallNumber)
104 {
105 if (hallNumber <= 530)
106 return space_group_international_number[hallNumber];
107 else
108 return space_group_international_number[0];
109 }
110
111 const char* SpaceGroups::schoenflies(unsigned short hallNumber)
112 {
113 if (hallNumber <= 530)
114 return space_group_schoenflies[hallNumber];
115 else
116 return space_group_schoenflies[0];
117 }
118
119 const char* SpaceGroups::hallSymbol(unsigned short hallNumber)
120 {
121 if (hallNumber <= 530)
122 return space_group_hall_symbol[hallNumber];
123 else
124 return space_group_hall_symbol[0];
125 }
126
127 const char* SpaceGroups::international(unsigned short hallNumber)
128 {
129 if (hallNumber <= 530)
130 return space_group_international[hallNumber];
131 else
132 return space_group_international[0];
133 }
134
135 const char* SpaceGroups::internationalFull(unsigned short hallNumber)
136 {
137 if (hallNumber <= 530)
138 return space_group_international_full[hallNumber];
139 else
140 return space_group_international_full[0];
141 }
142
143 const char* SpaceGroups::internationalShort(unsigned short hallNumber)
144 {
145 if (hallNumber <= 530)
146 return space_group_international_short[hallNumber];
147 else
148 return space_group_international_short[0];
149 }
150
151 const char* SpaceGroups::setting(unsigned short hallNumber)
152 {
153 if (hallNumber <= 530)
154 return space_group_setting[hallNumber];
155 else
156 return space_group_setting[0];
157 }
158
159 unsigned short SpaceGroups::transformsCount(unsigned short hallNumber)
160 {
161 if (hallNumber <= 530) {
162 std::string s = transformsString(hallNumber);
163 return std::count(s.begin(), s.end(), ' ') + 1;
164 } else {
165 return 0;
166 }
167 }
168
169 Real readTransformCoordinate(const std::string& coordinate, const Vector3& v)
170 {
171 // The coordinate should be at least 1 character
172 assert(coordinate.size() != 0);
173
174 Real ret = 0.0;
175 Index i = 0;
176 while (i < coordinate.size()) {
177 bool isNeg = false;
178 if (coordinate[i] == '-') {
179 isNeg = true;
180 ++i;
181 assert(i < coordinate.size());
182 }
183 // We assume we are adding, so no need for a boolean here
184 else if (coordinate[i] == '+') {
185 ++i;
186 assert(i < coordinate.size());
187 }
188
189 // Check to see if we have a digit
190 if (isdigit(coordinate[i])) {
191 // We SHOULD have a fraction. Also, we SHOULD only deal with single
192 // digit numbers. Add assertions to make sure this is the case.
193 assert(i + 2 < coordinate.size());
194 assert(coordinate[i + 1] == '/');
195 assert(isdigit(coordinate[i + 2]));
196 // Assert that this is a single digit number
197 if (coordinate.size() > i + 3)
198 assert(!isdigit(coordinate[i + 3]));
199 // Ancient methods used by our forefathers to cast a char to an int
200 Real numerator = coordinate[i] - '0';
201 Real denominator = coordinate[i + 2] - '0';
202 Real fraction = numerator / denominator;
203 fraction *= (isNeg) ? -1.0 : 1.0;
204
205 ret += fraction;
206 i += 3;
207 } else if (coordinate[i] == 'x') {
208 ret += (isNeg) ? -1.0 * v[0] : v[0];
209 ++i;
210 } else if (coordinate[i] == 'y') {
211 ret += (isNeg) ? -1.0 * v[1] : v[1];
212 ++i;
213 } else if (coordinate[i] == 'z') {
214 ret += (isNeg) ? -1.0 * v[2] : v[2];
215 ++i;
216 } else {
217 std::cerr << "In " << __FUNCTION__ << ", error reading string: '"
218 << coordinate << "'\n";
219 return 0;
220 }
221 }
222 return ret;
223 }
224
225 Vector3 getSingleTransform(const std::string& transform, const Vector3& v)
226 {
227 Vector3 ret;
228 std::vector<std::string> coordinates = split(transform, ',');
229
230 // This should be 3 in size. Something very bad happened if it is not.
231 assert(coordinates.size() == 3);
232
233 ret[0] = readTransformCoordinate(coordinates[0], v);
234 ret[1] = readTransformCoordinate(coordinates[1], v);
235 ret[2] = readTransformCoordinate(coordinates[2], v);
236 return ret;
237 }
238
239 Array<Vector3> SpaceGroups::getTransforms(unsigned short hallNumber,
240 const Vector3& v)
241 {
242 if (hallNumber == 0 || hallNumber > 530)
243 return Array<Vector3>();
244
245 Array<Vector3> ret;
246
247 std::string transformsStr = transformsString(hallNumber);
248 // These transforms are separated by spaces
249 std::vector<std::string> transforms = split(transformsStr, ' ');
250
251 for (auto& transform : transforms)
252 ret.push_back(getSingleTransform(transform, v));
253
254 return ret;
255 }
256
257 void SpaceGroups::fillUnitCell(Molecule& mol, unsigned short hallNumber,
258 double cartTol, bool wrapToCell, bool allCopies)
259 {
260 if (!mol.unitCell())
261 return;
262 UnitCell* uc = mol.unitCell();
263
264 Array<unsigned char> atomicNumbers = mol.atomicNumbers();
265 Array<Vector3> positions = mol.atomPositions3d();
266 Index numAtoms = mol.atomCount();
267
268 // We are going to loop through the original atoms. That is why
269 // we have numAtoms cached instead of using atomCount().
270 for (Index i = 0; i < numAtoms; ++i) {
271 unsigned char atomicNum = atomicNumbers[i];
272 Vector3 pos = uc->toFractional(positions[i]);
273
274 Array<Vector3> newAtoms = getTransforms(hallNumber, pos);
275
276 // We skip 0 because it is the original atom.
277 for (Index j = 1; j < newAtoms.size(); ++j) {
278 // The new atoms are in fractional coordinates. Convert to cartesian.
279 Vector3 newCandidate = uc->toCartesian(newAtoms[j]);
280 // if we are wrapping to the cell, we need to wrap the new atom
281 if (wrapToCell)
282 newCandidate = uc->wrapCartesian(newCandidate);
283
284 // If there is already any atom in this location within a
285 // certain tolerance, do not add the atom.
286 bool atomAlreadyPresent = false;
287 for (Index k = 0; k < mol.atomCount(); k++) {
288 Real distance = uc->distance(mol.atomPosition3d(k), newCandidate);
289 if (distance <= cartTol) {
290 atomAlreadyPresent = true;
291 break; // no need to keep looking
292 }
293 }
294
295 // If there is already an atom present here, just continue
296 if (atomAlreadyPresent)
297 continue;
298
299 // If we got this far, add the atom!
300 Atom newAtom = mol.addAtom(atomicNum);
301 newAtom.setPosition3d(newCandidate);
302 }
303 }
304
305 // Now we generate any copies on the unit boundary
306 if (allCopies)
307 fillTranslationalCopies(mol, cartTol);
308 else {
309 // Remove atoms with fractional coordinates near 1.0 only if a
310 // translational duplicate exists near 0.0 (same element, wrapped
311 // fractional coords within tolerance). If no duplicate exists, wrap
312 // the coordinate to 0.0 instead of deleting.
313 const double fracTol = 0.001;
314 std::vector<Index> toRemove;
315 for (Index i = 0; i < mol.atomCount(); ++i) {
316 Vector3 frac = uc->toFractional(mol.atomPositions3d()[i]);
317 bool nearBoundary = false;
318 for (Index j = 0; j < 3; ++j) {
319 if (std::abs(frac[j] - 1.0) < fracTol) {
320 nearBoundary = true;
321 break;
322 }
323 }
324 if (!nearBoundary)
325 continue;
326
327 // Build the wrapped version (1.0 -> 0.0)
328 Vector3 wrapped = frac;
329 for (Index j = 0; j < 3; ++j) {
330 if (std::abs(wrapped[j] - 1.0) < fracTol)
331 wrapped[j] = 0.0;
332 }
333 Vector3 wrappedCart = uc->toCartesian(wrapped);
334
335 // Check if a different atom of the same element exists at the
336 // wrapped position
337 bool hasDuplicate = false;
338 unsigned char atomicNum = mol.atomicNumber(i);
339 for (Index k = 0; k < mol.atomCount(); ++k) {
340 if (k == i)
341 continue;
342 if (mol.atomicNumber(k) != atomicNum)
343 continue;
344 if (uc->distance(mol.atomPosition3d(k), wrappedCart) < cartTol) {
345 hasDuplicate = true;
346 break;
347 }
348 }
349
350 if (hasDuplicate)
351 toRemove.push_back(i);
352 else
353 mol.setAtomPosition3d(i, wrappedCart); // wrap to 0.0
354 }
355 // Remove in reverse order so indices remain valid
356 for (auto it = toRemove.rbegin(); it != toRemove.rend(); ++it)
357 mol.removeAtom(*it);
358 }
359 }
360
361 void SpaceGroups::fillTranslationalCopies(Molecule& mol, double cartTol)
362 {
363 if (!mol.unitCell())
364 return;
365 UnitCell* uc = mol.unitCell();
366
367 Array<unsigned char> atomicNumbers = mol.atomicNumbers();
368 Array<Vector3> positions = mol.atomPositions3d();
369 Index numAtoms = mol.atomCount();
370 for (Index i = 0; i < numAtoms; ++i) {
371 unsigned char atomicNum = atomicNumbers[i];
372 Vector3 pos = uc->toFractional(positions[i]);
373
374 Array<Vector3> newAtoms;
375 // We need to check each coordinate to see if it is 0.0 or 1.0
376 // .. if so, we need to generate the symmetric copy
377 for (Index j = 0; j < 3; ++j) {
378 Vector3 newPos = pos;
379 if (fabs(pos[j]) < 0.001) {
380 newPos[j] = 1.0;
381 newAtoms.push_back(newPos);
382 }
383 if (fabs(pos[j] - 1.0) < 0.001) {
384 newPos[j] = 0.0;
385 newAtoms.push_back(newPos);
386 }
387
388 for (Index k = j + 1; k < 3; ++k) {
389 if (fabs(pos[k]) < 0.001) {
390 newPos[k] = 1.0;
391 newAtoms.push_back(newPos);
392 newPos[k] = 0.0; // revert for the other coords
393 }
394 if (fabs(pos[k] - 1.0) < 0.001) {
395 newPos[k] = 0.0;
396 newAtoms.push_back(newPos);
397 newPos[k] = 1.0; // revert
398 }
399 }
400 }
401 // finally, check if all coordinates are 0.0
402 if (fabs(pos[0]) < 0.001 && fabs(pos[1]) < 0.001 && fabs(pos[2]) < 0.001)
403 newAtoms.push_back(Vector3(1.0, 1.0, 1.0));
404 // or 1.0 .. unlikely, but possible
405 if (fabs(pos[0] - 1.0) < 0.001 && fabs(pos[1] - 1.0) < 0.001 &&
406 fabs(pos[2] - 1.0) < 0.001)
407 newAtoms.push_back(Vector3(0.0, 0.0, 0.0));
408
409 for (const auto& atomMat : newAtoms) {
410 // The new atoms are in fractional coordinates. Convert to cartesian.
411 Vector3 newCandidate = uc->toCartesian(atomMat);
412
413 // If there is already an atom in this location within a
414 // certain tolerance, do not add the atom.
415 bool atomAlreadyPresent = false;
416 Real cartTolSq = cartTol * cartTol;
417 for (Index k = 0; k < mol.atomCount(); k++) {
418 Real distSq = (mol.atomPosition3d(k) - newCandidate).squaredNorm();
419
420 if (distSq <= cartTolSq) {
421 atomAlreadyPresent = true;
422 break;
423 }
424 }
425
426 // If there is already an atom present here, just continue
427 if (atomAlreadyPresent)
428 continue;
429
430 // If we got this far, add the atom!
431 Atom newAtom = mol.addAtom(atomicNum);
432 newAtom.setPosition3d(newCandidate);
433 }
434 }
435 }
436
437 void SpaceGroups::reduceToAsymmetricUnit(Molecule& mol,
438 unsigned short hallNumber,
439 double cartTol)
440 {
441 if (!mol.unitCell())
442 return;
443 UnitCell* uc = mol.unitCell();
444
445 // The number of atoms may change as we remove atoms, so don't cache
446 // the number of atoms, atomic positions, or atomic numbers
447 // There's no point in looking at the last atom
448 for (Index i = 0; i + 1 < mol.atomCount(); ++i) {
449 unsigned char atomicNum = mol.atomicNumber(i);
450 Vector3 pos = uc->toFractional(mol.atomPosition3d(i));
451 Array<Vector3> transformAtoms = getTransforms(hallNumber, pos);
452
453 // Loop through the rest of the atoms in this crystal and see if any match
454 // up with a transform
455 for (Index j = i + 1; j < mol.atomCount(); ++j) {
456 // If the atomic number does not match, skip over it
457 if (mol.atomicNumber(j) != atomicNum)
458 continue;
459
460 Vector3 trialPos = mol.atomPosition3d(j);
461 // Loop through the transform atoms
462 // We skip 0 because it is the original atom.
463 for (Index k = 1; k < transformAtoms.size(); ++k) {
464 // The transform atoms are in fractional coordinates. Convert to
465 // cartesian.
466 Vector3 transformPos = uc->toCartesian(transformAtoms[k]);
467 Real distance = uc->distance(trialPos, transformPos);
468 // Is the atom within the cartesian tolerance distance?
469 if (distance <= cartTol) {
470 // Remove this atom and adjust the index
471 mol.removeAtom(j);
472 --j;
473 break;
474 }
475 }
476 }
477 }
478 }
479
480 Array<Index> SpaceGroups::translationalUniqueAtoms(const Molecule& mol,
481 double tolerance)
482 {
483 Array<Index> uniqueIndices;
484
485 if (!mol.unitCell())
486 return uniqueIndices;
487
488 const UnitCell* uc = mol.unitCell();
489 Index numAtoms = mol.atomCount();
490
491 // Store wrapped coordinates for atoms we've already accepted
492 std::vector<std::pair<unsigned char, Vector3>> accepted;
493
494 for (Index i = 0; i < numAtoms; ++i) {
495 unsigned char atomicNum = mol.atomicNumber(i);
496 Vector3 fracCoords = uc->toFractional(mol.atomPosition3d(i));
497
498 // Wrap coordinates to [0, 1) range for comparison
499 Vector3 wrappedCoords;
500 for (int c = 0; c < 3; ++c) {
501 double coord = fracCoords[c];
502 coord = coord - floor(coord);
503 if (coord > 1.0 - tolerance)
504 coord = 0.0;
505 wrappedCoords[c] = coord;
506 }
507
508 // Check if this is a duplicate of a previously accepted atom
509 bool isDuplicate = false;
510 for (const auto& prev : accepted) {
511 if (prev.first != atomicNum)
512 continue;
513
514 // Check if positions match within tolerance
515 if ((wrappedCoords - prev.second).norm() < tolerance) {
516 isDuplicate = true;
517 break;
518 }
519 }
520
521 if (!isDuplicate) {
522 uniqueIndices.push_back(i);
523 accepted.emplace_back(atomicNum, wrappedCoords);
524 }
525 }
526
527 return uniqueIndices;
528 }
529
530 const char* SpaceGroups::transformsString(unsigned short hallNumber)
531 {
532 if (hallNumber <= 530)
533 return space_group_transforms[hallNumber];
534 else
535 return "";
536 }
537
538 } // namespace Avogadro::Core