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