Apply clang-format-11
[alexxy/gromacs.git] / src / gromacs / selection / nbsearch.h
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2009-2018, The GROMACS development team.
5  * Copyright (c) 2019,2021, by the GROMACS development team, led by
6  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
7  * and including many others, as listed in the AUTHORS file in the
8  * top-level source directory and at http://www.gromacs.org.
9  *
10  * GROMACS is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Lesser General Public License
12  * as published by the Free Software Foundation; either version 2.1
13  * of the License, or (at your option) any later version.
14  *
15  * GROMACS is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public
21  * License along with GROMACS; if not, see
22  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
23  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
24  *
25  * If you want to redistribute modifications to GROMACS, please
26  * consider that scientific software is very special. Version
27  * control is crucial - bugs must be traceable. We will be happy to
28  * consider code for inclusion in the official distribution, but
29  * derived work must not be called official GROMACS. Details are found
30  * in the README & COPYING files - if they are missing, get the
31  * official version at http://www.gromacs.org.
32  *
33  * To help us fund GROMACS development, we humbly ask that you cite
34  * the research papers on the package. Check out http://www.gromacs.org.
35  */
36 /*! \file
37  * \brief API for neighborhood searching for analysis.
38  *
39  * The main part of the API is the class gmx::AnalysisNeighborhood.
40  * See \ref page_analysisnbsearch for an overview.
41  *
42  * The classes within this file can be used independently of the other parts
43  * of the selection module.
44  *
45  * \author Teemu Murtola <teemu.murtola@gmail.com>
46  * \inpublicapi
47  * \ingroup module_selection
48  */
49 #ifndef GMX_SELECTION_NBSEARCH_H
50 #define GMX_SELECTION_NBSEARCH_H
51
52 #include <memory>
53 #include <vector>
54
55 #include "gromacs/math/vec.h"
56 #include "gromacs/math/vectypes.h"
57 #include "gromacs/utility/arrayref.h"
58 #include "gromacs/utility/basedefinitions.h"
59 #include "gromacs/utility/gmxassert.h"
60 #include "gromacs/utility/real.h"
61
62 struct t_pbc;
63
64 namespace gmx
65 {
66 template<typename>
67 class ListOfLists;
68
69 namespace internal
70 {
71 class AnalysisNeighborhoodSearchImpl;
72 class AnalysisNeighborhoodPairSearchImpl;
73 }; // namespace internal
74
75 class AnalysisNeighborhoodSearch;
76 class AnalysisNeighborhoodPairSearch;
77
78 /*! \brief
79  * Input positions for neighborhood searching.
80  *
81  * This class supports uniformly specifying sets of positions for various
82  * methods in the analysis neighborhood searching classes
83  * (AnalysisNeighborhood and AnalysisNeighborhoodSearch).
84  *
85  * Note that copies are not made: only a reference to the positions passed to
86  * the constructors are kept.  The caller is responsible to ensure that those
87  * positions remain in scope as long as the neighborhood search object requires
88  * access to them.
89  *
90  * Also note that in addition to constructors here, Selection and
91  * SelectionPosition provide conversions operators to this type.  It is done
92  * this way to not introduce a cyclic dependency between the selection code and
93  * the neighborhood search code, which in turn allows splitting this search
94  * code into a separate lower-level module if desired at some point.
95  *
96  * Methods in this class do not throw.
97  *
98  * \inpublicapi
99  * \ingroup module_selection
100  */
101 class AnalysisNeighborhoodPositions
102 {
103 public:
104     /*! \brief
105      * Initializes positions from a single position vector.
106      *
107      * For positions initialized this way, AnalysisNeighborhoodPair always
108      * returns zero in the corresponding index.
109      *
110      * This constructor is not explicit to allow directly passing an rvec
111      * to methods that accept positions.
112      */
113     AnalysisNeighborhoodPositions(const rvec& x) :
114         count_(1), index_(-1), x_(&x), exclusionIds_(nullptr), indices_(nullptr)
115     {
116     }
117     /*! \brief
118      * Initializes positions from an array of position vectors.
119      */
120     AnalysisNeighborhoodPositions(const rvec x[], int count) :
121         count_(count), index_(-1), x_(x), exclusionIds_(nullptr), indices_(nullptr)
122     {
123     }
124     /*! \brief
125      * Initializes positions from a vector of position vectors.
126      */
127     AnalysisNeighborhoodPositions(const std::vector<RVec>& x) :
128         count_(ssize(x)), index_(-1), x_(as_rvec_array(x.data())), exclusionIds_(nullptr), indices_(nullptr)
129     {
130     }
131
132     /*! \brief
133      * Sets indices to use for mapping exclusions to these positions.
134      *
135      * The exclusion IDs can always be set, but they are ignored unless
136      * actual exclusions have been set with
137      * AnalysisNeighborhood::setTopologyExclusions().
138      */
139     AnalysisNeighborhoodPositions& exclusionIds(ArrayRef<const int> ids)
140     {
141         GMX_ASSERT(ssize(ids) == count_, "Exclusion id array should match the number of positions");
142         exclusionIds_ = ids.data();
143         return *this;
144     }
145     /*! \brief
146      * Sets indices that select a subset of all positions from the array.
147      *
148      * If called, selected positions from the array of positions passed to
149      * the constructor is used instead of the whole array.
150      * All returned indices from AnalysisNeighborhoodPair objects are
151      * indices to the \p indices array passed here.
152      */
153     AnalysisNeighborhoodPositions& indexed(ArrayRef<const int> indices)
154     {
155         count_   = ssize(indices);
156         indices_ = indices.data();
157         return *this;
158     }
159
160     /*! \brief
161      * Selects a single position to use from an array.
162      *
163      * If called, a single position from the array of positions passed to
164      * the constructor is used instead of the whole array.
165      * In contrast to the AnalysisNeighborhoodPositions(const rvec &)
166      * constructor, AnalysisNeighborhoodPair objects return \p index
167      * instead of zero.
168      *
169      * If used together with indexed(), \p index references the index array
170      * passed to indexed() instead of the position array.
171      */
172     AnalysisNeighborhoodPositions& selectSingleFromArray(int index)
173     {
174         GMX_ASSERT(index >= 0 && index < count_, "Invalid position index");
175         index_ = index;
176         return *this;
177     }
178
179 private:
180     int         count_;
181     int         index_;
182     const rvec* x_;
183     const int*  exclusionIds_;
184     const int*  indices_;
185
186     //! To access the positions for initialization.
187     friend class internal::AnalysisNeighborhoodSearchImpl;
188     //! To access the positions for initialization.
189     friend class internal::AnalysisNeighborhoodPairSearchImpl;
190 };
191
192 /*! \brief
193  * Neighborhood searching for analysis tools.
194  *
195  * See \ref page_analysisnbsearch for an overview.
196  *
197  * To use the search, create an object of this type, call setCutoff() to
198  * initialize it, and then repeatedly call initSearch() to start a search with
199  * different sets of reference positions.  For each set of reference positions,
200  * use methods in the returned AnalysisNeighborhoodSearch to find the reference
201  * positions that are within the given cutoff from a provided position.
202  *
203  * initSearch() is thread-safe and can be called from multiple threads.  Each
204  * call returns a different instance of the search object that can be used
205  * independently of the others.  The returned AnalysisNeighborhoodSearch
206  * objects are also thread-safe, and can be used concurrently from multiple
207  * threads.  It is also possible to create multiple concurrent searches within
208  * a single thread.
209  *
210  * \todo
211  * Generalize the exclusion machinery to make it easier to use for other cases
212  * than atom-atom exclusions from the topology.
213  *
214  * \inpublicapi
215  * \ingroup module_selection
216  */
217 class AnalysisNeighborhood
218 {
219 public:
220     //! Searching algorithm to use.
221     enum SearchMode
222     {
223         //! Select algorithm based on heuristic efficiency considerations.
224         eSearchMode_Automatic,
225         //! Use a simple loop over all pairs.
226         eSearchMode_Simple,
227         //! Use grid-based searching whenever possible.
228         eSearchMode_Grid
229     };
230
231     //! Creates an uninitialized neighborhood search.
232     AnalysisNeighborhood();
233     ~AnalysisNeighborhood();
234
235     /*! \brief
236      * Sets cutoff distance for the neighborhood searching.
237      *
238      * \param[in]  cutoff Cutoff distance for the search
239      *   (<=0 stands for no cutoff).
240      *
241      * Currently, can only be called before the first call to initSearch().
242      * If this method is not called, no cutoff is used in the searches.
243      *
244      * Does not throw.
245      */
246     void setCutoff(real cutoff);
247     /*! \brief
248      * Sets the search to only happen in the XY plane.
249      *
250      * Z component of the coordinates is not used in the searching,
251      * and returned distances are computed in the XY plane.
252      * Only boxes with the third box vector parallel to the Z axis are
253      * currently implemented.
254      *
255      * Does not throw.
256      */
257     void setXYMode(bool bXY);
258     /*! \brief
259      * Sets atom exclusions from a topology.
260      *
261      * The \p excls structure specifies the exclusions from test positions
262      * to reference positions, i.e., a block starting at `excls->index[i]`
263      * specifies the exclusions for test position `i`, and the indices in
264      * `excls->a` are indices of the reference positions.  If `excls->nr`
265      * is smaller than a test position id, then such test positions do not
266      * have any exclusions.
267      * It is assumed that the indices within a block of indices in
268      * `excls->a` is ascending.
269      *
270      * Does not throw.
271      *
272      * \see AnalysisNeighborhoodPositions::exclusionIds()
273      */
274     void setTopologyExclusions(const ListOfLists<int>* excls);
275     /*! \brief
276      * Sets the algorithm to use for searching.
277      *
278      * \param[in] mode  Search mode to use.
279      *
280      * Note that if \p mode is \ref eSearchMode_Grid, it is still only a
281      * suggestion: grid-based searching may not be possible with the
282      * provided input, in which case a simple search is still used.
283      * This is mainly useful for testing purposes to force a mode.
284      *
285      * Does not throw.
286      */
287     void setMode(SearchMode mode);
288     //! Returns the currently active search mode.
289     SearchMode mode() const;
290
291     /*! \brief
292      * Initializes neighborhood search for a set of positions.
293      *
294      * \param[in] pbc        PBC information for the frame.
295      * \param[in] positions  Set of reference positions to use.
296      * \returns   Search object that can be used to find positions from
297      *      \p x within the given cutoff.
298      * \throws    std::bad_alloc if out of memory.
299      *
300      * Currently, the input positions cannot use
301      * AnalysisNeighborhoodPositions::selectSingleFromArray().
302      */
303     AnalysisNeighborhoodSearch initSearch(const t_pbc* pbc, const AnalysisNeighborhoodPositions& positions);
304
305 private:
306     class Impl;
307
308     std::unique_ptr<Impl> impl_;
309 };
310
311 /*! \brief
312  * Value type to represent a pair of positions found in neighborhood searching.
313  *
314  * Methods in this class do not throw.
315  *
316  * \inpublicapi
317  * \ingroup module_selection
318  */
319 class AnalysisNeighborhoodPair
320 {
321 public:
322     //! Initializes an invalid pair.
323     AnalysisNeighborhoodPair() : refIndex_(-1), testIndex_(0), distance2_(0.0), dx_() {}
324     //! Initializes a pair object with the given data.
325     AnalysisNeighborhoodPair(int refIndex, int testIndex, real distance2, const rvec dx) :
326         refIndex_(refIndex), testIndex_(testIndex), distance2_(distance2), dx_()
327     {
328         copy_rvec(dx, dx_);
329     }
330
331     /*! \brief
332      * Whether this pair is valid.
333      *
334      * If isValid() returns false, other methods should not be called.
335      */
336     bool isValid() const { return refIndex_ >= 0; }
337
338     /*! \brief
339      * Returns the index of the reference position in the pair.
340      *
341      * This index is always the index into the position array provided to
342      * AnalysisNeighborhood::initSearch().
343      */
344     int refIndex() const
345     {
346         GMX_ASSERT(isValid(), "Accessing invalid object");
347         return refIndex_;
348     }
349     /*! \brief
350      * Returns the index of the test position in the pair.
351      *
352      * The contents of this index depends on the context (method call) that
353      * produces the pair.
354      * If there was no array in the call, this index is zero.
355      */
356     int testIndex() const
357     {
358         GMX_ASSERT(isValid(), "Accessing invalid object");
359         return testIndex_;
360     }
361     /*! \brief
362      * Returns the squared distance between the pair of positions.
363      */
364     real distance2() const
365     {
366         GMX_ASSERT(isValid(), "Accessing invalid object");
367         return distance2_;
368     }
369     /*! \brief
370      * Returns the shortest vector between the pair of positions.
371      *
372      * The vector is from the test position to the reference position.
373      */
374     const rvec& dx() const
375     {
376         GMX_ASSERT(isValid(), "Accessing invalid object");
377         return dx_;
378     }
379
380 private:
381     int  refIndex_;
382     int  testIndex_;
383     real distance2_;
384     rvec dx_;
385 };
386
387 /*! \brief
388  * Initialized neighborhood search with a fixed set of reference positions.
389  *
390  * An instance of this class is obtained through
391  * AnalysisNeighborhood::initSearch(), and can be used to do multiple searches
392  * against the provided set of reference positions.
393  * It is possible to create concurrent pair searches (including from different
394  * threads), as well as call other methods in this class while a pair search is
395  * in progress.
396  *
397  * This class works like a pointer: copies of it point to the same search.
398  * In general, avoid creating copies, and only use the copy/assignment support
399  * for moving the variable around.  With C++11, this class would best be
400  * movable.
401  *
402  * Methods in this class do not throw unless otherwise indicated.
403  *
404  * \todo
405  * Make it such that reset() is not necessary to call in code that repeatedly
406  * assigns the result of AnalysisNeighborhood::initSearch() to the same
407  * variable (see sm_distance.cpp).
408  *
409  * \todo
410  * Consider removing minimumDistance(), as nearestPoint() already returns the
411  * distance.
412  *
413  * \inpublicapi
414  * \ingroup module_selection
415  */
416 class AnalysisNeighborhoodSearch
417 {
418 public:
419     /*! \brief
420      * Internal short-hand type for a pointer to the implementation class.
421      *
422      * shared_ptr is used here to automatically keep a reference count to
423      * track whether an implementation class is still used outside the
424      * AnalysisNeighborhood object.  Ownership currently always stays with
425      * AnalysisNeighborhood; it always keeps one instance of the pointer.
426      */
427     typedef std::shared_ptr<internal::AnalysisNeighborhoodSearchImpl> ImplPointer;
428
429     /*! \brief
430      * Initializes an invalid search.
431      *
432      * Such an object cannot be used for searching.  It needs to be
433      * assigned a value from AnalysisNeighborhood::initSearch() before it
434      * can be used.  Provided to allow declaring a variable to hold the
435      * search before calling AnalysisNeighborhood::initSearch().
436      */
437     AnalysisNeighborhoodSearch();
438     /*! \brief
439      * Internally initialize the search.
440      *
441      * Used to implement AnalysisNeighborhood::initSearch().
442      * Cannot be called from user code.
443      */
444     explicit AnalysisNeighborhoodSearch(const ImplPointer& impl);
445
446     /*! \brief
447      * Clears this search.
448      *
449      * Equivalent to \c "*this = AnalysisNeighborhoodSearch();".
450      * Currently, this is necessary to avoid unnecessary memory allocation
451      * if the previous search variable is still in scope when you want to
452      * call AnalysisNeighborhood::initSearch() again.
453      */
454     void reset();
455
456     /*! \brief
457      * Returns the searching algorithm that this search is using.
458      *
459      * The return value is never AnalysisNeighborhood::eSearchMode_Automatic.
460      */
461     AnalysisNeighborhood::SearchMode mode() const;
462
463     /*! \brief
464      * Checks whether a point is within a neighborhood.
465      *
466      * \param[in] positions  Set of test positions to use.
467      * \returns   true if any of the test positions is within the cutoff of
468      *     any reference position.
469      */
470     bool isWithin(const AnalysisNeighborhoodPositions& positions) const;
471     /*! \brief
472      * Calculates the minimum distance from the reference points.
473      *
474      * \param[in] positions  Set of test positions to use.
475      * \returns   The distance to the nearest reference position, or the
476      *     cutoff value if there are no reference positions within the
477      *     cutoff.
478      */
479     real minimumDistance(const AnalysisNeighborhoodPositions& positions) const;
480     /*! \brief
481      * Finds the closest reference point.
482      *
483      * \param[in] positions  Set of test positions to use.
484      * \returns   The reference index identifies the reference position
485      *     that is closest to the test positions.
486      *     The test index identifies the test position that is closest to
487      *     the provided test position.  The returned pair is invalid if
488      *     no reference position is within the cutoff.
489      */
490     AnalysisNeighborhoodPair nearestPoint(const AnalysisNeighborhoodPositions& positions) const;
491
492     /*! \brief
493      * Starts a search to find all reference position pairs within a cutoff.
494      *
495      * \returns   Initialized search object to loop through all reference
496      *     position pairs within the configured cutoff.
497      * \throws    std::bad_alloc if out of memory.
498      *
499      * This works as if the reference positions were passed to
500      * startPairSearch(), except that it only returns each pair once,
501      * instead of returning both i-j and j-i pairs, as startPairSearch()
502      * does.  i-i pairs are not returned.  Note that the order of ref/test
503      * indices in the returned pairs is not predictable.  That is, one of
504      * i-j or j-i is always returned, but there is no control which one.
505      */
506     AnalysisNeighborhoodPairSearch startSelfPairSearch() const;
507
508     /*! \brief
509      * Starts a search to find reference positions within a cutoff.
510      *
511      * \param[in] positions  Set of test positions to use.
512      * \returns   Initialized search object to loop through all reference
513      *     positions within the configured cutoff.
514      * \throws    std::bad_alloc if out of memory.
515      *
516      * If you want to pass the same positions here as you used for the
517      * reference positions, consider using startSelfPairSearch().
518      * It can be up to 50% faster.
519      */
520     AnalysisNeighborhoodPairSearch startPairSearch(const AnalysisNeighborhoodPositions& positions) const;
521
522 private:
523     typedef internal::AnalysisNeighborhoodSearchImpl Impl;
524
525     ImplPointer impl_;
526 };
527
528 /*! \brief
529  * Initialized neighborhood pair search with a fixed set of positions.
530  *
531  * This class is used to loop through pairs of neighbors within the cutoff
532  * provided to AnalysisNeighborhood.  The following code demonstrates its use:
533  * \code
534    gmx::AnalysisNeighborhood       nb;
535    nb.setCutoff(cutoff);
536    gmx::AnalysisNeighborhoodPositions refPos(xref, nref);
537    gmx::AnalysisNeighborhoodSearch search = nb.initSearch(pbc, refPos);
538    gmx::AnalysisNeighborhoodPairSearch pairSearch = search.startPairSearch(selection);
539    gmx::AnalysisNeighborhoodPair pair;
540    while (pairSearch.findNextPair(&pair))
541    {
542        // <do something for each found pair the information in pair>
543    }
544  * \endcode
545  *
546  * It is not possible to use a single search object from multiple threads
547  * concurrently.
548  *
549  * This class works like a pointer: copies of it point to the same search.
550  * In general, avoid creating copies, and only use the copy/assignment support
551  * for moving the variable around.  With C++11, this class would best be
552  * movable.
553  *
554  * Methods in this class do not throw.
555  *
556  * \inpublicapi
557  * \ingroup module_selection
558  */
559 class AnalysisNeighborhoodPairSearch
560 {
561 public:
562     /*! \brief
563      * Internal short-hand type for a pointer to the implementation class.
564      *
565      * See AnalysisNeighborhoodSearch::ImplPointer for rationale of using
566      * shared_ptr and ownership semantics.
567      */
568     typedef std::shared_ptr<internal::AnalysisNeighborhoodPairSearchImpl> ImplPointer;
569
570     /*! \brief
571      * Internally initialize the search.
572      *
573      * Used to implement AnalysisNeighborhoodSearch::startPairSearch().
574      * Cannot be called from user code.
575      */
576     explicit AnalysisNeighborhoodPairSearch(const ImplPointer& impl);
577
578     /*! \brief
579      * Finds the next pair within the cutoff.
580      *
581      * \param[out] pair  Information about the found pair.
582      * \returns    false if there were no more pairs.
583      *
584      * If the method returns false, \p pair will be invalid.
585      *
586      * \see AnalysisNeighborhoodPair
587      * \see AnalysisNeighborhoodSearch::startPairSearch()
588      */
589     bool findNextPair(AnalysisNeighborhoodPair* pair);
590     /*! \brief
591      * Skip remaining pairs for a test position in the search.
592      *
593      * When called after findNextPair(), makes subsequent calls to
594      * findNextPair() skip any pairs that have the same test position as
595      * that previously returned.
596      * This is useful if the caller wants to search whether any reference
597      * position within the cutoff satisfies some condition.  This method
598      * can be used to skip remaining pairs after the first such position
599      * has been found if the remaining pairs would not have an effect on
600      * the outcome.
601      */
602     void skipRemainingPairsForTestPosition();
603
604 private:
605     ImplPointer impl_;
606 };
607
608 } // namespace gmx
609
610 #endif