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