2 * This file is part of the GROMACS molecular simulation package.
4 * Copyright (c) 2009,2010,2011,2012,2013,2014,2015,2016,2017,2018,2019, by the GROMACS development team, led by
5 * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
6 * and including many others, as listed in the AUTHORS file in the
7 * top-level source directory and at http://www.gromacs.org.
9 * GROMACS is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public License
11 * as published by the Free Software Foundation; either version 2.1
12 * of the License, or (at your option) any later version.
14 * GROMACS is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with GROMACS; if not, see
21 * http://www.gnu.org/licenses, or write to the Free Software Foundation,
22 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24 * If you want to redistribute modifications to GROMACS, please
25 * consider that scientific software is very special. Version
26 * control is crucial - bugs must be traceable. We will be happy to
27 * consider code for inclusion in the official distribution, but
28 * derived work must not be called official GROMACS. Details are found
29 * in the README & COPYING files - if they are missing, get the
30 * official version at http://www.gromacs.org.
32 * To help us fund GROMACS development, we humbly ask that you cite
33 * the research papers on the package. Check out http://www.gromacs.org.
37 * Implements neighborhood searching for analysis (from nbsearch.h).
39 * High-level overview of the algorithm is at \ref page_analysisnbsearch.
42 * The grid implementation could still be optimized in several different ways:
43 * - A better heuristic for selecting the grid size or falling back to a
44 * simple all-pairs search.
45 * - A multi-level grid implementation could be used to be able to use small
46 * grids for short cutoffs with very inhomogeneous particle distributions
47 * without a memory cost.
49 * \author Teemu Murtola <teemu.murtola@gmail.com>
50 * \ingroup module_selection
62 #include "gromacs/math/functions.h"
63 #include "gromacs/math/vec.h"
64 #include "gromacs/pbcutil/pbc.h"
65 #include "gromacs/topology/block.h"
66 #include "gromacs/utility/arrayref.h"
67 #include "gromacs/utility/exceptions.h"
68 #include "gromacs/utility/gmxassert.h"
69 #include "gromacs/utility/mutex.h"
70 #include "gromacs/utility/stringutil.h"
81 * Computes the bounding box for a set of positions.
83 * \param[in] posCount Number of positions in \p x.
84 * \param[in] x Positions to compute the bounding box for.
85 * \param[out] origin Origin of the bounding box.
86 * \param[out] size Size of the bounding box.
88 void computeBoundingBox(int posCount, const rvec x[], rvec origin, rvec size)
91 copy_rvec(x[0], origin);
92 copy_rvec(x[0], maxBound);
93 for (int i = 1; i < posCount; ++i)
95 for (int d = 0; d < DIM; ++d)
97 if (origin[d] > x[i][d])
101 if (maxBound[d] < x[i][d])
103 maxBound[d] = x[i][d];
107 rvec_sub(maxBound, origin, size);
115 /********************************************************************
116 * Implementation class declarations
119 class AnalysisNeighborhoodSearchImpl
122 typedef AnalysisNeighborhoodPairSearch::ImplPointer PairSearchImplPointer;
123 typedef std::vector<PairSearchImplPointer> PairSearchList;
124 typedef std::vector<std::vector<int>> CellList;
126 explicit AnalysisNeighborhoodSearchImpl(real cutoff);
127 ~AnalysisNeighborhoodSearchImpl();
130 * Initializes the search with a given box and reference positions.
132 * \param[in] mode Search mode to use.
133 * \param[in] bXY Whether to use 2D searching.
134 * \param[in] excls Exclusions.
135 * \param[in] pbc PBC information.
136 * \param[in] positions Set of reference positions.
138 void init(AnalysisNeighborhood::SearchMode mode,
140 const t_blocka* excls,
142 const AnalysisNeighborhoodPositions& positions);
143 PairSearchImplPointer getPairSearch();
145 real cutoffSquared() const { return cutoff2_; }
146 bool usesGridSearch() const { return bGrid_; }
150 * Determines a suitable grid size and sets up the cells.
152 * \param[in] box Box vectors (should not have zero vectors).
153 * \param[in] bSingleCell If `true`, the corresponding dimension will
154 * be forced to use a single cell.
155 * \param[in] posCount Number of positions that will be put on the
157 * \returns `false` if grid search is not suitable.
159 bool initGridCells(const matrix box, bool bSingleCell[DIM], int posCount);
161 * Sets ua a search grid for a given box.
163 * \param[in] pbc Information about the box.
164 * \param[in] posCount Number of positions in \p x.
165 * \param[in] x Reference positions that will be put on the grid.
166 * \param[in] bForce If `true`, grid searching will be used if at all
167 * possible, even if a simple search might give better performance.
168 * \returns `false` if grid search is not suitable.
170 bool initGrid(const t_pbc& pbc, int posCount, const rvec x[], bool bForce);
172 * Maps a point into a grid cell.
174 * \param[in] x Point to map.
175 * \param[out] cell Fractional cell coordinates of \p x on the grid.
176 * \param[out] xout Coordinates to use.
178 * \p xout will be within the rectangular unit cell in dimensions where
179 * the grid is periodic. For other dimensions, both \p xout and
180 * \p cell can be outside the grid/unit cell.
182 void mapPointToGridCell(const rvec x, rvec cell, rvec xout) const;
184 * Calculates linear index of a grid cell.
186 * \param[in] cell Cell indices (must be within the grid).
187 * \returns Linear index of \p cell.
189 int getGridCellIndex(const ivec cell) const;
191 * Calculates linear index of a grid cell from fractional coordinates.
193 * \param[in] cell Cell indices (must be within the grid).
194 * \returns Linear index of \p cell.
196 int getGridCellIndex(const rvec cell) const;
198 * Adds an index into a grid cell.
200 * \param[in] cell Fractional cell coordinates into which \p i should
202 * \param[in] i Index to add.
204 * \p cell should satisfy the conditions that \p mapPointToGridCell()
207 void addToGridCell(const rvec cell, int i);
209 * Initializes a cell pair loop for a dimension.
211 * \param[in] centerCell Fractional cell coordiates of the particle
212 * for which pairs are being searched.
213 * \param[in,out] cell Current/initial cell to loop over.
214 * \param[in,out] upperBound Last cell to loop over.
215 * \param[in] dim Dimension to initialize in this call.
217 * Initializes `cell[dim]` and `upperBound[dim]` for looping over
218 * neighbors of a particle at position given by \p centerCell.
219 * If 'dim != ZZ`, `cell[d]` (`d > dim`) set the plane/row of cells
220 * for which the loop is initialized. The loop should then go from
221 * `cell[dim]` until `upperBound[dim]`, inclusive.
222 * `cell[d]` with `d < dim` or `upperBound[d]` with `d != dim` are not
223 * modified by this function.
225 * `cell` and `upperBound` may be outside the grid for periodic
226 * dimensions and need to be shifted separately: to simplify the
227 * looping, the range is always (roughly) symmetric around the value in
230 void initCellRange(const rvec centerCell, ivec cell, ivec upperBound, int dim) const;
232 * Computes the extent of the cutoff sphere on a particular cell edge.
234 * \param[in] centerCell Fractional cell coordiates of the particle
235 * for which pairs are being searched.
236 * \param[in] cell Current cell (for dimensions `>dim`).
237 * \param[in] dim Dimension to compute in this call.
238 * \returns Fractional extent of the cutoff sphere when looping
239 * over cells in dimension `dim`, for `cell[d]` (`d > dim`).
241 * Input parameters are as for initCellRange(), except that if `cell`
242 * is over a periodic boundary from `centerCell`, triclinic shifts
243 * should have been applied to `centerCell` X/Y components.
245 real computeCutoffExtent(RVec centerCell, const ivec cell, int dim) const;
247 * Advances cell pair loop to the next cell.
249 * \param[in] centerCell Fractional cell coordiates of the particle
250 * for which pairs are being searched.
251 * \param[in,out] cell Current (in)/next (out) cell in the loop.
252 * \param[in,out] upperBound Last cell in the loop for each dimension.
254 bool nextCell(const rvec centerCell, ivec cell, ivec upperBound) const;
256 * Calculates the index and shift of a grid cell during looping.
258 * \param[in] cell Unshifted cell index.
259 * \param[out] shift Shift to apply to get the periodic distance
260 * for distances between the cells.
261 * \returns Grid cell index corresponding to `cell`.
263 int shiftCell(const ivec cell, rvec shift) const;
265 //! Whether to try grid searching.
269 //! The cutoff squared.
271 //! Whether to do searching in XY plane only.
274 //! Number of reference points for the current frame.
276 //! Reference point positions.
278 //! Reference position exclusion IDs.
279 const int* refExclusionIds_;
280 //! Reference position indices (NULL if no indices).
281 const int* refIndices_;
283 const t_blocka* excls_;
287 //! Whether grid searching is actually used for the current positions.
289 //! false if the box is rectangular.
291 //! Whether the grid is periodic in a dimension.
293 //! Array for storing in-unit-cell reference positions.
294 std::vector<RVec> xrefAlloc_;
295 //! Origin of the grid (zero for periodic dimensions).
297 //! Size of a single grid cell.
299 //! Inverse of \p cellSize_. Zero for dimensions where grid is not used.
302 * Shift in cell coordinates (for triclinic boxes) in X when crossing
303 * the Z periodic boundary.
307 * Shift in cell coordinates (for triclinic boxes) in Y when crossing
308 * the Z periodic boundary.
312 * Shift in cell coordinates (for triclinic boxes) in X when crossing
313 * the Y periodic boundary.
316 //! Number of cells along each dimension.
318 //! Data structure to hold the grid cell contents.
321 Mutex createPairSearchMutex_;
322 PairSearchList pairSearchList_;
324 friend class AnalysisNeighborhoodPairSearchImpl;
326 GMX_DISALLOW_COPY_AND_ASSIGN(AnalysisNeighborhoodSearchImpl);
329 class AnalysisNeighborhoodPairSearchImpl
332 explicit AnalysisNeighborhoodPairSearchImpl(const AnalysisNeighborhoodSearchImpl& search) :
335 selfSearchMode_ = false;
337 testPositions_ = nullptr;
338 testExclusionIds_ = nullptr;
339 testIndices_ = nullptr;
343 clear_rvec(testcell_);
344 clear_ivec(currCell_);
345 clear_ivec(cellBound_);
349 //! Initializes a search to find reference positions neighboring \p x.
350 void startSearch(const AnalysisNeighborhoodPositions& positions);
351 //! Initializes a search to find reference position pairs.
352 void startSelfSearch();
353 //! Searches for the next neighbor.
354 template<class Action>
355 bool searchNext(Action action);
356 //! Initializes a pair representing the pair found by searchNext().
357 void initFoundPair(AnalysisNeighborhoodPair* pair) const;
358 //! Advances to the next test position, skipping any remaining pairs.
359 void nextTestPosition();
362 //! Clears the loop indices.
363 void reset(int testIndex);
364 //! Checks whether a reference positiong should be excluded.
365 bool isExcluded(int j);
367 //! Parent search object.
368 const AnalysisNeighborhoodSearchImpl& search_;
369 //! Whether we are searching for ref-ref pairs.
370 bool selfSearchMode_;
371 //! Number of test positions.
373 //! Reference to the test positions.
374 const rvec* testPositions_;
375 //! Reference to the test exclusion indices.
376 const int* testExclusionIds_;
377 //! Reference to the test position indices.
378 const int* testIndices_;
379 //! Number of excluded reference positions for current test particle.
381 //! Exclusions for current test particle.
383 //! Index of the currently active test position in \p testPositions_.
385 //! Stores test position during a pair loop.
387 //! Stores the previous returned position during a pair loop.
389 //! Stores the pair distance corresponding to previ_.
391 //! Stores the shortest distance vector corresponding to previ_.
393 //! Stores the current exclusion index during loops.
395 //! Stores the fractional test particle cell location during loops.
397 //! Stores the cell index corresponding to testcell_.
399 //! Stores the current cell during pair loops.
401 //! Stores the current loop upper bounds for each dimension during pair loops.
403 //! Stores the index within the current cell during pair loops.
406 GMX_DISALLOW_COPY_AND_ASSIGN(AnalysisNeighborhoodPairSearchImpl);
409 /********************************************************************
410 * AnalysisNeighborhoodSearchImpl
413 AnalysisNeighborhoodSearchImpl::AnalysisNeighborhoodSearchImpl(real cutoff)
419 cutoff_ = cutoff2_ = GMX_REAL_MAX;
424 cutoff2_ = gmx::square(cutoff_);
429 refExclusionIds_ = nullptr;
430 refIndices_ = nullptr;
431 std::memset(&pbc_, 0, sizeof(pbc_));
435 bGridPBC_[XX] = true;
436 bGridPBC_[YY] = true;
437 bGridPBC_[ZZ] = true;
439 clear_rvec(gridOrigin_);
440 clear_rvec(cellSize_);
441 clear_rvec(invCellSize_);
442 clear_ivec(ncelldim_);
445 AnalysisNeighborhoodSearchImpl::~AnalysisNeighborhoodSearchImpl()
447 PairSearchList::const_iterator i;
448 for (i = pairSearchList_.begin(); i != pairSearchList_.end(); ++i)
450 GMX_RELEASE_ASSERT(i->unique(), "Dangling AnalysisNeighborhoodPairSearch reference");
454 AnalysisNeighborhoodSearchImpl::PairSearchImplPointer AnalysisNeighborhoodSearchImpl::getPairSearch()
456 lock_guard<Mutex> lock(createPairSearchMutex_);
457 // TODO: Consider whether this needs to/can be faster, e.g., by keeping a
458 // separate pool of unused search objects.
459 PairSearchList::const_iterator i;
460 for (i = pairSearchList_.begin(); i != pairSearchList_.end(); ++i)
467 PairSearchImplPointer pairSearch(new AnalysisNeighborhoodPairSearchImpl(*this));
468 pairSearchList_.push_back(pairSearch);
472 bool AnalysisNeighborhoodSearchImpl::initGridCells(const matrix box, bool bSingleCell[DIM], int posCount)
474 // Determine the size of cubes where there are on average 10 positions.
475 // The loop takes care of cases where some of the box edges are shorter
476 // than the desired cube size; in such cases, a single grid cell is
477 // used in these dimensions, and the cube size is determined only from the
478 // larger box vectors. Such boxes should be rare, but the bounding box
479 // approach can result in very flat boxes with certain types of selections
480 // (e.g., for interfacial systems or for small number of atoms).
481 real targetsize = 0.0;
482 int prevDimCount = 4;
487 for (int dd = 0; dd < DIM; ++dd)
489 const real boxSize = box[dd][dd];
490 if (boxSize < targetsize)
492 bSingleCell[dd] = true;
495 // TODO: Consider if a fallback would be possible/better.
508 if (dimCount == 0 || dimCount == prevDimCount)
512 targetsize = pow(volume * 10 / posCount, static_cast<real>(1. / dimCount));
513 prevDimCount = dimCount;
516 int totalCellCount = 1;
517 for (int dd = 0; dd < DIM; ++dd)
526 cellCount = std::max(1, static_cast<int>(box[dd][dd] / targetsize));
527 // TODO: If the cell count is one or two, it could be better to
528 // just fall back to bSingleCell[dd] = true.
529 if (bGridPBC_[dd] && cellCount < 3)
534 totalCellCount *= cellCount;
535 ncelldim_[dd] = cellCount;
537 if (totalCellCount <= 3)
541 // Never decrease the size of the cell vector to avoid reallocating
542 // memory for the nested vectors. The actual size of the vector is not
543 // used outside this function.
544 if (cells_.size() < static_cast<size_t>(totalCellCount))
546 cells_.resize(totalCellCount);
548 for (int ci = 0; ci < totalCellCount; ++ci)
555 bool AnalysisNeighborhoodSearchImpl::initGrid(const t_pbc& pbc, int posCount, const rvec x[], bool bForce)
562 // TODO: Use this again (can be useful when tuning initGridCells()),
563 // or remove throughout.
564 GMX_UNUSED_VALUE(bForce);
569 bGridPBC_[XX] = false;
570 bGridPBC_[YY] = false;
571 bGridPBC_[ZZ] = false;
574 bGridPBC_[XX] = true;
575 bGridPBC_[YY] = true;
576 bGridPBC_[ZZ] = false;
579 bGridPBC_[XX] = true;
580 bGridPBC_[YY] = true;
581 bGridPBC_[ZZ] = true;
584 // Grid searching not supported for now with screw.
588 bool bSingleCell[DIM] = { false, false, bXY_ };
590 copy_mat(pbc.box, box);
591 // TODO: In principle, we could use the bounding box for periodic
592 // dimensions as well if the bounding box is sufficiently far from the box
594 rvec origin, boundingBoxSize;
595 computeBoundingBox(posCount, x, origin, boundingBoxSize);
596 clear_rvec(gridOrigin_);
597 for (int dd = 0; dd < DIM; ++dd)
599 if (!bGridPBC_[dd] && !bSingleCell[dd])
601 gridOrigin_[dd] = origin[dd];
603 box[dd][dd] = boundingBoxSize[dd];
605 // TODO: In case the zero vector comes from the bounding box, this does
606 // not lead to a very efficient grid search, but that should be rare.
607 if (box[dd][dd] <= 0.0)
609 GMX_ASSERT(!bGridPBC_[dd], "Periodic box vector is zero");
610 bSingleCell[dd] = true;
616 if (!initGridCells(box, bSingleCell, posCount))
621 bTric_ = TRICLINIC(pbc.box);
622 for (int dd = 0; dd < DIM; ++dd)
624 cellSize_[dd] = box[dd][dd] / ncelldim_[dd];
627 invCellSize_[dd] = 0.0;
631 invCellSize_[dd] = 1.0 / cellSize_[dd];
632 // TODO: It could be better to avoid this when determining the cell
633 // size, but this can still remain here as a fallback to avoid
634 // incorrect results.
635 if (std::ceil(2 * cutoff_ * invCellSize_[dd]) >= ncelldim_[dd])
637 // Cutoff is too close to half the box size for grid searching
638 // (it is not possible to find a single shift for every pair of
646 cellShiftZY_ = box[ZZ][YY] * invCellSize_[YY];
647 cellShiftZX_ = box[ZZ][XX] * invCellSize_[XX];
648 cellShiftYX_ = box[YY][XX] * invCellSize_[XX];
653 void AnalysisNeighborhoodSearchImpl::mapPointToGridCell(const rvec x, rvec cell, rvec xout) const
656 rvec_sub(x, gridOrigin_, xtmp);
657 // The reverse order is necessary for triclinic cells: shifting in Z may
658 // modify also X and Y, and shifting in Y may modify X, so the mapping to
659 // a rectangular grid needs to be done in this order.
660 for (int dd = DIM - 1; dd >= 0; --dd)
662 real cellIndex = xtmp[dd] * invCellSize_[dd];
665 const real cellCount = ncelldim_[dd];
666 while (cellIndex < 0)
668 cellIndex += cellCount;
669 rvec_inc(xtmp, pbc_.box[dd]);
671 while (cellIndex >= cellCount)
673 cellIndex -= cellCount;
674 rvec_dec(xtmp, pbc_.box[dd]);
677 cell[dd] = cellIndex;
679 copy_rvec(xtmp, xout);
682 int AnalysisNeighborhoodSearchImpl::getGridCellIndex(const ivec cell) const
684 GMX_ASSERT(cell[XX] >= 0 && cell[XX] < ncelldim_[XX], "Grid cell X index out of range");
685 GMX_ASSERT(cell[YY] >= 0 && cell[YY] < ncelldim_[YY], "Grid cell Y index out of range");
686 GMX_ASSERT(cell[ZZ] >= 0 && cell[ZZ] < ncelldim_[ZZ], "Grid cell Z index out of range");
687 return cell[XX] + cell[YY] * ncelldim_[XX] + cell[ZZ] * ncelldim_[XX] * ncelldim_[YY];
690 int AnalysisNeighborhoodSearchImpl::getGridCellIndex(const rvec cell) const
693 for (int dd = 0; dd < DIM; ++dd)
695 int cellIndex = static_cast<int>(floor(cell[dd]));
698 const int cellCount = ncelldim_[dd];
703 else if (cellIndex >= cellCount)
705 cellIndex = cellCount - 1;
708 icell[dd] = cellIndex;
710 return getGridCellIndex(icell);
713 void AnalysisNeighborhoodSearchImpl::addToGridCell(const rvec cell, int i)
715 const int ci = getGridCellIndex(cell);
716 cells_[ci].push_back(i);
719 void AnalysisNeighborhoodSearchImpl::initCellRange(const rvec centerCell, ivec currCell, ivec upperBound, int dim) const
721 RVec shiftedCenter(centerCell);
722 // Shift the center to the cell coordinates of currCell, so that
723 // computeCutoffExtent() can assume simple rectangular grid.
728 if (currCell[ZZ] < 0)
730 shiftedCenter[XX] += cellShiftZX_;
732 else if (currCell[ZZ] >= ncelldim_[ZZ])
734 shiftedCenter[XX] -= cellShiftZX_;
736 if (currCell[YY] < 0)
738 shiftedCenter[XX] += cellShiftYX_;
740 else if (currCell[YY] >= ncelldim_[YY])
742 shiftedCenter[XX] -= cellShiftYX_;
745 if (dim == XX || dim == YY)
747 if (currCell[ZZ] < 0)
749 shiftedCenter[YY] += cellShiftZY_;
751 else if (currCell[ZZ] >= ncelldim_[ZZ])
753 shiftedCenter[YY] -= cellShiftZY_;
757 const real range = computeCutoffExtent(shiftedCenter, currCell, dim) * invCellSize_[dim];
758 real startOffset = shiftedCenter[dim] - range;
759 real endOffset = shiftedCenter[dim] + range;
760 // For non-periodic dimensions, clamp to the actual grid edges.
763 // If endOffset < 0 or startOffset > N, these may cause the whole
764 // test position/grid plane/grid row to be skipped.
769 const int cellCount = ncelldim_[dim];
770 if (endOffset > cellCount - 1)
772 endOffset = cellCount - 1;
775 currCell[dim] = static_cast<int>(floor(startOffset));
776 upperBound[dim] = static_cast<int>(floor(endOffset));
779 real AnalysisNeighborhoodSearchImpl::computeCutoffExtent(const RVec centerCell, const ivec cell, int dim) const
787 for (int d = dim + 1; d < DIM; ++d)
789 real dimDist = cell[d] - centerCell[d];
794 else if (dimDist <= 0)
798 dist2 += dimDist * dimDist * cellSize_[d] * cellSize_[d];
800 if (dist2 >= cutoff2_)
804 return std::sqrt(cutoff2_ - dist2);
807 bool AnalysisNeighborhoodSearchImpl::nextCell(const rvec centerCell, ivec cell, ivec upperBound) const
814 if (cell[dim] > upperBound[dim])
819 for (int d = dim - 1; d >= 0; --d)
821 initCellRange(centerCell, cell, upperBound, d);
822 if (cell[d] > upperBound[d])
833 int AnalysisNeighborhoodSearchImpl::shiftCell(const ivec cell, rvec shift) const
836 copy_ivec(cell, shiftedCell);
839 for (int d = 0; d < DIM; ++d)
841 const int cellCount = ncelldim_[d];
844 // A single shift may not be sufficient if the cell must be shifted
845 // in more than one dimension, although for each individual
846 // dimension it would be.
847 while (shiftedCell[d] < 0)
849 shiftedCell[d] += cellCount;
850 rvec_inc(shift, pbc_.box[d]);
852 while (shiftedCell[d] >= cellCount)
854 shiftedCell[d] -= cellCount;
855 rvec_dec(shift, pbc_.box[d]);
860 return getGridCellIndex(shiftedCell);
863 void AnalysisNeighborhoodSearchImpl::init(AnalysisNeighborhood::SearchMode mode,
865 const t_blocka* excls,
867 const AnalysisNeighborhoodPositions& positions)
869 GMX_RELEASE_ASSERT(positions.index_ == -1,
870 "Individual indexed positions not supported as reference");
872 if (bXY_ && pbc != nullptr && pbc->ePBC != epbcNONE)
874 if (pbc->ePBC != epbcXY && pbc->ePBC != epbcXYZ)
876 std::string message = formatString(
877 "Computations in the XY plane are not supported with PBC type '%s'",
878 epbc_names[pbc->ePBC]);
879 GMX_THROW(NotImplementedError(message));
881 if (pbc->ePBC == epbcXYZ
882 && (std::fabs(pbc->box[ZZ][XX]) > GMX_REAL_EPS * pbc->box[ZZ][ZZ]
883 || std::fabs(pbc->box[ZZ][YY]) > GMX_REAL_EPS * pbc->box[ZZ][ZZ]))
886 NotImplementedError("Computations in the XY plane are not supported when the "
887 "last box vector is not parallel to the Z axis"));
889 // Use a single grid cell in Z direction.
891 copy_mat(pbc->box, box);
893 set_pbc(&pbc_, epbcXY, box);
895 else if (pbc != nullptr)
901 pbc_.ePBC = epbcNONE;
904 nref_ = positions.count_;
905 if (mode == AnalysisNeighborhood::eSearchMode_Simple)
911 bGrid_ = initGrid(pbc_, positions.count_, positions.x_,
912 mode == AnalysisNeighborhood::eSearchMode_Grid);
914 refIndices_ = positions.indices_;
917 xrefAlloc_.resize(nref_);
918 xref_ = as_rvec_array(xrefAlloc_.data());
920 for (int i = 0; i < nref_; ++i)
922 const int ii = (refIndices_ != nullptr) ? refIndices_[i] : i;
924 mapPointToGridCell(positions.x_[ii], refcell, xrefAlloc_[i]);
925 addToGridCell(refcell, i);
928 else if (refIndices_ != nullptr)
930 xrefAlloc_.resize(nref_);
931 xref_ = as_rvec_array(xrefAlloc_.data());
932 for (int i = 0; i < nref_; ++i)
934 copy_rvec(positions.x_[refIndices_[i]], xrefAlloc_[i]);
939 xref_ = positions.x_;
942 refExclusionIds_ = nullptr;
943 if (excls != nullptr)
945 // TODO: Check that the IDs are ascending, or remove the limitation.
946 refExclusionIds_ = positions.exclusionIds_;
947 GMX_RELEASE_ASSERT(refExclusionIds_ != nullptr,
948 "Exclusion IDs must be set for reference positions "
949 "when exclusions are enabled");
953 /********************************************************************
954 * AnalysisNeighborhoodPairSearchImpl
957 void AnalysisNeighborhoodPairSearchImpl::reset(int testIndex)
959 testIndex_ = testIndex;
966 if (testIndex_ >= 0 && testIndex_ < testPosCount_)
968 const int index = (testIndices_ != nullptr ? testIndices_[testIndex] : testIndex);
971 search_.mapPointToGridCell(testPositions_[index], testcell_, xtest_);
972 search_.initCellRange(testcell_, currCell_, cellBound_, ZZ);
973 search_.initCellRange(testcell_, currCell_, cellBound_, YY);
974 search_.initCellRange(testcell_, currCell_, cellBound_, XX);
977 testCellIndex_ = search_.getGridCellIndex(testcell_);
982 copy_rvec(testPositions_[index], xtest_);
988 if (search_.excls_ != nullptr)
990 const int exclIndex = testExclusionIds_[index];
991 if (exclIndex < search_.excls_->nr)
993 const int startIndex = search_.excls_->index[exclIndex];
994 nexcl_ = search_.excls_->index[exclIndex + 1] - startIndex;
995 excl_ = &search_.excls_->a[startIndex];
1006 void AnalysisNeighborhoodPairSearchImpl::nextTestPosition()
1008 if (testIndex_ < testPosCount_)
1015 bool AnalysisNeighborhoodPairSearchImpl::isExcluded(int j)
1017 if (exclind_ < nexcl_)
1019 const int index = (search_.refIndices_ != nullptr ? search_.refIndices_[j] : j);
1020 const int refId = search_.refExclusionIds_[index];
1021 while (exclind_ < nexcl_ && excl_[exclind_] < refId)
1025 if (exclind_ < nexcl_ && refId == excl_[exclind_])
1034 void AnalysisNeighborhoodPairSearchImpl::startSearch(const AnalysisNeighborhoodPositions& positions)
1036 selfSearchMode_ = false;
1037 testPosCount_ = positions.count_;
1038 testPositions_ = positions.x_;
1039 testExclusionIds_ = positions.exclusionIds_;
1040 testIndices_ = positions.indices_;
1041 GMX_RELEASE_ASSERT(search_.excls_ == nullptr || testExclusionIds_ != nullptr,
1042 "Exclusion IDs must be set when exclusions are enabled");
1043 if (positions.index_ < 0)
1049 // Somewhat of a hack: setup the array such that only the last position
1051 testPosCount_ = positions.index_ + 1;
1052 reset(positions.index_);
1056 void AnalysisNeighborhoodPairSearchImpl::startSelfSearch()
1058 selfSearchMode_ = true;
1059 testPosCount_ = search_.nref_;
1060 testPositions_ = search_.xref_;
1061 testExclusionIds_ = search_.refExclusionIds_;
1062 testIndices_ = search_.refIndices_;
1063 GMX_RELEASE_ASSERT(search_.excls_ == nullptr || testIndices_ == nullptr,
1064 "Exclusion IDs not implemented with indexed ref positions");
1068 template<class Action>
1069 bool AnalysisNeighborhoodPairSearchImpl::searchNext(Action action)
1071 while (testIndex_ < testPosCount_)
1075 int cai = prevcai_ + 1;
1080 const int ci = search_.shiftCell(currCell_, shift);
1081 if (selfSearchMode_ && ci > testCellIndex_)
1085 const int cellSize = ssize(search_.cells_[ci]);
1086 for (; cai < cellSize; ++cai)
1088 const int i = search_.cells_[ci][cai];
1089 if (selfSearchMode_ && ci == testCellIndex_ && i >= testIndex_)
1098 rvec_sub(search_.xref_[i], xtest_, dx);
1099 rvec_sub(dx, shift, dx);
1100 const real r2 = search_.bXY_ ? dx[XX] * dx[XX] + dx[YY] * dx[YY] : norm2(dx);
1101 if (r2 <= search_.cutoff2_)
1103 if (action(i, r2, dx))
1108 copy_rvec(dx, prevdx_);
1115 } while (search_.nextCell(testcell_, currCell_, cellBound_));
1119 for (int i = previ_ + 1; i < search_.nref_; ++i)
1126 if (search_.pbc_.ePBC != epbcNONE)
1128 pbc_dx(&search_.pbc_, search_.xref_[i], xtest_, dx);
1132 rvec_sub(search_.xref_[i], xtest_, dx);
1134 const real r2 = search_.bXY_ ? dx[XX] * dx[XX] + dx[YY] * dx[YY] : norm2(dx);
1135 if (r2 <= search_.cutoff2_)
1137 if (action(i, r2, dx))
1141 copy_rvec(dx, prevdx_);
1152 void AnalysisNeighborhoodPairSearchImpl::initFoundPair(AnalysisNeighborhoodPair* pair) const
1156 *pair = AnalysisNeighborhoodPair();
1160 *pair = AnalysisNeighborhoodPair(previ_, testIndex_, prevr2_, prevdx_);
1164 } // namespace internal
1170 * Search action to find the next neighbor.
1172 * Used as the action for AnalysisNeighborhoodPairSearchImpl::searchNext() to
1173 * find the next neighbor.
1175 * Simply breaks the loop on the first found neighbor.
1177 bool withinAction(int /*i*/, real /*r2*/, const rvec /* dx */)
1183 * Search action find the minimum distance.
1185 * Used as the action for AnalysisNeighborhoodPairSearchImpl::searchNext() to
1186 * find the nearest neighbor.
1188 * With this action, AnalysisNeighborhoodPairSearchImpl::searchNext() always
1189 * returns false, and the output is put into the variables passed by pointer
1190 * into the constructor. If no neighbors are found, the output variables are
1191 * not modified, i.e., the caller must initialize them.
1197 * Initializes the action with given output locations.
1199 * \param[out] closestPoint Index of the closest reference location.
1200 * \param[out] minDist2 Minimum distance squared.
1201 * \param[out] dx Shortest distance vector.
1203 * The constructor call does not modify the pointed values, but only
1204 * stores the pointers for later use.
1205 * See the class description for additional semantics.
1207 MindistAction(int* closestPoint, real* minDist2, rvec* dx) // NOLINT(readability-non-const-parameter)
1209 closestPoint_(*closestPoint),
1210 minDist2_(*minDist2),
1214 //! Copies the action.
1215 MindistAction(const MindistAction&) = default;
1217 //! Processes a neighbor to find the nearest point.
1218 bool operator()(int i, real r2, const rvec dx)
1234 GMX_DISALLOW_ASSIGN(MindistAction);
1239 /********************************************************************
1240 * AnalysisNeighborhood::Impl
1243 class AnalysisNeighborhood::Impl
1246 typedef AnalysisNeighborhoodSearch::ImplPointer SearchImplPointer;
1247 typedef std::vector<SearchImplPointer> SearchList;
1249 Impl() : cutoff_(0), excls_(nullptr), mode_(eSearchMode_Automatic), bXY_(false) {}
1252 SearchList::const_iterator i;
1253 for (i = searchList_.begin(); i != searchList_.end(); ++i)
1255 GMX_RELEASE_ASSERT(i->unique(), "Dangling AnalysisNeighborhoodSearch reference");
1259 SearchImplPointer getSearch();
1261 Mutex createSearchMutex_;
1262 SearchList searchList_;
1264 const t_blocka* excls_;
1269 AnalysisNeighborhood::Impl::SearchImplPointer AnalysisNeighborhood::Impl::getSearch()
1271 lock_guard<Mutex> lock(createSearchMutex_);
1272 // TODO: Consider whether this needs to/can be faster, e.g., by keeping a
1273 // separate pool of unused search objects.
1274 SearchList::const_iterator i;
1275 for (i = searchList_.begin(); i != searchList_.end(); ++i)
1282 SearchImplPointer search(new internal::AnalysisNeighborhoodSearchImpl(cutoff_));
1283 searchList_.push_back(search);
1287 /********************************************************************
1288 * AnalysisNeighborhood
1291 AnalysisNeighborhood::AnalysisNeighborhood() : impl_(new Impl) {}
1293 AnalysisNeighborhood::~AnalysisNeighborhood() {}
1295 void AnalysisNeighborhood::setCutoff(real cutoff)
1297 GMX_RELEASE_ASSERT(impl_->searchList_.empty(),
1298 "Changing the cutoff after initSearch() not currently supported");
1299 impl_->cutoff_ = cutoff;
1302 void AnalysisNeighborhood::setXYMode(bool bXY)
1307 void AnalysisNeighborhood::setTopologyExclusions(const t_blocka* excls)
1309 GMX_RELEASE_ASSERT(impl_->searchList_.empty(),
1310 "Changing the exclusions after initSearch() not currently supported");
1311 impl_->excls_ = excls;
1314 void AnalysisNeighborhood::setMode(SearchMode mode)
1316 impl_->mode_ = mode;
1319 AnalysisNeighborhood::SearchMode AnalysisNeighborhood::mode() const
1321 return impl_->mode_;
1324 AnalysisNeighborhoodSearch AnalysisNeighborhood::initSearch(const t_pbc* pbc,
1325 const AnalysisNeighborhoodPositions& positions)
1327 Impl::SearchImplPointer search(impl_->getSearch());
1328 search->init(mode(), impl_->bXY_, impl_->excls_, pbc, positions);
1329 return AnalysisNeighborhoodSearch(search);
1332 /********************************************************************
1333 * AnalysisNeighborhoodSearch
1336 AnalysisNeighborhoodSearch::AnalysisNeighborhoodSearch() {}
1338 AnalysisNeighborhoodSearch::AnalysisNeighborhoodSearch(const ImplPointer& impl) : impl_(impl) {}
1340 void AnalysisNeighborhoodSearch::reset()
1345 AnalysisNeighborhood::SearchMode AnalysisNeighborhoodSearch::mode() const
1347 GMX_RELEASE_ASSERT(impl_, "Accessing an invalid search object");
1348 return (impl_->usesGridSearch() ? AnalysisNeighborhood::eSearchMode_Grid
1349 : AnalysisNeighborhood::eSearchMode_Simple);
1352 bool AnalysisNeighborhoodSearch::isWithin(const AnalysisNeighborhoodPositions& positions) const
1354 GMX_RELEASE_ASSERT(impl_, "Accessing an invalid search object");
1355 internal::AnalysisNeighborhoodPairSearchImpl pairSearch(*impl_);
1356 pairSearch.startSearch(positions);
1357 return pairSearch.searchNext(&withinAction);
1360 real AnalysisNeighborhoodSearch::minimumDistance(const AnalysisNeighborhoodPositions& positions) const
1362 GMX_RELEASE_ASSERT(impl_, "Accessing an invalid search object");
1363 internal::AnalysisNeighborhoodPairSearchImpl pairSearch(*impl_);
1364 pairSearch.startSearch(positions);
1365 real minDist2 = impl_->cutoffSquared();
1366 int closestPoint = -1;
1367 rvec dx = { 0.0, 0.0, 0.0 };
1368 MindistAction action(&closestPoint, &minDist2, &dx);
1369 (void)pairSearch.searchNext(action);
1370 return std::sqrt(minDist2);
1373 AnalysisNeighborhoodPair AnalysisNeighborhoodSearch::nearestPoint(const AnalysisNeighborhoodPositions& positions) const
1375 GMX_RELEASE_ASSERT(impl_, "Accessing an invalid search object");
1376 internal::AnalysisNeighborhoodPairSearchImpl pairSearch(*impl_);
1377 pairSearch.startSearch(positions);
1378 real minDist2 = impl_->cutoffSquared();
1379 int closestPoint = -1;
1380 rvec dx = { 0.0, 0.0, 0.0 };
1381 MindistAction action(&closestPoint, &minDist2, &dx);
1382 (void)pairSearch.searchNext(action);
1383 return AnalysisNeighborhoodPair(closestPoint, 0, minDist2, dx);
1386 AnalysisNeighborhoodPairSearch AnalysisNeighborhoodSearch::startSelfPairSearch() const
1388 GMX_RELEASE_ASSERT(impl_, "Accessing an invalid search object");
1389 Impl::PairSearchImplPointer pairSearch(impl_->getPairSearch());
1390 pairSearch->startSelfSearch();
1391 return AnalysisNeighborhoodPairSearch(pairSearch);
1394 AnalysisNeighborhoodPairSearch
1395 AnalysisNeighborhoodSearch::startPairSearch(const AnalysisNeighborhoodPositions& positions) const
1397 GMX_RELEASE_ASSERT(impl_, "Accessing an invalid search object");
1398 Impl::PairSearchImplPointer pairSearch(impl_->getPairSearch());
1399 pairSearch->startSearch(positions);
1400 return AnalysisNeighborhoodPairSearch(pairSearch);
1403 /********************************************************************
1404 * AnalysisNeighborhoodPairSearch
1407 AnalysisNeighborhoodPairSearch::AnalysisNeighborhoodPairSearch(const ImplPointer& impl) :
1412 bool AnalysisNeighborhoodPairSearch::findNextPair(AnalysisNeighborhoodPair* pair)
1414 bool bFound = impl_->searchNext(&withinAction);
1415 impl_->initFoundPair(pair);
1419 void AnalysisNeighborhoodPairSearch::skipRemainingPairsForTestPosition()
1421 impl_->nextTestPosition();