Merge release-4-6 (commit 'Ic142a690')
[alexxy/gromacs.git] / src / gromacs / selection / selectioncollection.h
1 /*
2  *
3  *                This source code is part of
4  *
5  *                 G   R   O   M   A   C   S
6  *
7  *          GROningen MAchine for Chemical Simulations
8  *
9  * Written by David van der Spoel, Erik Lindahl, Berk Hess, and others.
10  * Copyright (c) 1991-2000, University of Groningen, The Netherlands.
11  * Copyright (c) 2001-2009, The GROMACS development team,
12  * check out http://www.gromacs.org for more information.
13
14  * This program is free software; you can redistribute it and/or
15  * modify it under the terms of the GNU General Public License
16  * as published by the Free Software Foundation; either version 2
17  * of the License, or (at your option) any later version.
18  *
19  * If you want to redistribute modifications, please consider that
20  * scientific software is very special. Version control is crucial -
21  * bugs must be traceable. We will be happy to consider code for
22  * inclusion in the official distribution, but derived work must not
23  * be called official GROMACS. Details are found in the README & COPYING
24  * files - if they are missing, get the official version at www.gromacs.org.
25  *
26  * To help us fund GROMACS development, we humbly ask that you cite
27  * the papers on the package - you can find them in the top README file.
28  *
29  * For more info, check our website at http://www.gromacs.org
30  */
31 /*! \file
32  * \brief
33  * Declares gmx::SelectionCollection.
34  *
35  * \author Teemu Murtola <teemu.murtola@cbr.su.se>
36  * \inpublicapi
37  * \ingroup module_selection
38  */
39 #ifndef GMX_SELECTION_SELECTIONCOLLECTION_H
40 #define GMX_SELECTION_SELECTIONCOLLECTION_H
41
42 #include <string>
43 #include <vector>
44
45 #include "../legacyheaders/typedefs.h"
46
47 #include "../utility/common.h"
48 #include "selection.h" // For gmx::SelectionList
49
50 struct gmx_ana_indexgrps_t;
51
52 namespace gmx
53 {
54
55 class Options;
56 class SelectionCompiler;
57 class SelectionEvaluator;
58 class SelectionOptionStorage;
59
60 /*! \brief
61  * Collection of selections.
62  *
63  * This class is the main interface to the core of the selection engine.
64  * It is used to initialize and manage a collection of selections that share
65  * the same topology.  Selections within one collection can share variables and
66  * can be optimized together.  Selections from two different collections do not
67  * interact.
68  *
69  * The constructor creates an empty selection collection object.  To initialize
70  * the object, either call initOptions(), or both setReferencePosType() and
71  * setOutputPosType().  See these methods for more details on the
72  * initialization options.
73  *
74  * After setting the default values, one or more selections can be parsed with
75  * one or more calls to parseFromStdin(), parseFromFile(), and/or
76  * parseFromString().  parseRequestedFromStdin() and parseRequestedFromString()
77  * are provided for integration with SelectionOption.  After all selections are
78  * parsed, the topology must be set with setTopology() unless
79  * requiresTopology() returns false (the topology can also be set earlier).
80  * setIndexGroups() must also be called if external index group references are
81  * used in the selections; it can be called at any point before compile().
82  * Once all selections are parsed, they must be compiled all at once using
83  * compile().
84  *
85  * After compilation, dynamic selections have the maximum number of atoms they
86  * can evaluate to, but positions have undefined values (see \ref Selection and
87  * SelectionPosition).  evaluate() can be used to update the selections for a
88  * new frame.  evaluateFinal() can be called after all the frames have been
89  * processed to restore the selection values back to the ones they were after
90  * compile().
91  *
92  * At any point, requiresTopology() can be called to see whether the
93  * information provided so far requires loading the topology.
94  * printTree() can be used to print the internal representation of the
95  * selections (mostly useful for debugging).
96  *
97  * Note that for trajectory analysis using TrajectoryAnalysisModule, the
98  * SelectionCollection object is managed by Gromacs, and \ref Selection objects
99  * are obtained from SelectionOption.
100  *
101  * \inpublicapi
102  * \ingroup module_selection
103  */
104 class SelectionCollection
105 {
106     public:
107         /*! \brief
108          * Creates an empty selection collection.
109          *
110          * \throws  std::bad_alloc if out of memory.
111          */
112         SelectionCollection();
113         ~SelectionCollection();
114
115         /*! \brief
116          * Initializes options for setting global properties on the collection.
117          *
118          * \returns Initialized options object.
119          * \throws  std::bad_alloc if out of memory.
120          *
121          * The returned options can be used to set the default position types
122          * (see setReferencePosType() and setOutputPosType()) and debugging
123          * options.
124          */
125         Options &initOptions();
126
127         /*! \brief
128          * Sets the default reference position handling for a selection
129          * collection.
130          *
131          * \param[in]     type      Default selection reference position type
132          *     (one of the strings acceptable for
133          *     PositionCalculationCollection::typeFromEnum()).
134          * \throws  InternalError if \p type is invalid.
135          *
136          * Should be called before calling the parser functions, unless
137          * initOptions() has been called.  In the latter case, can still be
138          * used to override the default value (before initOptions() is called)
139          * and/or the value provided through the Options object.
140          *
141          * Strong exception safety.
142          */
143         void setReferencePosType(const char *type);
144         /*! \brief
145          * Sets the default reference position handling for a selection
146          * collection.
147          *
148          * \param[in]     type      Default selection output position type
149          *     (one of the strings acceptable for
150          *     PositionCalculationCollection::typeFromEnum()).
151          * \throws  InternalError if \p type is invalid.
152          *
153          * Should be called before calling the parser functions, unless
154          * initOptions() has been called.  In the latter case, can still be
155          * used to override the default value (before initOptions() is called)
156          * and/or the value provided through the Options object.
157          *
158          * Strong exception safety.
159          */
160         void setOutputPosType(const char *type);
161         /*! \brief
162          * Sets the debugging level for the selection collection.
163          *
164          * \param[in]   debugLevel  Debug level to set (0 = no debug
165          *      information).
166          *
167          * initOptions() creates debugging options that can also be used to set
168          * the debug level.  These are normally hidden, but if this method is
169          * called before initOptions() with a non-zero \p debugLevel, they are
170          * made visible.
171          *
172          * Mostly useful for debugging tools.
173          *
174          * Does not throw.
175          */
176         void setDebugLevel(int debugLevel);
177
178         /*! \brief
179          * Returns true if the collection requires topology information for
180          * evaluation.
181          *
182          * \returns true if any selection in the collection requires topology
183          *      information.
184          *
185          * Before the parser functions have been called, the return value is
186          * based just on the position types set.
187          * After parser functions have been called, the return value also takes
188          * into account the selection keywords used.
189          *
190          * Does not throw.
191          */
192         bool requiresTopology() const;
193         /*! \brief
194          * Sets the topology for the collection.
195          *
196          * \param[in]     top       Topology data.
197          * \param[in]     natoms    Number of atoms. If <=0, the number of
198          *      atoms in the topology is used.
199          *
200          * Either the topology must be provided, or \p natoms must be > 0.
201          *
202          * \p natoms determines the largest atom index that can be selected by
203          * the selection: even if the topology contains more atoms, they will
204          * not be selected.
205          *
206          * Does not throw currently, but this is subject to change when more
207          * underlying code is converted to C++.
208          */
209         void setTopology(t_topology *top, int natoms);
210         /*! \brief
211          * Sets the external index groups to use for the selections.
212          *
213          * \param[in]  grps  Index groups to use for the selections.
214          * \throws  std::bad_alloc if out of memory.
215          * \throws  InvalidInputError if a group reference cannot be resolved.
216          *
217          * Only the first call to this method can have a non-NULL \p grps.
218          * At this point, any selections that have already been provided are
219          * searched for references to external groups, and the references are
220          * replaced by the contents of the groups.  If any referenced group
221          * cannot be found in \p grps (or if \p grps is NULL and there are any
222          * references), InvalidInputError is thrown.
223          *
224          * The selection collection keeps a reference to \p grps until this
225          * method is called with a NULL \p grps.
226          * If this method is not called before compile(), it is automatically
227          * called as setIndexGroups(NULL).
228          */
229         void setIndexGroups(gmx_ana_indexgrps_t *grps);
230         /*! \brief
231          * Parses selection(s) from standard input for options not yet
232          * provided.
233          *
234          * \param[in]  bInteractive Whether the parser should behave
235          *      interactively.
236          * \throws     unspecified  Can throw any exception thrown by
237          *      parseFromStdin().
238          * \throws     std::bad_alloc if out of memory.
239          *
240          * This method cooperates with SelectionOption to allow interactive
241          * input of missing selections after all options have been processed.
242          * It should be called after the Options::finish() method has been
243          * called on all options that add selections to this collection.
244          * For each required selection option that has not been given, as well
245          * as for optional selection options that have been specified without
246          * values, it will prompt the user to input the necessary selections.
247          */
248         void parseRequestedFromStdin(bool bInteractive);
249         /*! \brief
250          * Parses selection(s) from a file for options not yet provided.
251          *
252          * \param[in]  filename Name of the file to parse selections from.
253          * \throws     unspecified  Can throw any exception thrown by
254          *      parseFromFile().
255          * \throws     std::bad_alloc if out of memory.
256          * \throws     InvalidInputError if
257          *      - the number of selections in \p filename doesn't match the
258          *        number requested.
259          *      - any selection uses a feature that is not allowed for the
260          *        corresponding option.
261          *      - if there is a request for any number of selections that is
262          *        not the last (in which case it is not possible to determine
263          *        which selections belong to which request).
264          *
265          * This method behaves as parseRequestedFromStdin(), but reads the
266          * selections from a file instead of standard input.
267          * This is used to implement SelectionFileOption.
268          *
269          * \see parseRequestedFromStdin()
270          */
271         void parseRequestedFromFile(const std::string &filename);
272         /*! \brief
273          * Parses selection(s) from a string for options not yet provided.
274          *
275          * \param[in]  str     String to parse.
276          * \throws     unspecified  Can throw any exception thrown by
277          *      parseFromString().
278          * \throws     std::bad_alloc if out of memory.
279          * \throws     InvalidInputError in same conditions as
280          *      parseRequestedFromFile().
281          *
282          * This method behaves as parseRequestedFromFile(), but reads the
283          * selections from a string instead of a file.
284          * This method is mainly used for testing.
285          *
286          * \see parseRequestedFromFile()
287          */
288         void parseRequestedFromString(const std::string &str);
289         /*! \brief
290          * Parses selection(s) from standard input.
291          *
292          * \param[in]  count    Number of selections to parse
293          *      (if -1, parse as many as provided by the user).
294          * \param[in]  bInteractive Whether the parser should behave
295          *      interactively.
296          * \param[out] output   Vector to which parsed selections are appended.
297          * \throws     std::bad_alloc if out of memory.
298          * \throws     InvalidInputError if there is a parsing error
299          *      (an interactive parser only throws this if too few selections
300          *      are provided and the user forced the end of input).
301          *
302          * Parsed selections are appended to \p output without clearing it
303          * first.  If parsing fails, \p output is not modified.
304          *
305          * The objects returned in \p output remain valid for the lifetime of
306          * the selection collection.
307          * Some information about the selections only becomes available once
308          * compile() has been called; see \ref Selection.
309          */
310         void parseFromStdin(int count, bool bInteractive,
311                             SelectionList *output);
312         /*! \brief
313          * Parses selection(s) from a file.
314          *
315          * \param[in]  filename Name of the file to parse selections from.
316          * \param[out] output   Vector to which parsed selections are appended.
317          * \throws     std::bad_alloc if out of memory.
318          * \throws     InvalidInputError if there is a parsing error.
319          *
320          * Parsed selections are appended to \p output without clearing it
321          * first.  If parsing fails, \p output is not modified.
322          *
323          * The objects returned in \p output remain valid for the lifetime of
324          * the selection collection.
325          * Some information about the selections only becomes available once
326          * compile() has been called; see \ref Selection.
327          */
328         void parseFromFile(const std::string &filename,
329                            SelectionList *output);
330         /*! \brief
331          * Parses selection(s) from a string.
332          *
333          * \param[in]  str      String to parse selections from.
334          * \param[out] output   Vector to which parsed selections are appended.
335          * \throws     std::bad_alloc if out of memory.
336          * \throws     InvalidInputError if there is a parsing error.
337          *
338          * Parsed selections are appended to \p output without clearing it
339          * first.  If parsing fails, \p output is not modified.
340          *
341          * The objects returned in \p output remain valid for the lifetime of
342          * the selection collection.
343          * Some information about the selections only becomes available once
344          * compile() has been called; see \ref Selection.
345          */
346         void parseFromString(const std::string &str,
347                              SelectionList *output);
348         /*! \brief
349          * Prepares the selections for evaluation and performs optimizations.
350          *
351          * \throws  InconsistentInputError if topology is required but not set.
352          * \throws  InvalidInputError if setIndexGroups() has not been called
353          *      and there are index group references.
354          * \throws  unspecified if compilation fails (TODO: list/reduce these).
355          *
356          * Before compilation, selections should have been added to the
357          * collection using the parseFrom*() functions.
358          * The compiled selection collection can be passed to evaluate() to
359          * evaluate the selection for a frame.
360          * Before the compiled selection is evaluated, the selections indicate
361          * the maximal set of atoms/positions to which they can be evaluated;
362          * see \ref Selection.
363          *
364          * If an error occurs, the collection is cleared.
365          *
366          * The covered fraction information is initialized to ::CFRAC_NONE for
367          * all selections.
368          */
369         void compile();
370         /*! \brief
371          * Evaluates selections in the collection.
372          *
373          * \param[in] fr  Frame for which the evaluation should be carried out.
374          * \param[in] pbc PBC data, or NULL if no PBC should be used.
375          * \throws    unspeficied  Multiple possible exceptions to indicate
376          *      evaluation failure (TODO: enumerate).
377          */
378         void evaluate(t_trxframe *fr, t_pbc *pbc);
379         /*! \brief
380          * Evaluates the largest possible index groups from dynamic selections.
381          *
382          * \param[in] nframes Total number of frames.
383          *
384          * This method restores the selections to the state they were after
385          * compile().
386          *
387          * \p nframes should equal the number of times evaluate() has been
388          * called.
389          *
390          * Does not throw.
391          */
392         void evaluateFinal(int nframes);
393
394         /*! \brief
395          * Prints a human-readable version of the internal selection element
396          * tree.
397          *
398          * \param[in] fp      File handle to receive the output.
399          * \param[in] bValues If true, the evaluated values of selection
400          *      elements are printed as well.
401          *
402          * The output is very techical, and intended for debugging purposes.
403          *
404          * Does not throw.
405          */
406         void printTree(FILE *fp, bool bValues) const;
407         /*! \brief
408          * Prints the selection strings into an XVGR file as comments.
409          *
410          * \param[in] fp   Output file.
411          * \param[in] oenv Output options structure.
412          *
413          * Does not throw.
414          */
415         void printXvgrInfo(FILE *fp, output_env_t oenv) const;
416
417     private:
418         class Impl;
419
420         PrivateImplPointer<Impl> _impl;
421
422         /*! \brief
423          * Needed for the compiler to freely modify the collection.
424          */
425         friend class SelectionCompiler;
426         /*! \brief
427          * Needed for the evaluator to freely modify the collection.
428          */
429         friend class SelectionEvaluator;
430         /*! \brief
431          * Needed for handling delayed selection parsing requests.
432          */
433         friend class SelectionOptionStorage;
434 };
435
436 } // namespace gmx
437
438 #endif