Apply clang-format to source tree
[alexxy/gromacs.git] / src / gromacs / selection / selectioncollection.h
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2010,2011,2012,2013,2014,2015,2016,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.
8  *
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.
13  *
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.
18  *
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.
23  *
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.
31  *
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.
34  */
35 /*! \file
36  * \brief
37  * Declares gmx::SelectionCollection.
38  *
39  * \author Teemu Murtola <teemu.murtola@gmail.com>
40  * \inpublicapi
41  * \ingroup module_selection
42  */
43 #ifndef GMX_SELECTION_SELECTIONCOLLECTION_H
44 #define GMX_SELECTION_SELECTIONCOLLECTION_H
45
46 #include <cstdio>
47
48 #include <string>
49 #include <vector>
50
51 #include "gromacs/selection/selection.h" // For gmx::SelectionList
52 #include "gromacs/utility/classhelpers.h"
53
54 struct gmx_ana_indexgrps_t;
55 struct gmx_mtop_t;
56 struct t_pbc;
57 struct t_trxframe;
58
59 namespace gmx
60 {
61
62 class IOptionsContainer;
63 class SelectionCompiler;
64 class SelectionEvaluator;
65 class TextInputStream;
66 class TextOutputStream;
67 struct SelectionTopologyProperties;
68
69 /*! \brief
70  * Collection of selections.
71  *
72  * This class is the main interface to the core of the selection engine.
73  * It is used to initialize and manage a collection of selections that share
74  * the same topology.  Selections within one collection can share variables and
75  * can be optimized together.  Selections from two different collections do not
76  * interact.
77  *
78  * The constructor creates an empty selection collection object.  To initialize
79  * the object, either call initOptions(), or both setReferencePosType() and
80  * setOutputPosType().  See these methods for more details on the
81  * initialization options.
82  *
83  * After setting the default values, one or more selections can be parsed with
84  * one or more calls to parseInteractive(), parseFromStdin(), parseFromFile(), and/or
85  * parseFromString().  After all selections are parsed, the topology must be
86  * set with setTopology() unless requiresTopology() returns false (the topology
87  * can also be set earlier).
88  * setIndexGroups() must also be called if external index group references are
89  * used in the selections; it can be called at any point before compile().
90  * Once all selections are parsed, they must be compiled all at once using
91  * compile().
92  *
93  * After compilation, dynamic selections have the maximum number of atoms they
94  * can evaluate to, but positions have undefined values (see \ref Selection and
95  * SelectionPosition).  evaluate() can be used to update the selections for a
96  * new frame.  evaluateFinal() can be called after all the frames have been
97  * processed to restore the selection values back to the ones they were after
98  * compile().
99  *
100  * At any point, requiresTopology() can be called to see whether the
101  * information provided so far requires loading the topology.
102  * Similarly, requiresIndexGroups() tells whether external index groups are
103  * requires.
104  * printTree() can be used to print the internal representation of the
105  * selections (mostly useful for debugging).
106  *
107  * Note that for trajectory analysis using TrajectoryAnalysisModule, the
108  * SelectionCollection object is managed by Gromacs, and \ref Selection objects
109  * are obtained from SelectionOption.
110  *
111  * \inpublicapi
112  * \ingroup module_selection
113  */
114 class SelectionCollection
115 {
116 public:
117     //! Flag for initOptions() to select how to behave with -seltype option.
118     enum SelectionTypeOption
119     {
120         /*! \brief
121          * Add the option for the user to select default value for
122          * setOutputPosType().
123          */
124         IncludeSelectionTypeOption,
125         /*! \brief
126          * Do not add the option, selections will always select atoms by
127          * default.
128          */
129         AlwaysAtomSelections
130     };
131
132     /*! \brief
133      * Creates an empty selection collection.
134      *
135      * \throws  std::bad_alloc if out of memory.
136      */
137     SelectionCollection();
138     ~SelectionCollection();
139
140     /*! \brief
141      * Initializes options for setting global properties on the collection.
142      *
143      * \param[in,out] options Options object to initialize.
144      * \param[in]     selectionTypeOption
145      *     Whether to add option to influence setOutputPosType().
146      * \throws        std::bad_alloc if out of memory.
147      *
148      * Adds options to \p options that can be used to set the default
149      * position types (see setReferencePosType() and setOutputPosType())
150      * and debugging flags.
151      */
152     void initOptions(IOptionsContainer* options, SelectionTypeOption selectionTypeOption);
153
154     /*! \brief
155      * Sets the default reference position handling for a selection
156      * collection.
157      *
158      * \param[in]     type      Default selection reference position type
159      *     (one of the strings acceptable for
160      *     PositionCalculationCollection::typeFromEnum()).
161      * \throws  InternalError if \p type is invalid.
162      *
163      * Should be called before calling the parser functions, unless
164      * initOptions() has been called.  In the latter case, can still be
165      * used to override the default value (before initOptions() is called)
166      * and/or the value provided through the Options object.
167      *
168      * Strong exception safety.
169      */
170     void setReferencePosType(const char* type);
171     /*! \brief
172      * Sets the default reference position handling for a selection
173      * collection.
174      *
175      * \param[in]     type      Default selection output position type
176      *     (one of the strings acceptable for
177      *     PositionCalculationCollection::typeFromEnum()).
178      * \throws  InternalError if \p type is invalid.
179      *
180      * Should be called before calling the parser functions, unless
181      * initOptions() has been called.  In the latter case, can still be
182      * used to override the default value (before initOptions() is called)
183      * and/or the value provided through the Options object.
184      *
185      * Strong exception safety.
186      */
187     void setOutputPosType(const char* type);
188     /*! \brief
189      * Sets the debugging level for the selection collection.
190      *
191      * \param[in]   debugLevel  Debug level to set (0 = no debug
192      *      information).
193      *
194      * initOptions() creates debugging options that can also be used to set
195      * the debug level.  These are normally hidden, but if this method is
196      * called before initOptions() with a non-zero \p debugLevel, they are
197      * made visible.
198      *
199      * Mostly useful for debugging tools.
200      *
201      * Does not throw.
202      */
203     void setDebugLevel(int debugLevel);
204
205     /*! \brief
206      * Returns what topology information is required for evaluation.
207      *
208      * \returns What topology information is required for compiling and/or
209      *     evaluating the selections in the collection.
210      *
211      * Before the parser functions have been called, the return value is
212      * based just on the position types set.
213      * After parser functions have been called, the return value also takes
214      * into account the selection keywords used.
215      * After the compiler has been called, the return value is final and
216      * also considers possible force evaluation requested for the
217      * selections.
218      *
219      * Does not throw.
220      */
221     SelectionTopologyProperties requiredTopologyProperties() const;
222     /*! \brief
223      * Returns true if the collection requires external index groups.
224      *
225      * \returns true if any selection has an unresolved index group reference.
226      *
227      * The return value is `false` after setIndexGroups() has been called.
228      *
229      * Does not throw.
230      */
231     bool requiresIndexGroups() const;
232     /*! \brief
233      * Sets the topology for the collection.
234      *
235      * \param[in]     top       Topology data.
236      * \param[in]     natoms    Number of atoms. If <=0, the number of
237      *      atoms in the topology is used.
238      *
239      * Either the topology must be provided, or \p natoms must be > 0.
240      *
241      * \p natoms determines the largest atom index that can be selected by
242      * the selection: even if the topology contains more atoms, they will
243      * not be selected.
244      *
245      * Does not throw currently, but this is subject to change when more
246      * underlying code is converted to C++.
247      */
248     void setTopology(gmx_mtop_t* top, int natoms);
249     /*! \brief
250      * Sets the external index groups to use for the selections.
251      *
252      * \param[in]  grps  Index groups to use for the selections.
253      * \throws  std::bad_alloc if out of memory.
254      * \throws  InconsistentInputError if a group reference cannot be resolved.
255      *
256      * Only the first call to this method can have a non-NULL \p grps.
257      * At this point, any selections that have already been provided are
258      * searched for references to external groups, and the references are
259      * replaced by the contents of the groups.  If any referenced group
260      * cannot be found in \p grps (or if \p grps is NULL and there are any
261      * references), InconsistentInputError is thrown.
262      *
263      * The selection collection keeps a reference to \p grps until this
264      * method is called with a NULL \p grps.
265      * If this method is not called before compile(), it is automatically
266      * called as setIndexGroups(NULL).
267      */
268     void setIndexGroups(gmx_ana_indexgrps_t* grps);
269     /*! \brief
270      * Parses selection(s) from standard input.
271      *
272      * \param[in]  count    Number of selections to parse
273      *      (if -1, parse as many as provided by the user).
274      * \param[in]  bInteractive Whether the parser should behave
275      *      interactively.
276      * \param[in]  context  Context to print for interactive input.
277      * \returns    Vector of parsed selections.
278      * \throws     std::bad_alloc if out of memory.
279      * \throws     InvalidInputError if there is a parsing error
280      *      (an interactive parser only throws this if too few selections
281      *      are provided and the user forced the end of input).
282      *
283      * The returned objects remain valid for the lifetime of
284      * the selection collection.
285      * Some information about the selections only becomes available once
286      * compile() has been called; see \ref Selection.
287      *
288      * The string provided to \p context should be such that it can replace
289      * the three dots in "Specify selections ...:".  It can be empty.
290      */
291     SelectionList parseFromStdin(int count, bool bInteractive, const std::string& context);
292     /*! \brief
293      * Parses selection(s) interactively using provided streams.
294      *
295      * \param[in]  count    Number of selections to parse
296      *      (if -1, parse as many as provided by the user).
297      * \param[in]  inputStream  Stream to use for input.
298      * \param[in]  outputStream Stream to use for output
299      *      (if NULL, the parser runs non-interactively and does not
300      *      produce any status messages).
301      * \param[in]  context  Context to print for interactive input.
302      * \returns    Vector of parsed selections.
303      * \throws     std::bad_alloc if out of memory.
304      * \throws     InvalidInputError if there is a parsing error
305      *      (an interactive parser only throws this if too few selections
306      *      are provided and the user forced the end of input).
307      *
308      * Works the same as parseFromStdin(), except that the caller can
309      * provide streams to use instead of `stdin` and `stderr`.
310      *
311      * Mainly usable for unit testing interactive input.
312      */
313     SelectionList parseInteractive(int                count,
314                                    TextInputStream*   inputStream,
315                                    TextOutputStream*  outputStream,
316                                    const std::string& context);
317     /*! \brief
318      * Parses selection(s) from a file.
319      *
320      * \param[in]  filename Name of the file to parse selections from.
321      * \returns    Vector of parsed selections.
322      * \throws     std::bad_alloc if out of memory.
323      * \throws     InvalidInputError if there is a parsing error.
324      *
325      * The returned objects remain valid for the lifetime of
326      * the selection collection.
327      * Some information about the selections only becomes available once
328      * compile() has been called; see \ref Selection.
329      */
330     SelectionList parseFromFile(const std::string& filename);
331     /*! \brief
332      * Parses selection(s) from a string.
333      *
334      * \param[in]  str      String to parse selections from.
335      * \returns    Vector of parsed selections.
336      * \throws     std::bad_alloc if out of memory.
337      * \throws     InvalidInputError if there is a parsing error.
338      *
339      * The returned objects remain valid for the lifetime of
340      * the selection collection.
341      * Some information about the selections only becomes available once
342      * compile() has been called; see \ref Selection.
343      */
344     SelectionList parseFromString(const std::string& str);
345     /*! \brief
346      * Prepares the selections for evaluation and performs optimizations.
347      *
348      * \throws  InconsistentInputError if topology is required but not set.
349      * \throws  InvalidInputError if setIndexGroups() has not been called
350      *      and there are index group references.
351      * \throws  unspecified if compilation fails (TODO: list/reduce these).
352      *
353      * Before compilation, selections should have been added to the
354      * collection using the parseFrom*() functions.
355      * The compiled selection collection can be passed to evaluate() to
356      * evaluate the selection for a frame.
357      * Before the compiled selection is evaluated, the selections indicate
358      * the maximal set of atoms/positions to which they can be evaluated;
359      * see \ref Selection.
360      *
361      * If an error occurs, the collection is cleared.
362      *
363      * The covered fraction information is initialized to ::CFRAC_NONE for
364      * all selections.
365      */
366     void compile();
367     /*! \brief
368      * Evaluates selections in the collection.
369      *
370      * \param[in] fr  Frame for which the evaluation should be carried out.
371      * \param[in] pbc PBC data, or NULL if no PBC should be used.
372      * \throws    unspeficied  Multiple possible exceptions to indicate
373      *      evaluation failure (TODO: enumerate).
374      */
375     void evaluate(t_trxframe* fr, t_pbc* pbc);
376     /*! \brief
377      * Evaluates the largest possible index groups from dynamic selections.
378      *
379      * \param[in] nframes Total number of frames.
380      *
381      * This method restores the selections to the state they were after
382      * compile().
383      *
384      * \p nframes should equal the number of times evaluate() has been
385      * called.
386      *
387      * Does not throw.
388      */
389     void evaluateFinal(int nframes);
390
391     /*! \brief
392      * Prints a human-readable version of the internal selection element
393      * tree.
394      *
395      * \param[in] fp      File handle to receive the output.
396      * \param[in] bValues If true, the evaluated values of selection
397      *      elements are printed as well.
398      *
399      * The output is very techical, and intended for debugging purposes.
400      *
401      * Does not throw.
402      */
403     void printTree(FILE* fp, bool bValues) const;
404     /*! \brief
405      * Prints the selection strings into an XVGR file as comments.
406      *
407      * \param[in] fp   Output file.
408      *
409      * Does not throw.
410      */
411     void printXvgrInfo(FILE* fp) const;
412
413 private:
414     class Impl;
415
416     PrivateImplPointer<Impl> impl_;
417
418     /*! \brief
419      * Needed for the compiler to freely modify the collection.
420      */
421     friend class SelectionCompiler;
422     /*! \brief
423      * Needed for the evaluator to freely modify the collection.
424      */
425     friend class SelectionEvaluator;
426 };
427
428 } // namespace gmx
429
430 #endif