27 const Eigen::VectorXd& positions,
28 const std::vector<std::pair<int, int>>& bonds)
31 const Eigen::Index dof = positions.size();
32 if (dof < 6 || dof % 3 != 0 || !positions.allFinite())
return out;
33 const int n =
static_cast<int>(dof / 3);
34 std::vector<std::vector<int>> adjacent(
static_cast<std::size_t
>(n));
35 for (
const auto& [a, b]: bonds) {
36 if (a < 0 || b < 0 || a >= n || b >= n || a == b)
continue;
37 adjacent[
static_cast<std::size_t
>(a)].push_back(b);
38 adjacent[
static_cast<std::size_t
>(b)].push_back(a);
40 const auto atom = [&](
int i) {
41 return Eigen::Vector3d(positions.segment<3>(3 * i));
44 const auto side = [&](
int from,
int other) {
45 std::vector<char> seen(
static_cast<std::size_t
>(n), 0);
46 std::vector<int> stack{from};
47 seen[
static_cast<std::size_t
>(from)] = 1;
48 while (!stack.empty()) {
49 const int here = stack.back();
51 for (
const int next: adjacent[
static_cast<std::size_t
>(here)]) {
52 if (here == from && next == other)
continue;
53 if (seen[
static_cast<std::size_t
>(next)])
continue;
54 seen[
static_cast<std::size_t
>(next)] = 1;
55 stack.push_back(next);
60 std::vector<Eigen::VectorXd> columns;
61 for (
const auto& [a, b]: bonds) {
62 if (a < 0 || b < 0 || a >= n || b >= n || a == b)
continue;
63 std::vector<char> reached = side(a, b);
64 if (reached[
static_cast<std::size_t
>(b)])
continue;
66 for (
const char flag: reached)
71 const Eigen::Vector3d origin = atom(a);
72 Eigen::Vector3d axis = atom(b) - origin;
73 const double length = axis.norm();
74 if (!(length > 0.0))
continue;
76 Eigen::VectorXd direction = Eigen::VectorXd::Zero(dof);
78 for (
int i = 0; i < n; ++i) {
79 if (!reached[
static_cast<std::size_t
>(i)])
continue;
80 const Eigen::Vector3d arm = atom(i) - origin;
81 scale = std::max(scale, arm.norm());
82 direction.segment<3>(3 * i) = axis.cross(arm);
84 const double norm = direction.norm();
86 if (!(norm > std::numeric_limits<double>::epsilon() * dof * scale))
88 columns.push_back(direction / norm);
89 out.bonds.emplace_back(a, b);
91 out.directions.resize(dof,
static_cast<Eigen::Index
>(columns.size()));
92 for (std::size_t j = 0; j < columns.size(); ++j)
93 out.directions.col(
static_cast<Eigen::Index
>(j)) = columns[j];