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