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