a648c3ca4f8ee3d6fb922c097271f6a1b7831706
[alexxy/gromacs.git] / src / gromacs / selection / selmethod.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2009-2018, The GROMACS development team.
5  * Copyright (c) 2019, by the GROMACS development team, led by
6  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
7  * and including many others, as listed in the AUTHORS file in the
8  * top-level source directory and at http://www.gromacs.org.
9  *
10  * GROMACS is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Lesser General Public License
12  * as published by the Free Software Foundation; either version 2.1
13  * of the License, or (at your option) any later version.
14  *
15  * GROMACS is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public
21  * License along with GROMACS; if not, see
22  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
23  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
24  *
25  * If you want to redistribute modifications to GROMACS, please
26  * consider that scientific software is very special. Version
27  * control is crucial - bugs must be traceable. We will be happy to
28  * consider code for inclusion in the official distribution, but
29  * derived work must not be called official GROMACS. Details are found
30  * in the README & COPYING files - if they are missing, get the
31  * official version at http://www.gromacs.org.
32  *
33  * To help us fund GROMACS development, we humbly ask that you cite
34  * the research papers on the package. Check out http://www.gromacs.org.
35  */
36 /*! \internal \file
37  * \brief
38  * Implements functions in selmethod.h.
39  *
40  * \author Teemu Murtola <teemu.murtola@gmail.com>
41  * \ingroup module_selection
42  */
43 #include "gmxpre.h"
44
45 #include "selmethod.h"
46
47 #include <cctype>
48 #include <cstdarg>
49
50 #include "gromacs/utility/arraysize.h"
51 #include "gromacs/utility/cstringutil.h"
52 #include "gromacs/utility/exceptions.h"
53 #include "gromacs/utility/stringutil.h"
54
55 #include "selmethod_impl.h"
56 #include "symrec.h"
57
58 /*! \internal \brief
59  * Helper structure for defining selection methods.
60  */
61 typedef struct
62 {
63     /*! \brief
64      * Name to register the method under.
65      *
66      * If NULL, use the actual name of the method.
67      * This field is used for defining synonyms.
68      */
69     const char* name;
70     /** Method data structure to register. */
71     gmx_ana_selmethod_t* method;
72 } t_register_method;
73
74 /*! \brief
75  * Convenience function for reporting errors found in selection methods.
76  */
77 static void report_error(FILE* fp, const char* name, gmx_fmtstr const char* fmt, ...)
78         gmx_format(printf, 3, 4);
79
80 static void report_error(FILE* fp, const char* name, gmx_fmtstr const char* fmt, ...)
81 {
82     va_list ap;
83     va_start(ap, fmt);
84     if (fp)
85     {
86         fprintf(fp, "selection method '%s': ", name);
87         vfprintf(fp, fmt, ap);
88         fprintf(fp, "\n");
89     }
90     va_end(ap);
91 }
92
93 /*! \brief
94  * Convenience function for reporting errors found in selection method parameters.
95  */
96 static void report_param_error(FILE* fp, const char* mname, const char* pname, gmx_fmtstr const char* fmt, ...)
97         gmx_format(printf, 4, 5);
98 static void report_param_error(FILE* fp, const char* mname, const char* pname, gmx_fmtstr const char* fmt, ...)
99 {
100     va_list ap;
101     va_start(ap, fmt);
102     if (fp)
103     {
104         fprintf(fp, "selection method '%s': parameter '%s': ", mname, pname);
105         vfprintf(fp, fmt, ap);
106         fprintf(fp, "\n");
107     }
108     va_end(ap);
109 }
110
111 /*! \brief
112  * Checks the validity of parameters.
113  *
114  * \param[in]     fp      File handle to use for diagnostic messages
115  *   (can be NULL).
116  * \param[in]     name    Name of the method (used for error messages).
117  * \param[in]     nparams Number of parameters in \p param.
118  * \param[in,out] param   Parameter array
119  *   (only the \c flags field of boolean parameters may be modified).
120  * \param[in]     symtab  Symbol table (used for checking overlaps).
121  * \returns       true if there are no problems with the parameters,
122  *   false otherwise.
123  *
124  * This function performs some checks common to both check_method() and
125  * check_modifier().
126  * The purpose of these checks is to ensure that the selection parser does not
127  * need to check for the validity of the parameters at each turn, and to
128  * report programming errors as early as possible.
129  * If you remove a check, make sure that the parameter parser can handle the
130  * resulting parameters.
131  */
132 static bool check_params(FILE*                                  fp,
133                          const char*                            name,
134                          int                                    nparams,
135                          gmx_ana_selparam_t                     param[],
136                          const gmx::SelectionParserSymbolTable& symtab)
137 {
138     bool bOk = true;
139     int  i, j;
140
141     if (nparams > 0 && !param)
142     {
143         report_error(fp, name, "error: missing parameter data");
144         return false;
145     }
146     if (nparams == 0 && param)
147     {
148         report_error(fp, name, "warning: parameter data unused because nparams=0");
149     }
150     /* Check each parameter */
151     for (i = 0; i < nparams; ++i)
152     {
153         /* Check that there is at most one NULL name, in the beginning */
154         if (param[i].name == nullptr && i > 0)
155         {
156             report_error(fp, name, "error: NULL parameter should be the first one");
157             bOk = false;
158             continue;
159         }
160         /* Check for duplicates */
161         for (j = 0; j < i; ++j)
162         {
163             if (param[j].name == nullptr)
164             {
165                 continue;
166             }
167             if (!gmx_strcasecmp(param[i].name, param[j].name))
168             {
169                 report_error(fp, name, "error: duplicate parameter name '%s'", param[i].name);
170                 bOk = false;
171                 break;
172             }
173         }
174         /* Check flags */
175         if (param[i].flags & SPAR_SET)
176         {
177             report_param_error(fp, name, param[i].name, "warning: flag SPAR_SET is set");
178             param[i].flags &= ~SPAR_SET;
179         }
180         if (param[i].flags & SPAR_RANGES)
181         {
182             if (param[i].val.type != INT_VALUE && param[i].val.type != REAL_VALUE)
183             {
184                 report_param_error(fp, name, param[i].name,
185                                    "error: SPAR_RANGES cannot be set for a non-numeric parameter");
186                 bOk = false;
187             }
188             if (param[i].flags & SPAR_DYNAMIC)
189             {
190                 report_param_error(fp, name, param[i].name,
191                                    "warning: SPAR_DYNAMIC does not have effect with SPAR_RANGES");
192                 param[i].flags &= ~SPAR_DYNAMIC;
193             }
194             if (!(param[i].flags & SPAR_VARNUM) && param[i].val.nr != 1)
195             {
196                 report_param_error(
197                         fp, name, param[i].name,
198                         "error: range should take either one or an arbitrary number of values");
199                 bOk = false;
200             }
201             if (param[i].flags & SPAR_ATOMVAL)
202             {
203                 report_param_error(fp, name, param[i].name,
204                                    "error: SPAR_RANGES and SPAR_ATOMVAL both set");
205                 bOk = false;
206             }
207         }
208         if ((param[i].flags & SPAR_VARNUM) && (param[i].flags & SPAR_ATOMVAL))
209         {
210             report_param_error(fp, name, param[i].name,
211                                "error: SPAR_VARNUM and SPAR_ATOMVAL both set");
212             bOk = false;
213         }
214         if (param[i].flags & SPAR_ENUMVAL)
215         {
216             if (param[i].val.type != STR_VALUE)
217             {
218                 report_param_error(fp, name, param[i].name,
219                                    "error: SPAR_ENUMVAL can only be set for string parameters");
220                 bOk = false;
221             }
222             if (param[i].val.nr != 1)
223             {
224                 report_param_error(fp, name, param[i].name,
225                                    "error: SPAR_ENUMVAL parameters should take exactly one value");
226                 bOk = false;
227             }
228             if (param[i].flags & (SPAR_DYNAMIC | SPAR_VARNUM | SPAR_ATOMVAL))
229             {
230                 report_param_error(fp, name, param[i].name,
231                                    "error: only SPAR_OPTIONAL supported with SPAR_ENUMVAL");
232                 bOk = false;
233             }
234         }
235         /* Check boolean parameters */
236         if (param[i].val.type == NO_VALUE)
237         {
238             if (param[i].val.nr != 0)
239             {
240                 report_param_error(fp, name, param[i].name,
241                                    "error: number of values should be zero for boolean parameters");
242                 bOk = false;
243             }
244             /* The boolean parameters should always be optional, so set the
245              * flag for convenience. */
246             param[i].flags |= SPAR_OPTIONAL;
247             /* Any other flags should not be specified */
248             if (param[i].flags & ~SPAR_OPTIONAL)
249             {
250                 report_param_error(fp, name, param[i].name,
251                                    "error: boolean parameter should not have any flags set");
252                 bOk = false;
253             }
254         }
255         /* Check val.nr */
256         if (param[i].flags & (SPAR_VARNUM | SPAR_ATOMVAL))
257         {
258             if (param[i].val.nr != -1)
259             {
260                 report_param_error(
261                         fp, name, param[i].name,
262                         "warning: val.nr is not -1 although SPAR_VARNUM/SPAR_ATOMVAL is set");
263             }
264             param[i].val.nr = -1;
265         }
266         else if (param[i].val.type != NO_VALUE)
267         {
268             if (param[i].val.nr <= 0)
269             {
270                 report_param_error(fp, name, param[i].name, "error: val.nr <= 0");
271                 bOk = false;
272             }
273         }
274         /* Check that the value pointer is NULL */
275         if (param[i].nvalptr != nullptr)
276         {
277             report_param_error(fp, name, param[i].name, "warning: nvalptr is set");
278         }
279         if (param[i].val.u.ptr != nullptr && !(param[i].flags & SPAR_ENUMVAL))
280         {
281             report_param_error(fp, name, param[i].name, "warning: value pointer is set");
282         }
283         /* Check that the name contains only valid characters */
284         if (param[i].name == nullptr)
285         {
286             continue;
287         }
288         if (!isalpha(param[i].name[0]))
289         {
290             report_param_error(fp, name, param[i].name, "error: name does not begin with a letter");
291             bOk = false;
292             continue;
293         }
294         for (j = 1; param[i].name[j] != 0; ++j)
295         {
296             if (param[i].name[j] != '_' && !isalnum(param[i].name[j]))
297             {
298                 report_param_error(fp, name, param[i].name,
299                                    "error: name contains non-alphanumeric characters");
300                 bOk = false;
301                 break;
302             }
303         }
304         if (param[i].name[j] != 0)
305         {
306             continue;
307         }
308         /* Check that the name does not conflict with a method */
309         if (symtab.findSymbol(param[i].name) != nullptr)
310         {
311             report_param_error(fp, name, param[i].name,
312                                "error: name conflicts with another method or a keyword");
313             bOk = false;
314         }
315     } /* End of parameter loop */
316       /* Check parameters of existing methods */
317     gmx::SelectionParserSymbolIterator symbol =
318             symtab.beginIterator(gmx::SelectionParserSymbol::MethodSymbol);
319     while (symbol != symtab.endIterator())
320     {
321         gmx_ana_selmethod_t* method = symbol->methodValue();
322         gmx_ana_selparam_t*  param  = gmx_ana_selmethod_find_param(name, method);
323         if (param)
324         {
325             report_param_error(fp, method->name, param->name,
326                                "error: name conflicts with another method or a keyword");
327             bOk = false;
328         }
329         ++symbol;
330     }
331     return bOk;
332 }
333
334 /*! \brief
335  * Checks the validity of selection method callback functions.
336  *
337  * \param[in] fp        File handle to use for diagnostic messages
338  *   (can be NULL).
339  * \param[in] method    The method to check.
340  * \returns   true if there are no problems, false otherwise.
341  *
342  * This function performs some checks common to both check_method() and
343  * check_modifier().
344  * This function checks that all the required callbacks are defined, i.e.,
345  * not NULL, to find programming errors.
346  */
347 static bool check_callbacks(FILE* fp, gmx_ana_selmethod_t* method)
348 {
349     bool bOk = true;
350     bool bNeedInit;
351     int  i;
352
353     /* Make some checks on init_data and free */
354     if (method->nparams > 0 && !method->init_data)
355     {
356         report_error(fp, method->name,
357                      "error: init_data should be provided because the method has parameters");
358         bOk = false;
359     }
360     if (method->free && !method->init_data)
361     {
362         report_error(fp, method->name, "warning: free is not used because of missing init_data");
363     }
364     /* Check presence of outinit for position-valued methods */
365     if (method->type == POS_VALUE && !method->outinit)
366     {
367         report_error(fp, method->name,
368                      "error: outinit should be provided because the method has POS_VALUE");
369         bOk = false;
370     }
371     /* Check presence of outinit for variable output count methods */
372     if ((method->flags & SMETH_VARNUMVAL) && !method->outinit)
373     {
374         report_error(fp, method->name,
375                      "error: outinit should be provided because the method has SMETH_VARNUMVAL");
376         bOk = false;
377     }
378     /* Warn of dynamic callbacks in static methods */
379     if (!(method->flags & SMETH_MODIFIER))
380     {
381         if (method->pupdate && !(method->flags & SMETH_DYNAMIC))
382         {
383             report_error(fp, method->name, "warning: pupdate not used because the method is static");
384             method->pupdate = nullptr;
385         }
386     }
387     /* Check that there is an evaluation function */
388     if (method->type != NO_VALUE && !method->update && !method->pupdate)
389     {
390         report_error(fp, method->name, "error: evaluation function missing");
391         bOk = false;
392     }
393     /* Loop through the parameters to determine if initialization callbacks
394      * are needed. */
395     bNeedInit = false;
396     for (i = 0; i < method->nparams; ++i)
397     {
398         if (method->param[i].val.type != POS_VALUE
399             && (method->param[i].flags & (SPAR_VARNUM | SPAR_ATOMVAL)))
400         {
401             bNeedInit = true;
402         }
403     }
404     /* Check that the callbacks required by the parameters are present */
405     if (bNeedInit && !method->init)
406     {
407         report_error(fp, method->name, "error: init should be provided");
408         bOk = false;
409     }
410     return bOk;
411 }
412
413 /*! \brief
414  * Checks the validity of a selection method.
415  *
416  * \param[in]     fp     File handle to use for diagnostic messages
417  *   (can be NULL).
418  * \param[in,out] method Method to check.
419  * \param[in]     symtab Symbol table (used for checking overlaps).
420  *
421  * Checks the validity of the given selection method data structure
422  * that does not have \ref SMETH_MODIFIER set.
423  * If you remove a check, please make sure that the selection parser,
424  * compiler, and evaluation functions can deal with the method.
425  */
426 static bool check_method(FILE* fp, gmx_ana_selmethod_t* method, const gmx::SelectionParserSymbolTable& symtab)
427 {
428     bool bOk = true;
429
430     /* Check the type */
431     if (method->type == NO_VALUE)
432     {
433         report_error(fp, method->name, "error: no value type specified");
434         bOk = false;
435     }
436     if (method->type == STR_VALUE && method->nparams > 0)
437     {
438         report_error(fp, method->name, "error: evaluates to a string but is not a keyword");
439         bOk = false;
440     }
441     /* Check flags */
442     if (method->type == GROUP_VALUE)
443     {
444         /* Group methods should always have SMETH_SINGLEVAL,
445          * so set it for convenience. */
446         method->flags |= SMETH_SINGLEVAL;
447         /* Check that conflicting flags are not present. */
448         if (method->flags & SMETH_VARNUMVAL)
449         {
450             report_error(fp, method->name,
451                          "error: SMETH_VARNUMVAL cannot be set for group-valued methods");
452             bOk = false;
453         }
454     }
455     else
456     {
457         if ((method->flags & SMETH_SINGLEVAL) && (method->flags & SMETH_VARNUMVAL))
458         {
459             report_error(fp, method->name, "error: SMETH_SINGLEVAL and SMETH_VARNUMVAL both set");
460             bOk = false;
461         }
462     }
463     if ((method->flags & SMETH_CHARVAL) && method->type != STR_VALUE)
464     {
465         report_error(fp, method->name,
466                      "error: SMETH_CHARVAL can only be specified for STR_VALUE methods");
467         bOk = false;
468     }
469     /* Check the parameters */
470     if (!check_params(fp, method->name, method->nparams, method->param, symtab))
471     {
472         bOk = false;
473     }
474     /* Check the callback pointers */
475     if (!check_callbacks(fp, method))
476     {
477         bOk = false;
478     }
479
480     return bOk;
481 }
482
483 /*! \brief
484  * Checks the validity of a selection modifier method.
485  *
486  * \param[in]     fp     File handle to use for diagnostic messages
487  *   (can be NULL).
488  * \param[in,out] method Method to check.
489  * \param[in]     symtab Symbol table (used for checking overlaps).
490  *
491  * Checks the validity of the given selection method data structure
492  * that has \ref SMETH_MODIFIER set.
493  * If you remove a check, please make sure that the selection parser,
494  * compiler, and evaluation functions can deal with the method.
495  */
496 static bool check_modifier(FILE* fp, gmx_ana_selmethod_t* method, const gmx::SelectionParserSymbolTable& symtab)
497 {
498     bool bOk = true;
499
500     /* Check the type */
501     if (method->type != NO_VALUE && method->type != POS_VALUE)
502     {
503         report_error(fp, method->name, "error: modifier should have type POS_VALUE or NO_VALUE");
504         bOk = false;
505     }
506     /* Check flags */
507     if (method->flags & (SMETH_SINGLEVAL | SMETH_VARNUMVAL))
508     {
509         report_error(fp, method->name,
510                      "error: modifier should not have SMETH_SINGLEVAL or SMETH_VARNUMVAL set");
511         bOk = false;
512     }
513     /* Check the parameters */
514     /* The first parameter is skipped */
515     if (!check_params(fp, method->name, method->nparams - 1, method->param + 1, symtab))
516     {
517         bOk = false;
518     }
519     /* Check the callback pointers */
520     if (!check_callbacks(fp, method))
521     {
522         bOk = false;
523     }
524     if (method->update)
525     {
526         report_error(fp, method->name, "error: modifier should not have update");
527         bOk = false;
528     }
529     if (method->type == POS_VALUE && !method->pupdate)
530     {
531         report_error(fp, method->name, "error: evaluation function missing");
532         bOk = false;
533     }
534
535     return bOk;
536 }
537
538 /*!
539  * \param[in,out] symtab Symbol table to register the method to.
540  * \param[in]     name   Name under which the method should be registered.
541  * \param[in]     method Method to register.
542  * \returns       0 on success, -1 if there was something wrong with the
543  *   method.
544  *
545  * \p name does not need to match the name of the method, and the same
546  * method can be registered multiple times under different names.
547  * If \p name equals some previously registered name,
548  * an error message is printed and the method is not registered.
549  *
550  * The function also performs some sanity checking on the input method,
551  * and refuses to register it if there are problems.
552  * Some problems only generate warnings.
553  * All problems are described to \p stderr.
554  */
555 int gmx_ana_selmethod_register(gmx::SelectionParserSymbolTable* symtab,
556                                const char*                      name,
557                                gmx_ana_selmethod_t*             method)
558 {
559     bool bOk;
560
561     /* Check the method */
562     if (method->flags & SMETH_MODIFIER)
563     {
564         bOk = check_modifier(stderr, method, *symtab);
565     }
566     else
567     {
568         bOk = check_method(stderr, method, *symtab);
569     }
570     /* Try to register the method if everything is ok */
571     if (bOk)
572     {
573         try
574         {
575             symtab->addMethod(name, method);
576         }
577         catch (const gmx::APIError& ex)
578         {
579             report_error(stderr, name, "%s", ex.what());
580             bOk = false;
581         }
582     }
583     if (!bOk)
584     {
585         report_error(stderr, name, "warning: not registered");
586         return -1;
587     }
588     return 0;
589 }
590
591 /*!
592  * \param[in,out] symtab Symbol table to register the methods to.
593  * \returns       0 on success, -1 if any of the default methods could not be
594  *   registered.
595  */
596 int gmx_ana_selmethod_register_defaults(gmx::SelectionParserSymbolTable* symtab)
597 {
598     /* Array of selection methods defined in the library. */
599     const t_register_method smtable_def[] = {
600         { nullptr, &sm_cog },         { nullptr, &sm_com },
601
602         { nullptr, &sm_all },         { nullptr, &sm_none },
603         { nullptr, &sm_atomnr },      { nullptr, &sm_resnr },
604         { "resid", &sm_resnr },       { nullptr, &sm_resindex },
605         { "residue", &sm_resindex },  { nullptr, &sm_molindex },
606         { "mol", &sm_molindex },      { "molecule", &sm_molindex },
607         { nullptr, &sm_atomname },    { "name", &sm_atomname },
608         { nullptr, &sm_pdbatomname }, { "pdbname", &sm_pdbatomname },
609         { nullptr, &sm_atomtype },    { "type", &sm_atomtype },
610         { nullptr, &sm_resname },     { nullptr, &sm_insertcode },
611         { nullptr, &sm_chain },       { nullptr, &sm_mass },
612         { nullptr, &sm_charge },      { nullptr, &sm_altloc },
613         { nullptr, &sm_occupancy },   { nullptr, &sm_betafactor },
614         { "beta", &sm_betafactor },   { nullptr, &sm_x },
615         { nullptr, &sm_y },           { nullptr, &sm_z },
616
617         { nullptr, &sm_distance },    { "dist", &sm_distance },
618         { nullptr, &sm_mindistance }, { "mindist", &sm_mindistance },
619         { nullptr, &sm_within },      { nullptr, &sm_insolidangle },
620         { nullptr, &sm_same },
621
622         { nullptr, &sm_merge },       { nullptr, &sm_plus },
623         { nullptr, &sm_permute },
624     };
625
626     int  rc;
627     bool bOk;
628
629     bOk = true;
630     for (int i = 0; i < asize(smtable_def); ++i)
631     {
632         gmx_ana_selmethod_t* method = smtable_def[i].method;
633
634         if (smtable_def[i].name == nullptr)
635         {
636             rc = gmx_ana_selmethod_register(symtab, method->name, method);
637         }
638         else
639         {
640             rc = gmx_ana_selmethod_register(symtab, smtable_def[i].name, method);
641         }
642         if (rc != 0)
643         {
644             bOk = false;
645         }
646     }
647     return bOk ? 0 : -1;
648 }
649
650 /*!
651  * \param[in] name   Name of the parameter to search.
652  * \param[in] method Method to search for the parameter.
653  * \returns   Pointer to the parameter in the
654  *   \ref gmx_ana_selmethod_t::param "method->param" array,
655  *   or NULL if no parameter with name \p name was found.
656  *
657  * This is a simple wrapper for gmx_ana_selparam_find().
658  */
659 gmx_ana_selparam_t* gmx_ana_selmethod_find_param(const char* name, gmx_ana_selmethod_t* method)
660 {
661     return gmx_ana_selparam_find(name, method->nparams, method->param);
662 }