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