Debian Codegraph @

avogadro/core/internalcoordinates.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 "internalcoordinates.h"
7 #include "matrix.h"
8
9 #include <cmath>
10
11 namespace Avogadro::Core {
12
13 Array<Vector3> internalToCartesian(
14 const Molecule& molecule, const Array<InternalCoordinate>& internalCoords)
15 {
16 Array<Vector3> coords(molecule.atomCount());
17 Vector3 ab(0.0, 0.0, 0.0);
18 Vector3 bc(0.0, 0.0, 0.0);
19
20 for (Index i = 0; i < molecule.atomCount(); ++i) {
21 Real sinTheta, cosTheta, sinPhi, cosPhi;
22 Real length = internalCoords[i].length;
23 Real angle = internalCoords[i].angle;
24 Real dihedral = internalCoords[i].dihedral;
25 // Index i represents the current atom
26 Index a = internalCoords[i].a; // i will be some distance to a
27 Index b = internalCoords[i].b; // i-a-b is an angle
28 Index c = internalCoords[i].c; // i-a-b-c is a dihedral
29
30 switch (i) {
31 case 0:
32 coords[i] = Vector3(0.0, 0.0, 0.0);
33 break;
34 case 1:
35 coords[i] = Vector3(length, 0.0, 0.0);
36 break;
37 case 2: {
38 sinTheta = std::sin(angle * DEG_TO_RAD);
39 cosTheta = std::cos(angle * DEG_TO_RAD);
40 ab = (coords[b] - coords[a]).normalized();
41
42 // We want to place atom i at distance 'length' from atom a
43 // at angle 'angle' from the a-b direction
44
45 // Perpendicular to ab in the xy-plane
46 Vector3 perpendicular(-ab.y(), ab.x(), 0.0);
47 if (perpendicular.norm() > 1e-6) {
48 perpendicular.normalize();
49 } else {
50 // ab is along z-axis, use x-axis as perpendicular
51 perpendicular = Vector3(1.0, 0.0, 0.0);
52 }
53
54 // Place atom i: start from a, extend in direction
55 // that makes angle with ab
56 coords[i] =
57 coords[a] + length * (cosTheta * ab + sinTheta * perpendicular);
58 break;
59 }
60 default:
61 // NeRF formula
62 // see J. Comp. Chem. Vol. 26, No. 10, p. 1063-1068 (2005)
63 // https://doi.org/10.1002/jcc.20237
64 sinTheta = std::sin(angle * DEG_TO_RAD);
65 cosTheta = std::cos(angle * DEG_TO_RAD);
66 sinPhi = std::sin(dihedral * DEG_TO_RAD);
67 cosPhi = std::cos(dihedral * DEG_TO_RAD);
68
69 // Place atom i relative to atoms a, b, c
70 // - i bonds to a at distance 'length'
71 // - angle at a between i-a-b is 'angle'
72 // - dihedral i-a-b-c is 'dihedral'
73
74 // Vector from a to b (the bond direction for angle reference)
75 ab = (coords[b] - coords[a]).normalized();
76
77 // Vector from b to c (needed for dihedral plane)
78 bc = (coords[c] - coords[b]).normalized();
79
80 // Normal to the plane defined by a-b-c
81 Vector3 n = ab.cross(bc);
82 Real n_norm = n.norm();
83
84 if (n_norm > 1e-10) {
85 n.normalize();
86 } else {
87 // Atoms a, b, c are collinear - choose arbitrary perpendicular
88 // Find a vector perpendicular to ab
89 if (std::abs(ab.x()) < 0.9) {
90 n = Vector3(1.0, 0.0, 0.0).cross(ab).normalized();
91 } else {
92 n = Vector3(0.0, 1.0, 0.0).cross(ab).normalized();
93 }
94 }
95
96 // Vector perpendicular to both ab and n
97 // (in the plane perpendicular to ab)
98 Vector3 n_perp = n.cross(ab);
99
100 // Local coordinate system at atom a:
101 // - ab direction: along the a-b bond (reference for angle)
102 // - n_perp direction: perpendicular to ab, in plane for 0° dihedral
103 // - n direction: perpendicular to ab, for rotating out of plane
104
105 // Position in local frame using NeRF formula (page 1066, eq. 2)
106 // We place atom i relative to atom a
107 // The angle is measured from the ab direction
108 // The dihedral rotates around the ab axis
109 Vector3 localPos(length * cosTheta, length * sinTheta * cosPhi,
110 length * sinTheta * sinPhi);
111
112 // Build rotation matrix with columns [ab, n_perp, n]
113 Matrix3 m;
114 m << ab, n_perp, n;
115
116 // Transform to global coordinates and translate to atom a
117 coords[i] = m * localPos + coords[a];
118 break;
119 }
120 }
121
122 return coords;
123 }
124
125 // Helper structure to store the connectivity tree
126 struct ConnectivityTree
127 {
128 Array<Index> parent; // parent[i] = atom that i bonds to (atom a)
129 Array<Index> grandparent; // grandparent[i] = parent's parent (atom b)
130 Array<Index>
131 greatgrandparent; // greatgrandparent[i] = grandparent's parent (atom c)
132 };
133
134 // Build a spanning tree of the molecule using BFS
135 // Handles disconnected fragments by building a separate tree for each component
136 ConnectivityTree buildConnectivityTree(const Molecule& molecule)
137 {
138 Index atomCount = molecule.atomCount();
139 ConnectivityTree tree;
140 tree.parent.resize(atomCount);
141 tree.grandparent.resize(atomCount);
142 tree.greatgrandparent.resize(atomCount);
143
144 // Initialize all to -1 (invalid index)
145 for (Index i = 0; i < atomCount; ++i) {
146 tree.parent[i] = static_cast<Index>(-1);
147 tree.grandparent[i] = static_cast<Index>(-1);
148 tree.greatgrandparent[i] = static_cast<Index>(-1);
149 }
150
151 // Get connected components from the molecule's graph
152 const Graph& graph = molecule.graph();
153 std::vector<std::set<size_t>> components = graph.connectedComponents();
154
155 // Process each connected component separately
156 for (const auto& component : components) {
157 if (component.empty())
158 continue;
159
160 // Pick the first atom in this component as root
161 Index root = *component.begin();
162
163 // BFS from this root
164 std::vector<bool> visited(atomCount, false);
165 std::vector<Index> queue;
166 queue.push_back(root);
167 visited[root] = true;
168
169 while (!queue.empty()) {
170 Index current = queue.front();
171 queue.erase(queue.begin());
172
173 // Get neighbors from the graph
174 std::vector<size_t> neighborIndices = graph.neighbors(current);
175
176 for (Index neighbor : neighborIndices) {
177 if (!visited[neighbor]) {
178 visited[neighbor] = true;
179 tree.parent[neighbor] = current;
180
181 // Set grandparent if parent has a parent
182 if (tree.parent[current] != static_cast<Index>(-1)) {
183 tree.grandparent[neighbor] = tree.parent[current];
184
185 // Set great-grandparent if grandparent has a parent
186 Index grandparentIdx = tree.parent[current];
187 if (tree.parent[grandparentIdx] != static_cast<Index>(-1)) {
188 tree.greatgrandparent[neighbor] = tree.parent[grandparentIdx];
189 }
190 }
191
192 queue.push_back(neighbor);
193 }
194 }
195 }
196 }
197
198 return tree;
199 }
200
201 Array<InternalCoordinate> cartesianToInternal(const Molecule& molecule)
202 {
203 Array<InternalCoordinate> internalCoords(molecule.atomCount());
204
205 if (molecule.atomCount() < 1)
206 return internalCoords;
207
208 // Build connectivity tree using the molecule's graph
209 ConnectivityTree tree = buildConnectivityTree(molecule);
210
211 // Convert each atom to internal coordinates based on tree
212 for (Index i = 0; i < molecule.atomCount(); ++i) {
213 InternalCoordinate coord;
214 coord.a = tree.parent[i];
215 coord.b = tree.grandparent[i];
216 coord.c = tree.greatgrandparent[i];
217
218 if (tree.parent[i] == static_cast<Index>(-1)) {
219 // Root of a fragment - place at origin
220 coord.length = 0.0;
221 coord.angle = 0.0;
222 coord.dihedral = 0.0;
223 } else {
224 // Calculate distance from i to parent (atom a)
225 Vector3 vec_i_to_a = molecule.atom(tree.parent[i]).position3d() -
226 molecule.atom(i).position3d();
227 coord.length = vec_i_to_a.norm();
228
229 if (tree.grandparent[i] == static_cast<Index>(-1)) {
230 // Second atom in fragment - has distance only
231 coord.angle = 0.0;
232 coord.dihedral = 0.0;
233 } else {
234 // Calculate angle i-a-b (at atom a, between i-a and a-b bonds)
235 Index a = tree.parent[i];
236 Index b = tree.grandparent[i];
237
238 Vector3 vec_a_to_i = -vec_i_to_a; // from a to i
239 Vector3 vec_a_to_b =
240 molecule.atom(b).position3d() - molecule.atom(a).position3d();
241
242 Real dot = vec_a_to_i.dot(vec_a_to_b);
243 Real len_product = vec_a_to_i.norm() * vec_a_to_b.norm();
244
245 if (len_product > 1e-8) {
246 Real cosAngle = dot / len_product;
247 // Clamp to avoid numerical issues with acos
248 cosAngle = std::clamp(cosAngle, -1.0, 1.0);
249 coord.angle = std::acos(cosAngle) * RAD_TO_DEG;
250 } else {
251 coord.angle = 0.0;
252 }
253
254 if (tree.greatgrandparent[i] == static_cast<Index>(-1)) {
255 // Third atom in fragment - has distance and angle only
256 coord.dihedral = 0.0;
257 } else {
258 // Calculate dihedral i-a-b-c
259 Index c = tree.greatgrandparent[i];
260
261 Vector3 p_i = molecule.atom(i).position3d();
262 Vector3 p_a = molecule.atom(a).position3d();
263 Vector3 p_b = molecule.atom(b).position3d();
264 Vector3 p_c = molecule.atom(c).position3d();
265
266 // Vectors along bonds
267 Vector3 b1 = p_a - p_i; // i -> a
268 Vector3 b2 = p_b - p_a; // a -> b
269 Vector3 b3 = p_c - p_b; // b -> c
270
271 // Normals to planes
272 Vector3 n1 = b1.cross(b2); // plane containing i-a-b
273 Vector3 n2 = b2.cross(b3); // plane containing a-b-c
274
275 Real n1_norm = n1.norm();
276 Real n2_norm = n2.norm();
277
278 if (n1_norm > 1e-8 && n2_norm > 1e-8) {
279 n1 = n1 / n1_norm;
280 n2 = n2 / n2_norm;
281
282 Real cos_dihedral = n1.dot(n2);
283 // Clamp to avoid numerical issues
284 cos_dihedral = std::clamp(cos_dihedral, -1.0, 1.0);
285
286 // Determine sign using triple product
287 Real sign = (n1.cross(n2)).dot(b2);
288
289 coord.dihedral = std::acos(cos_dihedral) * RAD_TO_DEG;
290 if (sign < 0) {
291 coord.dihedral = -coord.dihedral;
292 }
293 } else {
294 // Atoms are collinear
295 coord.dihedral = 0.0;
296 }
297 }
298 }
299 }
300
301 internalCoords[i] = coord;
302 }
303
304 return internalCoords;
305 }
306
307 } // end namespace Avogadro::Core