Debian Codegraph @

avogadro/core/angleiterator.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 "angleiterator.h"
7
8 #include <avogadro/core/graph.h>
9 #include <avogadro/core/molecule.h>
10
11 namespace Avogadro::Core {
12
13 AngleIterator::AngleIterator(const Molecule* mol)
14 : m_a(MaxIndex), m_b(0), m_c(MaxIndex), m_mol(mol)
15 {
16 }
17
18 Angle AngleIterator::begin()
19 {
20 return ++(*this);
21 }
22
23 Angle AngleIterator::operator++()
24 {
25 // never any angles
26 if (m_mol == nullptr || m_mol->atomCount() < 3 || m_mol->bondCount() < 2)
27 return std::make_tuple(MaxIndex, MaxIndex, MaxIndex);
28
29 Graph graph = m_mol->graph();
30 Index count = m_mol->atomCount();
31
32 // true if we have a valid current state
33 // (i.e. false at the start since a == b == c)
34 bool valid = (m_a != MaxIndex && m_c != MaxIndex);
35 Index aIndex = MaxIndex;
36 Index cIndex = MaxIndex;
37
38 // if we don't have a valid state, try to find an initial angle
39 if (!valid) {
40 for (Index i = 0; i < count; ++i) {
41 const auto& neighbors = graph.neighbors(i);
42 if (neighbors.size() < 2)
43 continue;
44
45 m_b = i;
46 m_a = 0;
47 m_c = 1;
48 aIndex = neighbors[m_a];
49 cIndex = neighbors[m_c];
50 valid = true;
51 break;
52 }
53 } else {
54 // we have a valid state, try to find the next angle
55 const auto& neighbors = graph.neighbors(m_b);
56 // first check if we can increment m_c
57 if (m_c + 1 < neighbors.size()) {
58 ++m_c;
59 aIndex = neighbors[m_a];
60 cIndex = neighbors[m_c];
61 } else {
62 // we can't increment m_c, try to increment m_a
63 if (m_a < neighbors.size() - 2) {
64 ++m_a;
65 m_c = m_a + 1;
66 aIndex = neighbors[m_a];
67 cIndex = neighbors[m_c];
68 } else {
69 // we can't increment m_a, try to increment m_b
70 // and reset m_a and m_c
71 valid = false;
72 for (Index i = m_b + 1; i < count; ++i) {
73 const auto& newNeighbors = graph.neighbors(i);
74 if (newNeighbors.size() < 2)
75 continue;
76
77 m_b = i;
78 m_a = 0;
79 m_c = 1;
80 aIndex = newNeighbors[m_a];
81 cIndex = newNeighbors[m_c];
82 valid = true;
83 break;
84 }
85 }
86 }
87 }
88
89 if (valid) {
90 m_current = std::make_tuple(aIndex, m_b, cIndex);
91 } else // no more valid angles
92 m_current = std::make_tuple(MaxIndex, MaxIndex, MaxIndex);
93
94 return m_current;
95 } // end ++ operator
96
97 } // namespace Avogadro::Core