Merge release-5-0 into master
[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, 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 "../legacyheaders/types/oenv.h"
52
53 #include "../onlinehelp/helptopicinterface.h"
54 #include "../utility/common.h"
55 #include "selection.h" // For gmx::SelectionList
56
57 struct gmx_ana_indexgrps_t;
58 struct t_pbc;
59 struct t_topology;
60 struct t_trxframe;
61
62 namespace gmx
63 {
64
65 class Options;
66 class SelectionCompiler;
67 class SelectionEvaluator;
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 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  * printTree() can be used to print the internal representation of the
103  * selections (mostly useful for debugging).
104  *
105  * Note that for trajectory analysis using TrajectoryAnalysisModule, the
106  * SelectionCollection object is managed by Gromacs, and \ref Selection objects
107  * are obtained from SelectionOption.
108  *
109  * \inpublicapi
110  * \ingroup module_selection
111  */
112 class SelectionCollection
113 {
114     public:
115         /*! \brief
116          * Creates a help tree for selections.
117          *
118          * \throws   std::bad_alloc if out of memory.
119          * \returns  Root topic of the created selection tree.
120          */
121         static HelpTopicPointer createDefaultHelpTopic();
122
123         /*! \brief
124          * Creates an empty selection collection.
125          *
126          * \throws  std::bad_alloc if out of memory.
127          */
128         SelectionCollection();
129         ~SelectionCollection();
130
131         /*! \brief
132          * Initializes options for setting global properties on the collection.
133          *
134          * \param[in,out] options Options object to initialize.
135          * \throws        std::bad_alloc if out of memory.
136          *
137          * Adds options to \p options that can be used to set the default
138          * position types (see setReferencePosType() and setOutputPosType())
139          * and debugging flags.
140          */
141         void initOptions(Options *options);
142
143         /*! \brief
144          * Sets the default reference position handling for a selection
145          * collection.
146          *
147          * \param[in]     type      Default selection reference position type
148          *     (one of the strings acceptable for
149          *     PositionCalculationCollection::typeFromEnum()).
150          * \throws  InternalError if \p type is invalid.
151          *
152          * Should be called before calling the parser functions, unless
153          * initOptions() has been called.  In the latter case, can still be
154          * used to override the default value (before initOptions() is called)
155          * and/or the value provided through the Options object.
156          *
157          * Strong exception safety.
158          */
159         void setReferencePosType(const char *type);
160         /*! \brief
161          * Sets the default reference position handling for a selection
162          * collection.
163          *
164          * \param[in]     type      Default selection output position type
165          *     (one of the strings acceptable for
166          *     PositionCalculationCollection::typeFromEnum()).
167          * \throws  InternalError if \p type is invalid.
168          *
169          * Should be called before calling the parser functions, unless
170          * initOptions() has been called.  In the latter case, can still be
171          * used to override the default value (before initOptions() is called)
172          * and/or the value provided through the Options object.
173          *
174          * Strong exception safety.
175          */
176         void setOutputPosType(const char *type);
177         /*! \brief
178          * Sets the debugging level for the selection collection.
179          *
180          * \param[in]   debugLevel  Debug level to set (0 = no debug
181          *      information).
182          *
183          * initOptions() creates debugging options that can also be used to set
184          * the debug level.  These are normally hidden, but if this method is
185          * called before initOptions() with a non-zero \p debugLevel, they are
186          * made visible.
187          *
188          * Mostly useful for debugging tools.
189          *
190          * Does not throw.
191          */
192         void setDebugLevel(int debugLevel);
193
194         /*! \brief
195          * Returns true if the collection requires topology information for
196          * evaluation.
197          *
198          * \returns true if any selection in the collection requires topology
199          *      information.
200          *
201          * Before the parser functions have been called, the return value is
202          * based just on the position types set.
203          * After parser functions have been called, the return value also takes
204          * into account the selection keywords used.
205          *
206          * Does not throw.
207          */
208         bool requiresTopology() const;
209         /*! \brief
210          * Sets the topology for the collection.
211          *
212          * \param[in]     top       Topology data.
213          * \param[in]     natoms    Number of atoms. If <=0, the number of
214          *      atoms in the topology is used.
215          *
216          * Either the topology must be provided, or \p natoms must be > 0.
217          *
218          * \p natoms determines the largest atom index that can be selected by
219          * the selection: even if the topology contains more atoms, they will
220          * not be selected.
221          *
222          * Does not throw currently, but this is subject to change when more
223          * underlying code is converted to C++.
224          */
225         void setTopology(t_topology *top, int natoms);
226         /*! \brief
227          * Sets the external index groups to use for the selections.
228          *
229          * \param[in]  grps  Index groups to use for the selections.
230          * \throws  std::bad_alloc if out of memory.
231          * \throws  InconsistentInputError if a group reference cannot be resolved.
232          *
233          * Only the first call to this method can have a non-NULL \p grps.
234          * At this point, any selections that have already been provided are
235          * searched for references to external groups, and the references are
236          * replaced by the contents of the groups.  If any referenced group
237          * cannot be found in \p grps (or if \p grps is NULL and there are any
238          * references), InconsistentInputError is thrown.
239          *
240          * The selection collection keeps a reference to \p grps until this
241          * method is called with a NULL \p grps.
242          * If this method is not called before compile(), it is automatically
243          * called as setIndexGroups(NULL).
244          */
245         void setIndexGroups(gmx_ana_indexgrps_t *grps);
246         /*! \brief
247          * Parses selection(s) from standard input.
248          *
249          * \param[in]  count    Number of selections to parse
250          *      (if -1, parse as many as provided by the user).
251          * \param[in]  bInteractive Whether the parser should behave
252          *      interactively.
253          * \param[in]  context  Context to print for interactive input.
254          * \returns    Vector of parsed selections.
255          * \throws     std::bad_alloc if out of memory.
256          * \throws     InvalidInputError if there is a parsing error
257          *      (an interactive parser only throws this if too few selections
258          *      are provided and the user forced the end of input).
259          *
260          * The returned objects remain valid for the lifetime of
261          * the selection collection.
262          * Some information about the selections only becomes available once
263          * compile() has been called; see \ref Selection.
264          *
265          * The string provided to \p context should be such that it can replace
266          * the three dots in "Specify selections ...:".  It can be empty.
267          */
268         SelectionList parseFromStdin(int count, bool bInteractive,
269                                      const std::string &context);
270         /*! \brief
271          * Parses selection(s) from a file.
272          *
273          * \param[in]  filename Name of the file to parse selections from.
274          * \returns    Vector of parsed selections.
275          * \throws     std::bad_alloc if out of memory.
276          * \throws     InvalidInputError if there is a parsing error.
277          *
278          * The returned objects remain valid for the lifetime of
279          * the selection collection.
280          * Some information about the selections only becomes available once
281          * compile() has been called; see \ref Selection.
282          */
283         SelectionList parseFromFile(const std::string &filename);
284         /*! \brief
285          * Parses selection(s) from a string.
286          *
287          * \param[in]  str      String to parse selections from.
288          * \returns    Vector of parsed selections.
289          * \throws     std::bad_alloc if out of memory.
290          * \throws     InvalidInputError if there is a parsing error.
291          *
292          * The returned objects remain valid for the lifetime of
293          * the selection collection.
294          * Some information about the selections only becomes available once
295          * compile() has been called; see \ref Selection.
296          */
297         SelectionList parseFromString(const std::string &str);
298         /*! \brief
299          * Prepares the selections for evaluation and performs optimizations.
300          *
301          * \throws  InconsistentInputError if topology is required but not set.
302          * \throws  InvalidInputError if setIndexGroups() has not been called
303          *      and there are index group references.
304          * \throws  unspecified if compilation fails (TODO: list/reduce these).
305          *
306          * Before compilation, selections should have been added to the
307          * collection using the parseFrom*() functions.
308          * The compiled selection collection can be passed to evaluate() to
309          * evaluate the selection for a frame.
310          * Before the compiled selection is evaluated, the selections indicate
311          * the maximal set of atoms/positions to which they can be evaluated;
312          * see \ref Selection.
313          *
314          * If an error occurs, the collection is cleared.
315          *
316          * The covered fraction information is initialized to ::CFRAC_NONE for
317          * all selections.
318          */
319         void compile();
320         /*! \brief
321          * Evaluates selections in the collection.
322          *
323          * \param[in] fr  Frame for which the evaluation should be carried out.
324          * \param[in] pbc PBC data, or NULL if no PBC should be used.
325          * \throws    unspeficied  Multiple possible exceptions to indicate
326          *      evaluation failure (TODO: enumerate).
327          */
328         void evaluate(t_trxframe *fr, t_pbc *pbc);
329         /*! \brief
330          * Evaluates the largest possible index groups from dynamic selections.
331          *
332          * \param[in] nframes Total number of frames.
333          *
334          * This method restores the selections to the state they were after
335          * compile().
336          *
337          * \p nframes should equal the number of times evaluate() has been
338          * called.
339          *
340          * Does not throw.
341          */
342         void evaluateFinal(int nframes);
343
344         /*! \brief
345          * Prints a human-readable version of the internal selection element
346          * tree.
347          *
348          * \param[in] fp      File handle to receive the output.
349          * \param[in] bValues If true, the evaluated values of selection
350          *      elements are printed as well.
351          *
352          * The output is very techical, and intended for debugging purposes.
353          *
354          * Does not throw.
355          */
356         void printTree(FILE *fp, bool bValues) const;
357         /*! \brief
358          * Prints the selection strings into an XVGR file as comments.
359          *
360          * \param[in] fp   Output file.
361          * \param[in] oenv Output options structure.
362          *
363          * Does not throw.
364          */
365         void printXvgrInfo(FILE *fp, output_env_t oenv) const;
366
367     private:
368         class Impl;
369
370         PrivateImplPointer<Impl> impl_;
371
372         /*! \brief
373          * Needed for the compiler to freely modify the collection.
374          */
375         friend class SelectionCompiler;
376         /*! \brief
377          * Needed for the evaluator to freely modify the collection.
378          */
379         friend class SelectionEvaluator;
380 };
381
382 } // namespace gmx
383
384 #endif