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