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