2 * This file is part of the GROMACS molecular simulation package.
4 * Copyright (c) 2009,2010,2011,2012,2013, by the GROMACS development team, led by
5 * David van der Spoel, Berk Hess, Erik Lindahl, and including many
6 * others, as listed in the AUTHORS file in the top-level source
7 * directory and at http://www.gromacs.org.
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.
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.
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.
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.
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.
37 * Declares gmx::Selection and supporting classes.
39 * \author Teemu Murtola <teemu.murtola@gmail.com>
41 * \ingroup module_selection
43 #ifndef GMX_SELECTION_SELECTION_H
44 #define GMX_SELECTION_SELECTION_H
49 #include "../legacyheaders/typedefs.h"
51 #include "../utility/arrayref.h"
52 #include "../utility/common.h"
53 #include "../utility/gmxassert.h"
56 #include "indexutil.h"
57 #include "selectionenums.h"
62 class SelectionOptionStorage;
63 class SelectionTreeElement;
65 class AnalysisNeighborhoodPositions;
67 class SelectionPosition;
69 //! Container of selections used in public selection interfaces.
70 typedef std::vector<Selection> SelectionList;
77 * Internal data for a single selection.
79 * This class is internal to the selection module, but resides in a public
80 * header because of efficiency reasons: it allows frequently used access
81 * methods in \ref Selection to be inlined.
83 * Methods in this class do not throw unless otherwise specified.
85 * \ingroup module_selection
91 * Creates a new selection object.
93 * \param[in] elem Root of the evaluation tree for this selection.
94 * \param[in] selstr String that was parsed to produce this selection.
95 * \throws std::bad_alloc if out of memory.
97 SelectionData(SelectionTreeElement *elem, const char *selstr);
100 //! Returns the name for this selection.
101 const char *name() const { return name_.c_str(); }
102 //! Returns the string that was parsed to produce this selection.
103 const char *selectionText() const { return selectionText_.c_str(); }
104 //! Returns true if the size of the selection (posCount()) is dynamic.
105 bool isDynamic() const { return bDynamic_; }
106 //! Returns the type of positions in the selection.
107 e_index_t type() const { return rawPositions_.m.type; }
109 //! Number of positions in the selection.
110 int posCount() const { return rawPositions_.count(); }
111 //! Returns the root of the evaluation tree for this selection.
112 SelectionTreeElement &rootElement() { return rootElement_; }
114 //! Returns whether the covered fraction can change between frames.
115 bool isCoveredFractionDynamic() const { return bDynamicCoveredFraction_; }
117 //! Returns true if the given flag is set.
118 bool hasFlag(SelectionFlag flag) const { return flags_.test(flag); }
119 //! Sets the flags for this selection.
120 void setFlags(SelectionFlags flags) { flags_ = flags; }
122 //! \copydoc Selection::initCoveredFraction()
123 bool initCoveredFraction(e_coverfrac_t type);
126 * Updates the name of the selection if missing.
128 * \throws std::bad_alloc if out of memory.
130 * If selections get their value from a group reference that cannot be
131 * resolved during parsing, the name is final only after group
132 * references have been resolved.
134 * This function is called by SelectionCollection::setIndexGroups().
138 * Computes total masses and charges for all selection positions.
140 * \param[in] top Topology information.
141 * \throws std::bad_alloc if out of memory.
143 * For dynamic selections, the values need to be updated after each
144 * evaluation with refreshMassesAndCharges().
145 * This is done by SelectionEvaluator.
147 * This function is called by SelectionCompiler.
149 * Strong exception safety guarantee.
151 void initializeMassesAndCharges(const t_topology *top);
153 * Updates masses and charges after dynamic selection has been
156 * \param[in] top Topology information.
158 * Called by SelectionEvaluator.
160 void refreshMassesAndCharges(const t_topology *top);
162 * Updates the covered fraction after a selection has been evaluated.
164 * Called by SelectionEvaluator.
166 void updateCoveredFractionForFrame();
168 * Computes average covered fraction after all frames have been evaluated.
170 * \param[in] nframes Number of frames that have been evaluated.
172 * \p nframes should be equal to the number of calls to
173 * updateCoveredFractionForFrame().
174 * Called by SelectionEvaluator::evaluateFinal().
176 void computeAverageCoveredFraction(int nframes);
178 * Restores position information to state it was in after compilation.
180 * \param[in] top Topology information.
182 * Depends on SelectionCompiler storing the original atoms in the
183 * \a rootElement_ object.
184 * Called by SelectionEvaluator::evaluateFinal().
186 void restoreOriginalPositions(const t_topology *top);
189 //! Name of the selection.
191 //! The actual selection string.
192 std::string selectionText_;
193 //! Low-level representation of selected positions.
194 gmx_ana_pos_t rawPositions_;
195 //! Total masses for the current positions.
196 std::vector<real> posMass_;
197 //! Total charges for the current positions.
198 std::vector<real> posCharge_;
199 SelectionFlags flags_;
200 //! Root of the selection evaluation tree.
201 SelectionTreeElement &rootElement_;
202 //! Type of the covered fraction.
203 e_coverfrac_t coveredFractionType_;
204 //! Covered fraction of the selection for the current frame.
205 real coveredFraction_;
206 //! The average covered fraction (over the trajectory).
207 real averageCoveredFraction_;
208 //! true if the value can change as a function of time.
210 //! true if the covered fraction depends on the frame.
211 bool bDynamicCoveredFraction_;
214 * Needed to wrap access to information.
216 friend class gmx::Selection;
218 * Needed for proper access to position information.
220 friend class gmx::SelectionPosition;
222 GMX_DISALLOW_COPY_AND_ASSIGN(SelectionData);
225 } // namespace internal
228 * Provides access to a single selection.
230 * This class provides a public interface for accessing selection information.
231 * General information about the selection can be accessed with methods name(),
232 * selectionText(), isDynamic(), and type(). The first three can be accessed
233 * any time after the selection has been parsed, and type() can be accessed
234 * after the selection has been compiled.
236 * There are a few methods that can be used to change the behavior of the
237 * selection. setEvaluateVelocities() and setEvaluateForces() can be called
238 * before the selection is compiled to request evaluation of velocities and/or
239 * forces in addition to coordinates.
241 * Each selection is made of a set of positions. Each position has associated
242 * coordinates, and possibly velocities and forces if they have been requested
243 * and are available. It also has a set of atoms associated with it; typically
244 * the coordinates are the center-of-mass or center-of-geometry coordinates for
245 * that set of atoms. To access the number of positions in the selection, use
246 * posCount(). To access individual positions, use position().
247 * See SelectionPosition for details of how to use individual positions.
248 * setOriginalId() can be used to adjust the return value of
249 * SelectionPosition::mappedId(); see that method for details.
251 * It is also possible to access the list of atoms that make up all the
252 * positions directly: atomCount() returns the total number of atoms in the
253 * selection and atomIndices() an array of their indices.
254 * Similarly, it is possible to access the coordinates and other properties
255 * of the positions as continuous arrays through coordinates(), velocities(),
256 * forces(), masses(), charges(), refIds(), and mappedIds().
258 * Both positions and atoms can be accessed after the selection has been
259 * compiled. For dynamic selections, the return values of these methods change
260 * after each evaluation to reflect the situation for the current frame.
261 * Before any frame has been evaluated, these methods return the maximal set
262 * to which the selection can evaluate.
264 * There are two possible modes for how positions for dynamic selections are
265 * handled. In the default mode, posCount() can change, and for each frame,
266 * only the positions that are selected in that frame can be accessed. In a
267 * masked mode, posCount() remains constant, i.e., the positions are always
268 * evaluated for the maximal set, and SelectionPosition::selected() is used to
269 * determine whether a position is selected for a frame. The masked mode can
270 * be requested with SelectionOption::dynamicMask().
272 * The class also provides methods for printing out information: printInfo()
273 * and printDebugInfo(). These are mainly for internal use by Gromacs.
275 * This class works like a pointer type: copying and assignment is lightweight,
276 * and all copies work interchangeably, accessing the same internal data.
278 * Methods in this class do not throw.
280 * \see SelectionPosition
283 * \ingroup module_selection
289 * Creates a selection wrapper that has no associated selection.
291 * Any attempt to call methods in the object before a selection is
292 * assigned results in undefined behavior.
294 Selection() : sel_(NULL) {}
296 * Creates a new selection object.
298 * \param sel Selection data to wrap.
300 * Only for internal use by the selection module.
302 explicit Selection(internal::SelectionData *sel) : sel_(sel) {}
304 //! Returns the name of the selection.
305 const char *name() const { return data().name(); }
306 //! Returns the string that was parsed to produce this selection.
307 const char *selectionText() const { return data().selectionText(); }
308 //! Returns true if the size of the selection (posCount()) is dynamic.
309 bool isDynamic() const { return data().isDynamic(); }
310 //! Returns the type of positions in the selection.
311 e_index_t type() const { return data().type(); }
313 //! Total number of atoms in the selection.
314 int atomCount() const
316 return data().rawPositions_.m.mapb.nra;
318 //! Returns atom indices of all atoms in the selection.
319 ConstArrayRef<int> atomIndices() const
321 return ConstArrayRef<int>(sel_->rawPositions_.m.mapb.a,
322 sel_->rawPositions_.m.mapb.nra);
324 //! Number of positions in the selection.
325 int posCount() const { return data().posCount(); }
326 //! Access a single position.
327 SelectionPosition position(int i) const;
328 //! Returns coordinates for this selection as a continuous array.
329 ConstArrayRef<rvec> coordinates() const
331 return ConstArrayRef<rvec>(data().rawPositions_.x, posCount());
333 //! Returns whether velocities are available for this selection.
334 bool hasVelocities() const { return data().rawPositions_.v != NULL; }
336 * Returns velocities for this selection as a continuous array.
338 * Must not be called if hasVelocities() returns false.
340 ConstArrayRef<rvec> velocities() const
342 GMX_ASSERT(hasVelocities(), "Velocities accessed, but unavailable");
343 return ConstArrayRef<rvec>(data().rawPositions_.v, posCount());
345 //! Returns whether forces are available for this selection.
346 bool hasForces() const { return sel_->rawPositions_.f != NULL; }
348 * Returns forces for this selection as a continuous array.
350 * Must not be called if hasForces() returns false.
352 ConstArrayRef<rvec> forces() const
354 GMX_ASSERT(hasForces(), "Forces accessed, but unavailable");
355 return ConstArrayRef<rvec>(data().rawPositions_.f, posCount());
357 //! Returns masses for this selection as a continuous array.
358 ConstArrayRef<real> masses() const
360 // posMass_ may have more entries than posCount() in the case of
361 // dynamic selections that don't have a topology
362 // (and thus the masses and charges are fixed).
363 GMX_ASSERT(data().posMass_.size() >= static_cast<size_t>(posCount()),
364 "Internal inconsistency");
365 return ConstArrayRef<real>(data().posMass_.begin(),
366 data().posMass_.begin() + posCount());
368 //! Returns charges for this selection as a continuous array.
369 ConstArrayRef<real> charges() const
371 // posCharge_ may have more entries than posCount() in the case of
372 // dynamic selections that don't have a topology
373 // (and thus the masses and charges are fixed).
374 GMX_ASSERT(data().posCharge_.size() >= static_cast<size_t>(posCount()),
375 "Internal inconsistency");
376 return ConstArrayRef<real>(data().posCharge_.begin(),
377 data().posCharge_.begin() + posCount());
380 * Returns reference IDs for this selection as a continuous array.
382 * \see SelectionPosition::refId()
384 ConstArrayRef<int> refIds() const
386 return ConstArrayRef<int>(data().rawPositions_.m.refid, posCount());
389 * Returns mapped IDs for this selection as a continuous array.
391 * \see SelectionPosition::mappedId()
393 ConstArrayRef<int> mappedIds() const
395 return ConstArrayRef<int>(data().rawPositions_.m.mapid, posCount());
398 //! Returns whether the covered fraction can change between frames.
399 bool isCoveredFractionDynamic() const { return data().isCoveredFractionDynamic(); }
400 //! Returns the covered fraction for the current frame.
401 real coveredFraction() const { return data().coveredFraction_; }
404 * Allows passing a selection directly to neighborhood searching.
406 * When initialized this way, AnalysisNeighborhoodPair objects return
407 * indices that can be used to index the selection positions with
410 * Works exactly like if AnalysisNeighborhoodPositions had a
411 * constructor taking a Selection object as a parameter.
412 * See AnalysisNeighborhoodPositions for rationale and additional
415 operator AnalysisNeighborhoodPositions() const;
418 * Initializes information about covered fractions.
420 * \param[in] type Type of covered fraction required.
421 * \returns true if the covered fraction can be calculated for the
424 bool initCoveredFraction(e_coverfrac_t type)
426 return data().initCoveredFraction(type);
429 * Sets whether this selection evaluates velocities for positions.
431 * \param[in] bEnabled If true, velocities are evaluated.
433 * If you request the evaluation, but then evaluate the selection for
434 * a frame that does not contain velocity information, results are
438 * Implement it such that in the above case, hasVelocities() will
439 * return false for such frames.
443 void setEvaluateVelocities(bool bEnabled)
445 data().flags_.set(efSelection_EvaluateVelocities, bEnabled);
448 * Sets whether this selection evaluates forces for positions.
450 * \param[in] bEnabled If true, forces are evaluated.
452 * If you request the evaluation, but then evaluate the selection for
453 * a frame that does not contain force information, results are
458 void setEvaluateForces(bool bEnabled)
460 data().flags_.set(efSelection_EvaluateForces, bEnabled);
464 * Sets the ID for the \p i'th position for use with
465 * SelectionPosition::mappedId().
467 * \param[in] i Zero-based index
468 * \param[in] id Identifier to set.
470 * This method is not part of SelectionPosition because that interface
471 * only provides access to const data by design.
473 * This method can only be called after compilation, before the
474 * selection has been evaluated for any frame.
476 * \see SelectionPosition::mappedId()
478 void setOriginalId(int i, int id) { data().rawPositions_.m.orgid[i] = id; }
481 * Prints out one-line description of the selection.
483 * \param[in] fp Where to print the information.
485 * The output contains the name of the selection, the number of atoms
486 * and the number of positions, and indication of whether the selection
489 void printInfo(FILE *fp) const;
491 * Prints out extended information about the selection for debugging.
493 * \param[in] fp Where to print the information.
494 * \param[in] nmaxind Maximum number of values to print in lists
497 void printDebugInfo(FILE *fp, int nmaxind) const;
500 internal::SelectionData &data()
502 GMX_ASSERT(sel_ != NULL,
503 "Attempted to access uninitialized selection");
506 const internal::SelectionData &data() const
508 GMX_ASSERT(sel_ != NULL,
509 "Attempted to access uninitialized selection");
514 * Pointer to internal data for the selection.
516 * The memory for this object is managed by a SelectionCollection
517 * object, and the \ref Selection class simply provides a public
518 * interface for accessing the data.
520 internal::SelectionData *sel_;
523 * Needed to access the data to adjust flags.
525 friend class SelectionOptionStorage;
529 * Provides access to information about a single selected position.
531 * Each position has associated coordinates, and possibly velocities and forces
532 * if they have been requested and are available. It also has a set of atoms
533 * associated with it; typically the coordinates are the center-of-mass or
534 * center-of-geometry coordinates for that set of atoms. It is possible that
535 * there are not atoms associated if the selection has been provided as a fixed
538 * After the selection has been compiled, but not yet evaluated, the contents
539 * of the coordinate, velocity and force vectors are undefined.
541 * Default copy constructor and assignment operators are used, and work as
542 * intended: the copy references the same position and works identically.
544 * Methods in this class do not throw.
549 * \ingroup module_selection
551 class SelectionPosition
555 * Constructs a wrapper object for given selection position.
557 * \param[in] sel Selection from which the position is wrapped.
558 * \param[in] index Zero-based index of the position to wrap.
560 * Asserts if \p index is out of range.
562 * Only for internal use of the library. To obtain a SelectionPosition
563 * object in other code, use Selection::position().
565 SelectionPosition(const internal::SelectionData &sel, int index)
566 : sel_(&sel), i_(index)
568 GMX_ASSERT(index >= 0 && index < sel.posCount(),
569 "Invalid selection position index");
573 * Returns type of this position.
575 * Currently always returns the same as Selection::type().
577 e_index_t type() const { return sel_->type(); }
578 //! Returns coordinates for this position.
579 const rvec &x() const
581 return sel_->rawPositions_.x[i_];
584 * Returns velocity for this position.
586 * Must not be called if Selection::hasVelocities() returns false.
588 const rvec &v() const
590 GMX_ASSERT(sel_->rawPositions_.v != NULL,
591 "Velocities accessed, but unavailable");
592 return sel_->rawPositions_.v[i_];
595 * Returns force for this position.
597 * Must not be called if Selection::hasForces() returns false.
599 const rvec &f() const
601 GMX_ASSERT(sel_->rawPositions_.f != NULL,
602 "Velocities accessed, but unavailable");
603 return sel_->rawPositions_.f[i_];
606 * Returns total mass for this position.
608 * Returns the total mass of atoms that make up this position.
609 * If there are no atoms associated or masses are not available,
614 return sel_->posMass_[i_];
617 * Returns total charge for this position.
619 * Returns the sum of charges of atoms that make up this position.
620 * If there are no atoms associated or charges are not available,
625 return sel_->posCharge_[i_];
627 //! Returns the number of atoms that make up this position.
628 int atomCount() const
630 return sel_->rawPositions_.m.mapb.index[i_ + 1]
631 - sel_->rawPositions_.m.mapb.index[i_];
633 //! Return atom indices that make up this position.
634 ConstArrayRef<int> atomIndices() const
636 const int *atoms = sel_->rawPositions_.m.mapb.a;
639 return ConstArrayRef<int>();
641 const int first = sel_->rawPositions_.m.mapb.index[i_];
642 return ConstArrayRef<int>(&atoms[first], atomCount());
645 * Returns whether this position is selected in the current frame.
647 * The return value is equivalent to \c refid() == -1. Returns always
648 * true if SelectionOption::dynamicMask() has not been set.
652 bool selected() const
657 * Returns reference ID for this position.
659 * For dynamic selections, this provides means to associate positions
660 * across frames. After compilation, these IDs are consequently
661 * numbered starting from zero. For each frame, the ID then reflects
662 * the location of the position in the original array of positions.
663 * If SelectionOption::dynamicMask() has been set for the parent
664 * selection, the IDs for positions not present in the current
665 * selection are set to -1, otherwise they are removed completely.
668 * If a dynamic selection consists of at most three positions, after
669 * compilation refId() will return 0, 1, 2 for them, respectively.
670 * If for a particular frame, only the first and the third are present,
671 * refId() will return 0, 2.
672 * If SelectionOption::dynamicMask() has been set, all three positions
673 * can be accessed also for that frame and refId() will return 0, -1,
678 return sel_->rawPositions_.m.refid[i_];
681 * Returns mapped ID for this position.
683 * Returns ID of the position that corresponds to that set with
684 * Selection::setOriginalId().
686 * If for an array \c id, \c setOriginalId(i, id[i]) has been called
687 * for each \c i, then it always holds that
688 * \c mappedId()==id[refId()].
690 * Selection::setOriginalId() has not been called, the default values
691 * are dependent on type():
692 * - ::INDEX_ATOM: atom indices
693 * - ::INDEX_RES: residue numbers
694 * - ::INDEX_MOL: molecule numbers
696 * All the default values are zero-based
700 return sel_->rawPositions_.m.mapid[i_];
704 * Allows passing a selection position directly to neighborhood searching.
706 * When initialized this way, AnalysisNeighborhoodPair objects return
707 * the index that can be used to access this position using
708 * Selection::position().
710 * Works exactly like if AnalysisNeighborhoodPositions had a
711 * constructor taking a SelectionPosition object as a parameter.
712 * See AnalysisNeighborhoodPositions for rationale and additional
715 operator AnalysisNeighborhoodPositions() const;
718 const internal::SelectionData *sel_;
723 inline SelectionPosition
724 Selection::position(int i) const
726 return SelectionPosition(data(), i);