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