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