03762e4929274055152b6666e7165467879b60cc
[alexxy/gromacs.git] / src / gromacs / selection / sm_compare.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, 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 internal selection method for comparison expressions.
38  *
39  * \author Teemu Murtola <teemu.murtola@gmail.com>
40  * \ingroup module_selection
41  */
42 #include "gmxpre.h"
43
44 #include <cmath>
45
46 #include "gromacs/math/utilities.h"
47 #include "gromacs/utility/arraysize.h"
48 #include "gromacs/utility/basedefinitions.h"
49 #include "gromacs/utility/exceptions.h"
50 #include "gromacs/utility/smalloc.h"
51
52 #include "selmethod.h"
53
54 /** Defines the comparison operator for comparison expressions. */
55 typedef enum
56 {
57     CMP_INVALID,        /**< Indicates an error */
58     CMP_LESS,           /**< '<' */
59     CMP_LEQ,            /**< '<=' */
60     CMP_GTR,            /**< '>' */
61     CMP_GEQ,            /**< '>=' */
62     CMP_EQUAL,          /**< '==' */
63     CMP_NEQ             /**< '!=' */
64 } e_comparison_t;
65
66 /** The operand has a single value. */
67 #define CMP_SINGLEVAL  1
68 /** The operand value is dynamic. */
69 #define CMP_DYNAMICVAL 2
70 /** The value is real. */
71 #define CMP_REALVAL    4
72 /** The integer array is allocated. */
73 #define CMP_ALLOCINT   16
74 /** The real array is allocated. */
75 #define CMP_ALLOCREAL  32
76
77 /*! \internal \brief
78  * Data structure for comparison expression operand values.
79  */
80 typedef struct
81 {
82     /** Flags that describe the type of the operand. */
83     int             flags;
84     /** (Array of) integer value(s). */
85     int            *i;
86     /** (Array of) real value(s). */
87     real           *r;
88 } t_compare_value;
89
90 /*! \internal \brief
91  * Data structure for comparison expression evaluation.
92  */
93 typedef struct
94 {
95     /** Comparison operator as a string. */
96     char            *cmpop;
97     /** Comparison operator type. */
98     e_comparison_t   cmpt;
99     /** Left value. */
100     t_compare_value  left;
101     /** Right value. */
102     t_compare_value  right;
103 } t_methoddata_compare;
104
105 /*! \brief
106  * Allocates data for comparison expression evaluation.
107  *
108  * \param[in]     npar  Not used (should be 5).
109  * \param[in,out] param Method parameters (should point to a copy of
110  *   \ref smparams_compare).
111  * \returns       Pointer to the allocated data (\c t_methoddata_compare).
112  *
113  * Allocates memory for a \c t_methoddata_compare structure.
114  */
115 static void *
116 init_data_compare(int npar, gmx_ana_selparam_t *param);
117 /*! \brief
118  * Initializes data for comparison expression evaluation.
119  *
120  * \param[in] top   Not used.
121  * \param[in] npar  Not used (should be 5).
122  * \param[in] param Method parameters (should point to \ref smparams_compare).
123  * \param[in] data  Should point to a \c t_methoddata_compare.
124  * \returns   0 if the input data is valid, -1 on error.
125  */
126 static void
127 init_compare(const gmx_mtop_t *top, int npar, gmx_ana_selparam_t *param, void *data);
128 /** Frees the memory allocated for comparison expression evaluation. */
129 static void
130 free_data_compare(void *data);
131 /*! \brief
132  * Evaluates comparison expressions.
133  *
134  * \param[in]  context  Not used.
135  * \param[in]  g        Evaluation index group.
136  * \param[out] out      Output data structure (\p out->u.g is used).
137  * \param[in]  data     Should point to a \c t_methoddata_compare.
138  */
139 static void
140 evaluate_compare(const gmx::SelMethodEvalContext &context,
141                  gmx_ana_index_t *g, gmx_ana_selvalue_t *out, void *data);
142
143 /** Parameters for comparison expression evaluation. */
144 static gmx_ana_selparam_t smparams_compare[] = {
145     {"int1",  {INT_VALUE,  -1, {nullptr}}, nullptr,
146      SPAR_OPTIONAL | SPAR_DYNAMIC | SPAR_ATOMVAL},
147     {"real1", {REAL_VALUE, -1, {nullptr}}, nullptr,
148      SPAR_OPTIONAL | SPAR_DYNAMIC | SPAR_ATOMVAL},
149     {"op",    {STR_VALUE,   1, {nullptr}}, nullptr, 0},
150     {"int2",  {INT_VALUE,  -1, {nullptr}}, nullptr,
151      SPAR_OPTIONAL | SPAR_DYNAMIC | SPAR_ATOMVAL},
152     {"real2", {REAL_VALUE, -1, {nullptr}}, nullptr,
153      SPAR_OPTIONAL | SPAR_DYNAMIC | SPAR_ATOMVAL},
154 };
155
156 /** \internal Selection method data for comparison expression evaluation. */
157 gmx_ana_selmethod_t sm_compare = {
158     "cmp", GROUP_VALUE, SMETH_SINGLEVAL,
159     asize(smparams_compare), smparams_compare,
160     &init_data_compare,
161     nullptr,
162     &init_compare,
163     nullptr,
164     &free_data_compare,
165     nullptr,
166     &evaluate_compare,
167     nullptr,
168     {nullptr, nullptr, 0, nullptr},
169 };
170
171 /*! \brief
172  * Returns a \c e_comparison_t value corresponding to an operator.
173  *
174  * \param[in] str  String to process.
175  * \returns   The comparison type corresponding to the first one or two
176  *   characters of \p str.
177  *
178  * \p str can contain any number of characters; only the first two
179  * are used.
180  * If the beginning of \p str does not match any of the recognized types,
181  * \ref CMP_INVALID is returned.
182  */
183 static e_comparison_t
184 comparison_type(char *str)
185 {
186     switch (str[0])
187     {
188         case '<': return (str[1] == '=') ? CMP_LEQ   : CMP_LESS;
189         case '>': return (str[1] == '=') ? CMP_GEQ   : CMP_GTR;
190         case '=': return (str[1] == '=') ? CMP_EQUAL : CMP_INVALID;
191         case '!': return (str[1] == '=') ? CMP_NEQ   : CMP_INVALID;
192     }
193     return CMP_INVALID;
194 }
195
196 /*! \brief
197  * Returns a string corresponding to a \c e_comparison_t value.
198  *
199  * \param[in] cmpt  Comparison type to convert.
200  * \returns   Pointer to a string that corresponds to \p cmpt.
201  *
202  * The return value points to a string constant and should not be \p free'd.
203  *
204  * The function returns NULL if \p cmpt is not one of the valid values.
205  */
206 static const char *
207 comparison_type_str(e_comparison_t cmpt)
208 {
209     const char *p = nullptr;
210     switch (cmpt)
211     {
212         case CMP_INVALID: p = "INVALID"; break;
213         case CMP_LESS:    p = "<";       break;
214         case CMP_LEQ:     p = "<=";      break;
215         case CMP_GTR:     p = ">";       break;
216         case CMP_GEQ:     p = ">=";      break;
217         case CMP_EQUAL:   p = "==";      break;
218         case CMP_NEQ:     p = "!=";      break;
219             // No default clause so we intentionally get compiler errors
220             // if new selection choices are added later.
221     }
222     return p;
223 }
224
225 /*!
226  * \param[in] fp    File to receive the output.
227  * \param[in] data  Should point to a \c t_methoddata_compare.
228  */
229 void
230 _gmx_selelem_print_compare_info(FILE *fp, void *data)
231 {
232     t_methoddata_compare *d = (t_methoddata_compare *)data;
233
234     fprintf(fp, " \"");
235     /* Print the left value */
236     if ((d->left.flags & CMP_SINGLEVAL) && !(d->left.flags & CMP_DYNAMICVAL))
237     {
238         if (d->left.flags & CMP_REALVAL)
239         {
240             fprintf(fp, "%f ", d->left.r[0]);
241         }
242         else
243         {
244             fprintf(fp, "%d ", d->left.i[0]);
245         }
246     }
247     /* Print the operator */
248     if (d->cmpt != CMP_INVALID)
249     {
250         fprintf(fp, "%s", comparison_type_str(d->cmpt));
251     }
252     else
253     {
254         fprintf(fp, "%s", d->cmpop);
255     }
256     /* Print the right value */
257     if ((d->right.flags & CMP_SINGLEVAL) && !(d->right.flags & CMP_DYNAMICVAL))
258     {
259         if (d->right.flags & CMP_REALVAL)
260         {
261             fprintf(fp, " %f", d->right.r[0]);
262         }
263         else
264         {
265             fprintf(fp, " %d", d->right.i[0]);
266         }
267     }
268     fprintf(fp, "\"");
269 }
270
271 static void *
272 init_data_compare(int /* npar */, gmx_ana_selparam_t *param)
273 {
274     t_methoddata_compare *data;
275
276     snew(data, 1);
277     param[2].val.u.s = &data->cmpop;
278     return data;
279 }
280
281 /*! \brief
282  * Reverses a comparison operator.
283  *
284  * \param[in] type  Comparison operator to reverse.
285  * \returns   The correct comparison operator that equals \p type when the
286  *   left and right sides are interchanged.
287  */
288 static e_comparison_t
289 reverse_comparison_type(e_comparison_t type)
290 {
291     switch (type)
292     {
293         case CMP_LESS: return CMP_GTR;
294         case CMP_LEQ:  return CMP_GEQ;
295         case CMP_GTR:  return CMP_LESS;
296         case CMP_GEQ:  return CMP_LEQ;
297         default:       break;
298     }
299     return type;
300 }
301
302 /*! \brief
303  * Initializes the value storage for comparison expression.
304  *
305  * \param[out] val   Value structure to initialize.
306  * \param[in]  param Parameters to use for initialization.
307  * \returns    The number of values provided for the value, 0 on error.
308  */
309 static int
310 init_comparison_value(t_compare_value *val, gmx_ana_selparam_t param[2])
311 {
312     int  n;
313
314     val->flags = 0;
315     if (param[0].flags & SPAR_SET)
316     {
317         val->flags |=  (param[0].flags & SPAR_DYNAMIC) ? CMP_DYNAMICVAL : 0;
318         val->flags |= !(param[0].flags & SPAR_ATOMVAL) ? CMP_SINGLEVAL  : 0;
319         n           = param[0].val.nr;
320         val->i      = param[0].val.u.i;
321     }
322     else if (param[1].flags & SPAR_SET)
323     {
324         val->flags |=  (param[1].flags & SPAR_DYNAMIC) ? CMP_DYNAMICVAL : 0;
325         val->flags |= !(param[1].flags & SPAR_ATOMVAL) ? CMP_SINGLEVAL  : 0;
326         val->flags |= CMP_REALVAL;
327         n           = param[1].val.nr;
328         val->r      = param[1].val.u.r;
329     }
330     else
331     {
332         n           = 0;
333         val->i      = nullptr;
334         val->r      = nullptr;
335     }
336     return n;
337 }
338
339 /*! \brief
340  * Converts an integer value to floating point.
341  *
342  * \param[in]     n   Number of values in the \p val->u array.
343  * \param[in,out] val Value to convert.
344  */
345 static void
346 convert_int_real(int n, t_compare_value *val)
347 {
348     int   i;
349     real *rv;
350
351     snew(rv, n);
352     for (i = 0; i < n; ++i)
353     {
354         rv[i] = (real)val->i[i];
355     }
356     /* Free the previous value if one is present. */
357     sfree(val->r);
358     val->r      = rv;
359     val->flags |= CMP_REALVAL | CMP_ALLOCREAL;
360 }
361
362 /*! \brief
363  * Converts a floating point value to integer.
364  *
365  * \param[in]     n      Number of values in the \p val->u array.
366  * \param[in,out] val    Value to convert.
367  * \param[in]     cmpt   Comparison operator type.
368  * \param[in]     bRight true if \p val appears on the right hand size of
369  *   \p cmpt.
370  * \returns       0 on success, EINVAL on error.
371  *
372  * The values are rounded such that the same comparison operator can be used.
373  */
374 static void
375 convert_real_int(int n, t_compare_value *val, e_comparison_t cmpt, bool bRight)
376 {
377     int   i;
378     int  *iv;
379
380     if (!bRight)
381     {
382         cmpt = reverse_comparison_type(cmpt);
383     }
384     snew(iv, n);
385     /* Round according to the comparison type */
386     for (i = 0; i < n; ++i)
387     {
388         switch (cmpt)
389         {
390             case CMP_LESS:
391             case CMP_GEQ:
392                 iv[i] = static_cast<int>(std::ceil(val->r[i]));
393                 break;
394             case CMP_GTR:
395             case CMP_LEQ:
396                 iv[i] = static_cast<int>(std::floor(val->r[i]));
397                 break;
398             case CMP_EQUAL:
399             case CMP_NEQ:
400                 sfree(iv);
401                 /* TODO: Implement, although it isn't typically very useful.
402                  * Implementation is only a matter of proper initialization,
403                  * the evaluation function can already handle this case with
404                  * proper preparations. */
405                 GMX_THROW(gmx::NotImplementedError("Equality comparison between dynamic integer and static real expressions not implemented"));
406             case CMP_INVALID: /* Should not be reached */
407                 sfree(iv);
408                 GMX_THROW(gmx::InternalError("Invalid comparison type"));
409         }
410     }
411     /* Free the previous value if one is present. */
412     sfree(val->i);
413     val->i      = iv;
414     val->flags &= ~CMP_REALVAL;
415     val->flags |= CMP_ALLOCINT;
416 }
417
418 static void
419 init_compare(const gmx_mtop_t * /* top */, int /* npar */, gmx_ana_selparam_t *param, void *data)
420 {
421     t_methoddata_compare *d = (t_methoddata_compare *)data;
422     int                   n1, n2;
423
424     /* Store the values */
425     n1 = init_comparison_value(&d->left, &param[0]);
426     n2 = init_comparison_value(&d->right, &param[3]);
427     /* Store the comparison type */
428     d->cmpt = comparison_type(d->cmpop);
429     if (d->cmpt == CMP_INVALID)
430     {
431         GMX_THROW(gmx::InternalError("Invalid comparison type"));
432     }
433     /* Convert the values to the same type */
434     /* TODO: Currently, there are no dynamic integer-valued selection methods,
435      * which means that only the branches with convert_int_real() will ever be
436      * taken. It should be considered whether it is necessary to support these
437      * other cases at all.
438      */
439     if ((d->left.flags & CMP_REALVAL) && !(d->right.flags & CMP_REALVAL))
440     {
441         if (d->left.flags & d->right.flags & CMP_DYNAMICVAL)
442         {
443             /* Nothing can be done */
444         }
445         else if (!(d->right.flags & CMP_DYNAMICVAL))
446         {
447             convert_int_real(n2, &d->right);
448         }
449         else /* d->left is static */
450         {
451             convert_real_int(n1, &d->left, d->cmpt, false);
452         }
453     }
454     else if (!(d->left.flags & CMP_REALVAL) && (d->right.flags & CMP_REALVAL))
455     {
456         if (d->left.flags & d->right.flags & CMP_DYNAMICVAL)
457         {
458             /* Reverse the sides to place the integer on the right */
459             int    flags;
460             d->left.r      = d->right.r;
461             d->right.r     = nullptr;
462             d->right.i     = d->left.i;
463             d->left.i      = nullptr;
464             flags          = d->left.flags;
465             d->left.flags  = d->right.flags;
466             d->right.flags = flags;
467             d->cmpt        = reverse_comparison_type(d->cmpt);
468         }
469         else if (!(d->left.flags & CMP_DYNAMICVAL))
470         {
471             convert_int_real(n1, &d->left);
472         }
473         else /* d->right is static */
474         {
475             convert_real_int(n2, &d->right, d->cmpt, true);
476         }
477     }
478 }
479
480 /*!
481  * \param data Data to free (should point to a \c t_methoddata_compare).
482  *
483  * Frees the memory allocated for \c t_methoddata_compare.
484  */
485 static void
486 free_data_compare(void *data)
487 {
488     t_methoddata_compare *d = (t_methoddata_compare *)data;
489
490     sfree(d->cmpop);
491     if (d->left.flags & CMP_ALLOCINT)
492     {
493         sfree(d->left.i);
494     }
495     if (d->left.flags & CMP_ALLOCREAL)
496     {
497         sfree(d->left.r);
498     }
499     if (d->right.flags & CMP_ALLOCINT)
500     {
501         sfree(d->right.i);
502     }
503     if (d->right.flags & CMP_ALLOCREAL)
504     {
505         sfree(d->right.r);
506     }
507     sfree(d);
508 }
509
510 /*! \brief
511  * Implementation for evaluate_compare() for integer values.
512  *
513  * \param[in]  g     Evaluation index group.
514  * \param[out] out   Output data structure (\p out->u.g is used).
515  * \param[in]  data  Should point to a \c t_methoddata_compare.
516  */
517 static void
518 evaluate_compare_int(gmx_ana_index_t *g, gmx_ana_selvalue_t *out, void *data)
519 {
520     t_methoddata_compare *d = (t_methoddata_compare *)data;
521     int                   i, i1, i2, ig;
522     int                   a, b;
523     bool                  bAccept;
524
525     for (i = i1 = i2 = ig = 0; i < g->isize; ++i)
526     {
527         a       = d->left.i[i1];
528         b       = d->right.i[i2];
529         bAccept = false;
530         switch (d->cmpt)
531         {
532             case CMP_INVALID: break;
533             case CMP_LESS:    bAccept = a <  b; break;
534             case CMP_LEQ:     bAccept = a <= b; break;
535             case CMP_GTR:     bAccept = a >  b; break;
536             case CMP_GEQ:     bAccept = a >= b; break;
537             case CMP_EQUAL:   bAccept = a == b; break;
538             case CMP_NEQ:     bAccept = a != b; break;
539         }
540         if (bAccept)
541         {
542             out->u.g->index[ig++] = g->index[i];
543         }
544         if (!(d->left.flags & CMP_SINGLEVAL))
545         {
546             ++i1;
547         }
548         if (!(d->right.flags & CMP_SINGLEVAL))
549         {
550             ++i2;
551         }
552     }
553     out->u.g->isize = ig;
554 }
555
556 /*! \brief
557  * Implementation for evaluate_compare() if either value is non-integer.
558  *
559  * \param[in]  g     Evaluation index group.
560  * \param[out] out   Output data structure (\p out->u.g is used).
561  * \param[in]  data  Should point to a \c t_methoddata_compare.
562  *
563  * Left value is assumed to be real-valued; right value can be either.
564  * This is ensured by the initialization method.
565  */
566 static void
567 evaluate_compare_real(gmx_ana_index_t *g, gmx_ana_selvalue_t *out, void *data)
568 {
569     t_methoddata_compare *d = (t_methoddata_compare *)data;
570     int                   i, i1, i2, ig;
571     real                  a, b;
572     bool                  bAccept;
573
574     for (i = i1 = i2 = ig = 0; i < g->isize; ++i)
575     {
576         a       = d->left.r[i1];
577         b       = (d->right.flags & CMP_REALVAL) ? d->right.r[i2] : d->right.i[i2];
578         bAccept = false;
579         switch (d->cmpt)
580         {
581             case CMP_INVALID: break;
582             case CMP_LESS:    bAccept = a <  b; break;
583             case CMP_LEQ:     bAccept = a <= b; break;
584             case CMP_GTR:     bAccept = a >  b; break;
585             case CMP_GEQ:     bAccept = a >= b; break;
586             case CMP_EQUAL:   bAccept =  gmx_within_tol(a, b, GMX_REAL_EPS); break;
587             case CMP_NEQ:     bAccept = !gmx_within_tol(a, b, GMX_REAL_EPS); break;
588         }
589         if (bAccept)
590         {
591             out->u.g->index[ig++] = g->index[i];
592         }
593         if (!(d->left.flags & CMP_SINGLEVAL))
594         {
595             ++i1;
596         }
597         if (!(d->right.flags & CMP_SINGLEVAL))
598         {
599             ++i2;
600         }
601     }
602     out->u.g->isize = ig;
603 }
604
605 static void
606 evaluate_compare(const gmx::SelMethodEvalContext & /*context*/,
607                  gmx_ana_index_t *g, gmx_ana_selvalue_t *out, void *data)
608 {
609     t_methoddata_compare *d = (t_methoddata_compare *)data;
610
611     if (!((d->left.flags | d->right.flags) & CMP_REALVAL))
612     {
613         evaluate_compare_int(g, out, data);
614     }
615     else
616     {
617         evaluate_compare_real(g, out, data);
618     }
619 }