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