Sort all includes in src/gromacs
[alexxy/gromacs.git] / src / gromacs / selection / selection.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2009,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 /*! \internal \file
36  * \brief
37  * Implements classes in selection.h.
38  *
39  * \author Teemu Murtola <teemu.murtola@gmail.com>
40  * \ingroup module_selection
41  */
42 #include "gmxpre.h"
43
44 #include "selection.h"
45
46 #include "gromacs/selection/nbsearch.h"
47 #include "gromacs/selection/position.h"
48 #include "gromacs/topology/topology.h"
49
50 #include "selelem.h"
51 #include "selvalue.h"
52
53 namespace gmx
54 {
55
56 namespace internal
57 {
58
59 /********************************************************************
60  * SelectionData
61  */
62
63 SelectionData::SelectionData(SelectionTreeElement *elem,
64                              const char           *selstr)
65     : name_(elem->name()), selectionText_(selstr),
66       rootElement_(*elem), coveredFractionType_(CFRAC_NONE),
67       coveredFraction_(1.0), averageCoveredFraction_(1.0),
68       bDynamic_(false), bDynamicCoveredFraction_(false)
69 {
70     if (elem->child->type == SEL_CONST)
71     {
72         // TODO: This is not exception-safe if any called function throws.
73         gmx_ana_pos_copy(&rawPositions_, elem->child->v.u.p, true);
74     }
75     else
76     {
77         SelectionTreeElementPointer child = elem->child;
78         child->flags     &= ~SEL_ALLOCVAL;
79         _gmx_selvalue_setstore(&child->v, &rawPositions_);
80         /* We should also skip any modifiers to determine the dynamic
81          * status. */
82         while (child->type == SEL_MODIFIER)
83         {
84             child = child->child;
85             if (child->type == SEL_SUBEXPRREF)
86             {
87                 child = child->child;
88                 /* Because most subexpression elements are created
89                  * during compilation, we need to check for them
90                  * explicitly here.
91                  */
92                 if (child->type == SEL_SUBEXPR)
93                 {
94                     child = child->child;
95                 }
96             }
97         }
98         /* For variable references, we should skip the
99          * SEL_SUBEXPRREF and SEL_SUBEXPR elements. */
100         if (child->type == SEL_SUBEXPRREF)
101         {
102             child = child->child->child;
103         }
104         bDynamic_ = (child->child->flags & SEL_DYNAMIC);
105     }
106     initCoveredFraction(CFRAC_NONE);
107 }
108
109
110 SelectionData::~SelectionData()
111 {
112 }
113
114
115 bool
116 SelectionData::initCoveredFraction(e_coverfrac_t type)
117 {
118     coveredFractionType_ = type;
119     if (type == CFRAC_NONE)
120     {
121         bDynamicCoveredFraction_ = false;
122     }
123     else if (!_gmx_selelem_can_estimate_cover(rootElement()))
124     {
125         coveredFractionType_     = CFRAC_NONE;
126         bDynamicCoveredFraction_ = false;
127     }
128     else
129     {
130         bDynamicCoveredFraction_ = true;
131     }
132     coveredFraction_        = bDynamicCoveredFraction_ ? 0.0 : 1.0;
133     averageCoveredFraction_ = coveredFraction_;
134     return type == CFRAC_NONE || coveredFractionType_ != CFRAC_NONE;
135 }
136
137 namespace
138 {
139
140 /*! \brief
141  * Helper function to compute total masses and charges for positions.
142  *
143  * \param[in]  top     Topology to take atom masses from.
144  * \param[in]  pos     Positions to compute masses and charges for.
145  * \param[out] masses  Output masses.
146  * \param[out] charges Output charges.
147  *
148  * Does not throw if enough space has been reserved for the output vectors.
149  */
150 void computeMassesAndCharges(const t_topology *top, const gmx_ana_pos_t &pos,
151                              std::vector<real> *masses,
152                              std::vector<real> *charges)
153 {
154     GMX_ASSERT(top != NULL, "Should not have been called with NULL topology");
155     masses->clear();
156     charges->clear();
157     for (int b = 0; b < pos.count(); ++b)
158     {
159         real mass   = 0.0;
160         real charge = 0.0;
161         for (int i = pos.m.mapb.index[b]; i < pos.m.mapb.index[b+1]; ++i)
162         {
163             const int index = pos.m.mapb.a[i];
164             mass   += top->atoms.atom[index].m;
165             charge += top->atoms.atom[index].q;
166         }
167         masses->push_back(mass);
168         charges->push_back(charge);
169     }
170 }
171
172 }       // namespace
173
174 void
175 SelectionData::refreshName()
176 {
177     rootElement_.fillNameIfMissing(selectionText_.c_str());
178     name_ = rootElement_.name();
179 }
180
181 void
182 SelectionData::initializeMassesAndCharges(const t_topology *top)
183 {
184     GMX_ASSERT(posMass_.empty() && posCharge_.empty(),
185                "Should not be called more than once");
186     posMass_.reserve(posCount());
187     posCharge_.reserve(posCount());
188     if (top == NULL)
189     {
190         posMass_.resize(posCount(), 1.0);
191         posCharge_.resize(posCount(), 0.0);
192     }
193     else
194     {
195         computeMassesAndCharges(top, rawPositions_, &posMass_, &posCharge_);
196     }
197 }
198
199
200 void
201 SelectionData::refreshMassesAndCharges(const t_topology *top)
202 {
203     if (top != NULL && isDynamic() && !hasFlag(efSelection_DynamicMask))
204     {
205         computeMassesAndCharges(top, rawPositions_, &posMass_, &posCharge_);
206     }
207 }
208
209
210 void
211 SelectionData::updateCoveredFractionForFrame()
212 {
213     if (isCoveredFractionDynamic())
214     {
215         real cfrac = _gmx_selelem_estimate_coverfrac(rootElement());
216         coveredFraction_         = cfrac;
217         averageCoveredFraction_ += cfrac;
218     }
219 }
220
221
222 void
223 SelectionData::computeAverageCoveredFraction(int nframes)
224 {
225     if (isCoveredFractionDynamic() && nframes > 0)
226     {
227         averageCoveredFraction_ /= nframes;
228     }
229 }
230
231
232 void
233 SelectionData::restoreOriginalPositions(const t_topology *top)
234 {
235     if (isDynamic())
236     {
237         gmx_ana_pos_t &p = rawPositions_;
238         gmx_ana_indexmap_update(&p.m, rootElement().v.u.g,
239                                 hasFlag(gmx::efSelection_DynamicMask));
240         refreshMassesAndCharges(top);
241     }
242 }
243
244 }   // namespace internal
245
246 /********************************************************************
247  * Selection
248  */
249
250 Selection::operator AnalysisNeighborhoodPositions() const
251 {
252     AnalysisNeighborhoodPositions pos(data().rawPositions_.x,
253                                       data().rawPositions_.count());
254     if (hasOnlyAtoms())
255     {
256         pos.exclusionIds(atomIndices());
257     }
258     return pos;
259 }
260
261
262 void
263 Selection::printInfo(FILE *fp) const
264 {
265     fprintf(fp, "\"%s\" (%d position%s, %d atom%s%s)", name(),
266             posCount(),  posCount()  == 1 ? "" : "s",
267             atomCount(), atomCount() == 1 ? "" : "s",
268             isDynamic() ? ", dynamic" : "");
269     fprintf(fp, "\n");
270 }
271
272
273 void
274 Selection::printDebugInfo(FILE *fp, int nmaxind) const
275 {
276     const gmx_ana_pos_t &p = data().rawPositions_;
277
278     fprintf(fp, "  ");
279     printInfo(fp);
280     fprintf(fp, "    Group ");
281     gmx_ana_index_t g;
282     gmx_ana_index_set(&g, p.m.mapb.nra, p.m.mapb.a, 0);
283     gmx_ana_index_dump(fp, &g, nmaxind);
284
285     fprintf(fp, "    Block (size=%d):", p.m.mapb.nr);
286     if (!p.m.mapb.index)
287     {
288         fprintf(fp, " (null)");
289     }
290     else
291     {
292         int n = p.m.mapb.nr;
293         if (nmaxind >= 0 && n > nmaxind)
294         {
295             n = nmaxind;
296         }
297         for (int i = 0; i <= n; ++i)
298         {
299             fprintf(fp, " %d", p.m.mapb.index[i]);
300         }
301         if (n < p.m.mapb.nr)
302         {
303             fprintf(fp, " ...");
304         }
305     }
306     fprintf(fp, "\n");
307
308     int n = posCount();
309     if (nmaxind >= 0 && n > nmaxind)
310     {
311         n = nmaxind;
312     }
313     fprintf(fp, "    RefId:");
314     if (!p.m.refid)
315     {
316         fprintf(fp, " (null)");
317     }
318     else
319     {
320         for (int i = 0; i < n; ++i)
321         {
322             fprintf(fp, " %d", p.m.refid[i]);
323         }
324         if (n < posCount())
325         {
326             fprintf(fp, " ...");
327         }
328     }
329     fprintf(fp, "\n");
330
331     fprintf(fp, "    MapId:");
332     if (!p.m.mapid)
333     {
334         fprintf(fp, " (null)");
335     }
336     else
337     {
338         for (int i = 0; i < n; ++i)
339         {
340             fprintf(fp, " %d", p.m.mapid[i]);
341         }
342         if (n < posCount())
343         {
344             fprintf(fp, " ...");
345         }
346     }
347     fprintf(fp, "\n");
348 }
349
350
351 /********************************************************************
352  * SelectionPosition
353  */
354
355 SelectionPosition::operator AnalysisNeighborhoodPositions() const
356 {
357     AnalysisNeighborhoodPositions pos(sel_->rawPositions_.x,
358                                       sel_->rawPositions_.count());
359     if (sel_->hasOnlyAtoms())
360     {
361         // TODO: Move atomIndices() such that it can be reused here as well.
362         pos.exclusionIds(constArrayRefFromArray<int>(sel_->rawPositions_.m.mapb.a,
363                                                      sel_->rawPositions_.m.mapb.nra));
364     }
365     return pos.selectSingleFromArray(i_);
366 }
367
368 } // namespace gmx