3 * This source code is part of
7 * GROningen MAchine for Chemical Simulations
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.
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.
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.
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.
29 * For more info, check our website at http://www.gromacs.org
32 * \brief Selection compilation and optimization.
35 * Better error handling and memory management in error situations.
36 * At least, the main compilation function leaves the selection collection in
37 * a bad state if an error occurs.
40 * The memory usage could still be optimized.
41 * Use of memory pooling could still be extended, and a lot of redundant
42 * gmin/gmax data could be eliminated for complex arithmetic expressions.
44 * \author Teemu Murtola <teemu.murtola@cbr.su.se>
45 * \ingroup module_selection
48 * \page page_module_selection_compiler Selection compilation
50 * The compiler takes the selection element tree from the selection parser
51 * (see \ref page_module_selection_parser) as input.
52 * The selection parser is quite independent of selection evaluation details,
53 * and the compiler processes the tree to conform to what the evaluation
55 * For better control and optimization possibilities, the compilation is
56 * done on all selections simultaneously.
57 * Hence, all the selections should be parsed before the compiler can be
60 * The compiler initializes all fields in gmx::SelectionTreeElement not
61 * initialized by the parser: gmx::SelectionTreeElement::v (some fields have
62 * already been initialized by the parser),
63 * gmx::SelectionTreeElement::evaluate, and gmx::SelectionTreeElement::u
64 * (again, some elements have been initialized in the parser).
65 * The gmx::SelectionTreeElement::cdata field is used during the compilation to store
66 * internal data, but the data is freed when the compiler returns.
68 * In addition to initializing the elements, the compiler reorganizes the tree
69 * to simplify and optimize evaluation. The compiler also evaluates the static
70 * parts of the selection: in the end of the compilation, static parts have
71 * been replaced by the result of the evaluation.
73 * The compiler is invoked using gmx::SelectionCompiler.
74 * The gmx::SelectionCompiler::compile() method does the compilation in several
75 * passes over the gmx::SelectionTreeElement tree.
76 * -# Defaults are set for the position type and flags of position calculation
77 * methods that were not explicitly specified in the user input.
78 * -# Subexpressions are extracted: a separate root is created for each
79 * subexpression, and placed before the expression is first used.
80 * Currently, only variables and expressions used to evaluate parameter
81 * values are extracted, but common subexpression could also be detected
83 * -# A second pass (in fact, multiple passes because of interdependencies)
84 * with simple reordering and initialization is done:
85 * -# Boolean expressions are combined such that one element can evaluate,
86 * e.g., "A and B and C". The subexpressions in boolean expression are
87 * reordered such that static expressions come first without otherwise
88 * altering the relative order of the expressions.
89 * -# The compiler data structure is allocated for each element, and
90 * the fields are initialized, with the exception of the contents of
91 * \c gmax and \c gmin fields. This is the part that needs multiple
92 * passes, because some flags are set recursively based on which elements
93 * refer to an element, and these flags need to be set to initialize
95 * -# The gmx::SelectionTreeElement::evaluate field is set to the correct
96 * evaluation function from evaluate.h.
98 * -# The evaluation function of all elements is replaced with the
99 * analyze_static() function to be able to initialize the element before
100 * the actual evaluation function is called.
101 * The evaluation machinery is then called to initialize the whole tree,
102 * while simultaneously evaluating the static expressions.
103 * During the evaluation, track is kept of the smallest and largest
104 * possible selections, and these are stored in the internal compiler
105 * data structure for each element.
106 * To be able to do this for all possible values of dynamical expressions,
107 * special care needs to be taken with boolean expressions because they
108 * are short-circuiting. This is done through the
109 * \c SEL_CDATA_EVALMAX flag, which makes dynamic child expressions
110 * of \c BOOL_OR expressions evaluate to empty groups, while subexpressions
111 * of \c BOOL_AND are evaluated to largest possible groups.
112 * Memory is also allocated to store the results of the evaluation.
113 * For each element, analyze_static() calls the actual evaluation function
114 * after the element has been properly initialized.
115 * -# Another evaluation pass is done over subexpressions with more than
116 * one reference to them. These cannot be completely processed during the
117 * first pass, because it is not known whether later references require
118 * additional evaluation of static expressions.
119 * -# Unused subexpressions are removed. For efficiency reasons (and to avoid
120 * some checks), this is actually done several times already earlier in
121 * the compilation process.
122 * -# Most of the processing is now done, and the next pass simply sets the
123 * evaluation group of root elements to the largest selection as determined
124 * in pass 4. For root elements of subexpressions that should not be
125 * evaluated before they are referred to, the evaluation group/function is
126 * cleared. At the same time, position calculation data is initialized for
127 * for selection method elements that require it. Compiler data is also
128 * freed as it is no longer needed.
129 * -# A final pass initializes the total masses and charges in the
130 * \c gmx_ana_selection_t data structures.
132 * The actual evaluation of the selection is described in the documentation
133 * of the functions in evaluate.h.
136 * Some combinations of method parameter flags are not yet properly treated by
137 * the compiler or the evaluation functions in evaluate.cpp. All the ones used by
138 * currently implemented methods should work, but new combinations might not.
141 * \section selcompiler_tree Element tree after compilation
143 * After the compilation, the selection element tree is suitable for
144 * gmx_ana_selcollection_evaluate().
145 * Enough memory has been allocated for gmx::SelectionTreeElement::v
146 * (and gmx::SelectionTreeElement::cgrp for \ref SEL_SUBEXPR elements) to allow
147 * the selection to be evaluated without allocating any memory.
150 * \subsection selcompiler_tree_root Root elements
152 * The top level of the tree consists of a chain of \ref SEL_ROOT elements.
153 * These are used for two purposes:
154 * -# A selection that should be evaluated.
155 * These elements appear in the same order as the selections in the input.
156 * For these elements, gmx::SelectionTreeElement::v has been set to the
157 * maximum possible group that the selection can evaluate to (only for
158 * dynamic selections), and gmx::SelectionTreeElement::cgrp has been set to
159 * use a NULL group for evaluation.
160 * -# A subexpression that appears in one or more selections.
161 * Each selection that gives a value for a method parameter is a
162 * potential subexpression, as is any variable value.
163 * Only subexpressions that require evaluation for each frame are left
164 * after the selection is compiled.
165 * Each subexpression appears in the chain before any references to it.
166 * For these elements, gmx::SelectionTreeElement::cgrp has been set to the
167 * group that should be used to evaluate the subexpression.
168 * If gmx::SelectionTreeElement::cgrp is empty, the total evaluation group
169 * is not known in advance or it is more efficient to evaluate the
170 * subexpression only when it is referenced. If this is the case,
171 * gmx::SelectionTreeElement::evaluate is also NULL.
173 * The children of the \ref SEL_ROOT elements can be used to distinguish
174 * the two types of root elements from each other; the rules are the same
175 * as for the parsed tree (see \ref selparser_tree_root).
176 * Subexpressions are treated as if they had been provided through variables.
178 * Selection names are stored as after parsing (see \ref selparser_tree_root).
181 * \subsection selcompiler_tree_const Constant elements
183 * All (sub)selections that do not require particle positions have been
184 * replaced with \ref SEL_CONST elements.
185 * Constant elements from the parser are also retained if present in
186 * dynamic parts of the selections.
187 * Several constant elements with a NULL gmx::SelectionTreeElement::evaluate
188 * are left for debugging purposes; of these, only the ones for \ref BOOL_OR
189 * expressions are used during evaluation.
191 * The value is stored in gmx::SelectionTreeElement::v, and for group values
192 * with an evaluation function set, also in gmx::SelectionTreeElement::cgrp.
193 * For \ref GROUP_VALUE elements, unnecessary atoms (i.e., atoms that
194 * could never be selected) have been removed from the value.
196 * \ref SEL_CONST elements have no children.
199 * \subsection selcompiler_tree_method Method evaluation elements
201 * All selection methods that need to be evaluated dynamically are described
202 * by a \ref SEL_EXPRESSION element. The gmx::SelectionTreeElement::method and
203 * gmx::SelectionTreeElement::mdata fields have already been initialized by the parser,
204 * and the compiler only calls the initialization functions in the method
205 * data structure to do some additional initialization of these fields at
206 * appropriate points. If the gmx::SelectionTreeElement::pc data field has been
207 * created by the parser, the compiler initializes the data structure properly
208 * once the required positions are known. If the gmx::SelectionTreeElement::pc
209 * field is NULL after the parser, but the method provides only
210 * sel_updatefunc_pos(), an appropriate position calculation data structure is
211 * created. If gmx::SelectionTreeElement::pc is not NULL,
212 * gmx::SelectionTreeElement::pos is also initialized to hold the positions
215 * Children of these elements are of type \ref SEL_SUBEXPRREF, and describe
216 * parameter values that need to be evaluated for each frame. See the next
217 * section for more details.
218 * \ref SEL_CONST children can also appear, and stand for parameters that get
219 * their value from a static expression. These elements are present only for
220 * debugging purposes: they always have a NULL evaluation function.
223 * \subsection selcompiler_tree_subexpr Subexpression elements
225 * As described in \ref selcompiler_tree_root, subexpressions are created
226 * for each variable and each expression that gives a value to a selection
227 * method parameter. As the only child of the \ref SEL_ROOT element,
228 * these elements have a \ref SEL_SUBEXPR element. The \ref SEL_SUBEXPR
229 * element has a single child, which evaluates the actual expression.
230 * After compilation, only subexpressions that require particle positions
231 * for evaluation are left.
232 * For non-variable subexpression, automatic names have been generated to
235 * For \ref SEL_SUBEXPR elements, memory has been allocated for
236 * gmx::SelectionTreeElement::cgrp to store the group for which the expression
237 * has been evaluated during the current frame. This is only done if full
238 * subexpression evaluation by _gmx_sel_evaluate_subexpr() is needed; the other
239 * evaluation functions do not require this memory.
241 * \ref SEL_SUBEXPRREF elements are used to describe references to
242 * subexpressions. They have always a single child, which is the
243 * \ref SEL_SUBEXPR element being referenced.
245 * If a subexpression is used only once, the evaluation has been optimized by
246 * setting the child of the \ref SEL_SUBEXPR element to evaluate the value of
247 * \ref SEL_SUBEXPRREF directly (in the case of memory pooling, this is managed
248 * by the evaluation functions). In such cases, the evaluation routines for the
249 * \ref SEL_SUBEXPRREF and \ref SEL_SUBEXPR elements only propagate some status
250 * information, but do not unnecessarily copy the values.
253 * \subsection selcompiler_tree_bool Boolean elements
255 * \ref SEL_BOOLEAN elements have been merged such that one element
256 * may carry out evaluation of more than one operation of the same type.
257 * The static parts of the expressions have been evaluated, and are placed
258 * in the first child. These are followed by the dynamic expressions, in the
259 * order provided by the user.
262 * \subsection selcompiler_tree_arith Arithmetic elements
264 * Constant and static expressions in \ref SEL_ARITHMETIC elements have been
266 * Currently, no other processing is done.
268 #include "compiler.h"
283 #include "gromacs/selection/indexutil.h"
284 #include "gromacs/selection/poscalc.h"
285 #include "gromacs/selection/selection.h"
286 #include "gromacs/selection/selmethod.h"
287 #include "gromacs/utility/exceptions.h"
288 #include "gromacs/utility/stringutil.h"
290 #include "evaluate.h"
291 #include "keywords.h"
293 #include "selectioncollection-impl.h"
297 using gmx::SelectionTreeElement;
298 using gmx::SelectionTreeElementPointer;
306 * Whether a subexpression needs to evaluated for all atoms.
308 * This flag is set for \ref SEL_SUBEXPR elements that are used to
309 * evaluate non-atom-valued selection method parameters, as well as
310 * those that are used directly as values of selections.
312 SEL_CDATA_FULLEVAL = 1,
314 * Whether the whole subexpression should be treated as static.
316 * This flag is always false if \ref SEL_DYNAMIC is set for the element,
317 * but it is also false for static elements within common subexpressions.
319 SEL_CDATA_STATIC = 2,
320 /** Whether the subexpression will always be evaluated in the same group. */
321 SEL_CDATA_STATICEVAL = 4,
322 /** Whether the compiler evaluation routine should return the maximal selection. */
323 SEL_CDATA_EVALMAX = 8,
324 /** Whether memory has been allocated for \p gmin and \p gmax. */
325 SEL_CDATA_MINMAXALLOC = 16,
326 /** Whether to update \p gmin and \p gmax in static analysis. */
327 SEL_CDATA_DOMINMAX = 128,
328 /** Whether the subexpression uses simple pass evaluation functions. */
329 SEL_CDATA_SIMPLESUBEXPR = 32,
330 /** Whether this expression is a part of a common subexpression. */
331 SEL_CDATA_COMMONSUBEXPR = 64
335 * Internal data structure used by the compiler.
337 typedef struct t_compiler_data
339 /** The real evaluation method. */
340 gmx::sel_evalfunc evaluate;
341 /** Number of references to a \ref SEL_SUBEXPR element. */
343 /** Flags for specifying how to treat this element during compilation. */
345 /** Smallest selection that can be selected by the subexpression. */
346 gmx_ana_index_t *gmin;
347 /** Largest selection that can be selected by the subexpression. */
348 gmx_ana_index_t *gmax;
352 /********************************************************************
353 * COMPILER UTILITY FUNCTIONS
354 ********************************************************************/
357 * Helper method for printing out debug information about a min/max group.
360 print_group_info(FILE *fp, const char *name,
361 const SelectionTreeElement &sel,
364 fprintf(fp, " %s=", name);
367 fprintf(fp, "(null)");
369 else if (sel.cdata->flags & SEL_CDATA_MINMAXALLOC)
371 fprintf(fp, "(%d atoms, %p)", g->isize, (void*)g);
373 else if (sel.v.type == GROUP_VALUE && g == sel.v.u.g)
375 fprintf(fp, "(static, %p)", (void*)g);
379 fprintf(fp, "%p", (void*)g);
384 * \param[in] fp File handle to receive the output.
385 * \param[in] sel Selection element to print.
386 * \param[in] level Indentation level, starting from zero.
389 _gmx_selelem_print_compiler_info(FILE *fp, const SelectionTreeElement &sel,
396 fprintf(fp, "%*c cdata: flg=", level*2+1, ' ');
397 if (sel.cdata->flags & SEL_CDATA_FULLEVAL)
401 if (!(sel.cdata->flags & SEL_CDATA_STATIC))
405 if (sel.cdata->flags & SEL_CDATA_STATICEVAL)
409 if (sel.cdata->flags & SEL_CDATA_EVALMAX)
413 if (sel.cdata->flags & SEL_CDATA_MINMAXALLOC)
417 if (sel.cdata->flags & SEL_CDATA_SIMPLESUBEXPR)
421 if (sel.cdata->flags & SEL_CDATA_COMMONSUBEXPR)
425 if (!sel.cdata->flags)
429 if (sel.cdata->refcount > 0)
431 fprintf(fp, " refc=%d", sel.cdata->refcount);
433 fprintf(fp, " eval=");
434 _gmx_sel_print_evalfunc_name(fp, sel.cdata->evaluate);
435 print_group_info(fp, "gmin", sel, sel.cdata->gmin);
436 print_group_info(fp, "gmax", sel, sel.cdata->gmax);
443 void SelectionTreeElement::freeCompilerData()
447 evaluate = cdata->evaluate;
448 if (cdata->flags & SEL_CDATA_MINMAXALLOC)
450 cdata->gmin->name = NULL;
451 cdata->gmax->name = NULL;
452 gmx_ana_index_deinit(cdata->gmin);
453 gmx_ana_index_deinit(cdata->gmax);
465 * Allocates memory for storing the evaluated value of a selection element.
467 * \param sel Selection element to initialize
468 * \param[in] isize Maximum evaluation group size.
469 * \param[in] bChildEval true if children have already been processed.
471 * If called more than once, memory is (re)allocated to ensure that the
472 * maximum of the \p isize values can be stored.
475 alloc_selection_data(const SelectionTreeElementPointer &sel,
476 int isize, bool bChildEval)
484 /* Find out the number of elements to allocate */
485 if (sel->flags & SEL_SINGLEVAL)
489 else if (sel->flags & SEL_ATOMVAL)
493 else /* sel->flags should contain SEL_VARNUMVAL */
499 SelectionTreeElementPointer child = sel;
500 if (sel->type == SEL_SUBEXPRREF)
502 GMX_RELEASE_ASSERT(sel->child && sel->child->type == SEL_SUBEXPR,
503 "Subexpression expected for subexpression reference");
504 child = sel->child->child;
505 GMX_RELEASE_ASSERT(child,
506 "Subexpression elements should always have a child element");
508 nalloc = (sel->v.type == POS_VALUE) ? child->v.u.p->nr : child->v.nr;
510 /* For positions, we actually want to allocate just a single structure
511 * for nalloc positions. */
512 if (sel->v.type == POS_VALUE)
517 /* Allocate memory for sel->v.u if needed */
518 if (sel->flags & SEL_ALLOCVAL)
520 _gmx_selvalue_reserve(&sel->v, nalloc);
522 /* Reserve memory inside group and position structures if
523 * SEL_ALLOCDATA is set. */
524 if (sel->flags & SEL_ALLOCDATA)
526 if (sel->v.type == GROUP_VALUE)
528 gmx_ana_index_reserve(sel->v.u.g, isize);
530 else if (sel->v.type == POS_VALUE)
532 gmx_ana_pos_reserve(sel->v.u.p, isize, 0);
538 * Replace the evaluation function of each element in the subtree.
540 * \param sel Root of the selection subtree to process.
541 * \param[in] eval The new evaluation function.
544 set_evaluation_function(const SelectionTreeElementPointer &sel,
545 gmx::sel_evalfunc eval)
547 sel->evaluate = eval;
548 if (sel->type != SEL_SUBEXPRREF)
550 SelectionTreeElementPointer child = sel->child;
553 set_evaluation_function(child, eval);
560 /********************************************************************
561 * POSITION KEYWORD DEFAULT INITIALIZATION
562 ********************************************************************/
565 * Initializes default values for position keyword evaluation.
567 * \param[in,out] root Root of the element tree to initialize.
568 * \param[in] spost Default output position type.
569 * \param[in] rpost Default reference position type.
570 * \param[in] sel Selection that the element evaluates the positions
571 * for, or NULL if the element is an internal element.
574 init_pos_keyword_defaults(SelectionTreeElement *root,
575 const char *spost, const char *rpost,
576 const gmx::internal::SelectionData *sel)
578 /* Selections use largest static group by default, while
579 * reference positions use the whole residue/molecule. */
580 if (root->type == SEL_EXPRESSION)
582 bool bSelection = (sel != NULL);
583 int flags = bSelection ? POS_COMPLMAX : POS_COMPLWHOLE;
586 if (sel->hasFlag(gmx::efSelection_DynamicMask))
588 flags |= POS_MASKONLY;
590 if (sel->hasFlag(gmx::efSelection_EvaluateVelocities))
592 flags |= POS_VELOCITIES;
594 if (sel->hasFlag(gmx::efSelection_EvaluateForces))
599 _gmx_selelem_set_kwpos_type(root, bSelection ? spost : rpost);
600 _gmx_selelem_set_kwpos_flags(root, flags);
602 /* Change the defaults once we are no longer processing modifiers */
603 if (root->type != SEL_ROOT && root->type != SEL_MODIFIER
604 && root->type != SEL_SUBEXPRREF && root->type != SEL_SUBEXPR)
608 /* Recurse into children */
609 SelectionTreeElementPointer child = root->child;
612 init_pos_keyword_defaults(child.get(), spost, rpost, sel);
618 /********************************************************************
619 * SUBEXPRESSION PROCESSING
620 ********************************************************************/
623 * Reverses the chain of selection elements starting at \p root.
625 * \param root First selection in the whole selection chain.
626 * \returns The new first element for the chain.
628 static SelectionTreeElementPointer
629 reverse_selelem_chain(const SelectionTreeElementPointer &root)
631 SelectionTreeElementPointer prev;
632 SelectionTreeElementPointer item = root;
635 SelectionTreeElementPointer next = item->next;
644 * Removes subexpressions that don't have any references.
646 * \param root First selection in the whole selection chain.
647 * \returns The new first element for the chain.
649 * The elements are processed in reverse order to correctly detect
650 * subexpressions only referred to by other subexpressions.
652 static SelectionTreeElementPointer
653 remove_unused_subexpressions(SelectionTreeElementPointer root)
657 return SelectionTreeElementPointer();
659 root = reverse_selelem_chain(root);
660 while (root->child->type == SEL_SUBEXPR && root->child.unique())
662 // Frees the root element.
665 SelectionTreeElementPointer prev = root;
666 SelectionTreeElementPointer item = root->next;
669 SelectionTreeElementPointer next = item->next;
670 if (item->child->type == SEL_SUBEXPR && item->child.unique())
672 // Frees the current item when it goes out of scope.
681 return reverse_selelem_chain(root);
685 * Creates a name with a running number for a subexpression.
687 * \param[in,out] sel The subexpression to be named.
688 * \param[in] i Running number for the subexpression.
690 * The name of the selection becomes "SubExpr N", where N is \p i;
691 * Memory is allocated for the name and the name is stored both as the
692 * name of the subexpression element and as
693 * gmx::SelectionTreeElement::u::cgrp::name; the latter is freed by
694 * _gmx_selelem_free().
697 create_subexpression_name(const SelectionTreeElementPointer &sel, int i)
699 std::string name(gmx::formatString("SubExpr %d", i));
701 sel->u.cgrp.name = strdup(name.c_str());
705 * Processes and extracts subexpressions from a given selection subtree.
707 * \param sel Root of the subtree to process.
708 * \param subexprn Pointer to a subexpression counter.
709 * \returns Pointer to a chain of subselections, or NULL if none were found.
711 * This function finds recursively all \ref SEL_SUBEXPRREF elements below
712 * the given root element and ensures that their children are within
713 * \ref SEL_SUBEXPR elements. It also creates a chain of \ref SEL_ROOT elements
714 * that contain the subexpression as their children and returns the first
715 * of these root elements.
717 static SelectionTreeElementPointer
718 extract_item_subselections(const SelectionTreeElementPointer &sel,
721 SelectionTreeElementPointer root;
722 SelectionTreeElementPointer subexpr;
723 SelectionTreeElementPointer child = sel->child;
729 root = subexpr = extract_item_subselections(child, subexprn);
733 subexpr->next = extract_item_subselections(child, subexprn);
735 while (subexpr && subexpr->next)
737 subexpr = subexpr->next;
739 /* The latter check excludes variable references. */
740 if (child->type == SEL_SUBEXPRREF && child->child->type != SEL_SUBEXPR)
742 /* Create the root element for the subexpression */
745 root.reset(new SelectionTreeElement(SEL_ROOT));
750 subexpr->next.reset(new SelectionTreeElement(SEL_ROOT));
751 subexpr = subexpr->next;
753 /* Create the subexpression element and
754 * move the actual subexpression under the created element. */
755 subexpr->child.reset(new SelectionTreeElement(SEL_SUBEXPR));
756 _gmx_selelem_set_vtype(subexpr->child, child->v.type);
757 subexpr->child->child = child->child;
758 child->child = subexpr->child;
759 create_subexpression_name(subexpr->child, ++*subexprn);
760 /* Set the flags for the created elements */
761 subexpr->flags |= (child->flags & SEL_VALFLAGMASK);
762 subexpr->child->flags |= (child->flags & SEL_VALFLAGMASK);
764 if (child->type == SEL_SUBEXPRREF)
766 child->setName(child->child->name());
775 * Extracts subexpressions of the selection chain.
777 * \param sel First selection in the whole selection chain.
778 * \returns The new first element for the chain.
780 * Finds all the subexpressions (and their subexpressions) in the
781 * selection chain starting from \p sel and creates \ref SEL_SUBEXPR
783 * \ref SEL_ROOT elements are also created for each subexpression
784 * and inserted into the selection chain before the expressions that
787 static SelectionTreeElementPointer
788 extract_subexpressions(SelectionTreeElementPointer sel)
790 SelectionTreeElementPointer root;
791 SelectionTreeElementPointer next = sel;
795 SelectionTreeElementPointer item
796 = extract_item_subselections(next, &subexprn);
824 /********************************************************************
825 * BOOLEAN OPERATION REORDERING
826 ********************************************************************/
829 * Removes redundant boolean selection elements.
831 * \param sel Root of the selection subtree to optimize.
833 * This function merges similar boolean operations (e.g., (A or B) or C becomes
834 * a single OR operation with three operands).
837 optimize_boolean_expressions(const SelectionTreeElementPointer &sel)
839 /* Do recursively for children */
840 if (sel->type != SEL_SUBEXPRREF)
842 SelectionTreeElementPointer prev;
843 SelectionTreeElementPointer child = sel->child;
846 optimize_boolean_expressions(child);
847 /* Remove double negations */
848 if (child->type == SEL_BOOLEAN && child->u.boolt == BOOL_NOT
849 && child->child->type == SEL_BOOLEAN && child->child->u.boolt == BOOL_NOT)
851 /* Move the doubly negated expression up two levels */
854 sel->child = child->child->child;
859 prev->next = child->child->child;
862 child->child->child->next = child->next;
863 // Discards the two negations.
870 if (sel->type != SEL_BOOLEAN || sel->u.boolt == BOOL_NOT)
874 /* Merge subsequent binary operations */
875 SelectionTreeElementPointer prev;
876 SelectionTreeElementPointer child = sel->child;
879 if (child->type == SEL_BOOLEAN && child->u.boolt == sel->u.boolt)
883 sel->child = child->child;
888 prev->next = child->child;
894 prev->next = child->next;
895 // Discards the old child.
907 * Reorders children of boolean expressions such that static selections
910 * \param sel Root of the selection subtree to reorder.
912 * The relative order of static expressions does not change.
913 * The same is true for the dynamic expressions.
916 reorder_boolean_static_children(const SelectionTreeElementPointer &sel)
918 /* Do recursively for children */
919 if (sel->type != SEL_SUBEXPRREF)
921 SelectionTreeElementPointer child = sel->child;
924 reorder_boolean_static_children(child);
929 /* Reorder boolean expressions such that static selections come first */
930 if (sel->type == SEL_BOOLEAN && (sel->flags & SEL_DYNAMIC))
932 // Add a dummy head element that precedes the first child.
933 SelectionTreeElementPointer dummy(
934 new SelectionTreeElement(SEL_BOOLEAN));
935 dummy->next = sel->child;
936 SelectionTreeElementPointer prev = dummy;
937 SelectionTreeElementPointer child = dummy;
940 /* child is the last handled static expression */
941 /* prev is the last handled non-static expression */
942 SelectionTreeElementPointer next = prev->next;
943 while (next && (next->flags & SEL_DYNAMIC))
948 /* next is now the first static expression after child */
953 /* Reorder such that next comes after child */
956 prev->next = next->next;
957 next->next = child->next;
964 /* Advance child by one */
968 sel->child = dummy->next;
973 /********************************************************************
974 * ARITHMETIC EXPRESSION PROCESSING
975 ********************************************************************/
978 * Processes arithmetic expressions to simplify and speed up evaluation.
980 * \param sel Root of the selection subtree to process.
982 * Currently, this function only converts integer constants to reals
983 * within arithmetic expressions.
986 optimize_arithmetic_expressions(const SelectionTreeElementPointer &sel)
988 /* Do recursively for children. */
989 if (sel->type != SEL_SUBEXPRREF)
991 SelectionTreeElementPointer child = sel->child;
994 optimize_arithmetic_expressions(child);
999 if (sel->type != SEL_ARITHMETIC)
1004 /* Convert integer constants to reals. */
1005 SelectionTreeElementPointer child = sel->child;
1008 if (child->v.type == INT_VALUE)
1012 if (child->type != SEL_CONST)
1014 GMX_THROW(gmx::InconsistentInputError("Non-constant integer expressions not implemented in arithmetic evaluation"));
1017 r[0] = child->v.u.i[0];
1018 sfree(child->v.u.i);
1020 child->v.type = REAL_VALUE;
1022 else if (child->v.type != REAL_VALUE)
1024 GMX_THROW(gmx::InternalError("Non-numerical value in arithmetic expression"));
1026 child = child->next;
1031 /********************************************************************
1032 * EVALUATION PREPARATION COMPILER
1033 ********************************************************************/
1036 * Sets the evaluation functions for the selection (sub)tree.
1038 * \param[in,out] sel Root of the selection subtree to process.
1040 * This function sets the evaluation function
1041 * (gmx::SelectionTreeElement::evaluate) for the selection elements.
1044 init_item_evalfunc(const SelectionTreeElementPointer &sel)
1046 /* Process children. */
1047 if (sel->type != SEL_SUBEXPRREF)
1049 SelectionTreeElementPointer child = sel->child;
1052 init_item_evalfunc(child);
1053 child = child->next;
1057 /* Set the evaluation function */
1061 if (sel->v.type == GROUP_VALUE)
1063 sel->evaluate = &_gmx_sel_evaluate_static;
1067 case SEL_EXPRESSION:
1068 if (!(sel->flags & SEL_DYNAMIC) && sel->u.expr.method
1069 && sel->u.expr.method->init_frame)
1071 sel->flags |= SEL_INITFRAME;
1073 sel->evaluate = &_gmx_sel_evaluate_method;
1076 case SEL_ARITHMETIC:
1077 sel->evaluate = &_gmx_sel_evaluate_arithmetic;
1081 if (sel->v.type != NO_VALUE)
1083 sel->evaluate = &_gmx_sel_evaluate_modifier;
1088 switch (sel->u.boolt)
1090 case BOOL_NOT: sel->evaluate = &_gmx_sel_evaluate_not; break;
1091 case BOOL_AND: sel->evaluate = &_gmx_sel_evaluate_and; break;
1092 case BOOL_OR: sel->evaluate = &_gmx_sel_evaluate_or; break;
1094 GMX_THROW(gmx::NotImplementedError("xor expressions not implemented"));
1099 sel->evaluate = &_gmx_sel_evaluate_root;
1103 sel->evaluate = ((sel->cdata->flags & SEL_CDATA_SIMPLESUBEXPR)
1104 ? &_gmx_sel_evaluate_subexpr_simple
1105 : &_gmx_sel_evaluate_subexpr);
1108 case SEL_SUBEXPRREF:
1109 sel->evaluate = ((sel->cdata->flags & SEL_CDATA_SIMPLESUBEXPR)
1110 ? &_gmx_sel_evaluate_subexprref_simple
1111 : &_gmx_sel_evaluate_subexprref);
1115 GMX_THROW(gmx::APIError("Unresolved group reference in compilation"));
1117 sel->cdata->evaluate = sel->evaluate;
1121 * Sets the memory pool for selection elements that can use it.
1123 * \param sel Root of the selection subtree to process.
1124 * \param[in] mempool Memory pool to use.
1127 setup_memory_pooling(const SelectionTreeElementPointer &sel,
1128 gmx_sel_mempool_t *mempool)
1130 if (sel->type != SEL_SUBEXPRREF)
1132 SelectionTreeElementPointer child = sel->child;
1135 if ((sel->type == SEL_BOOLEAN && (child->flags & SEL_DYNAMIC))
1136 || (sel->type == SEL_ARITHMETIC && child->type != SEL_CONST
1137 && !(child->flags & SEL_SINGLEVAL))
1138 || (sel->type == SEL_SUBEXPR
1139 && !(sel->cdata->flags & SEL_CDATA_SIMPLESUBEXPR)))
1141 child->mempool = mempool;
1142 if (child->type == SEL_SUBEXPRREF
1143 && (child->child->cdata->flags & SEL_CDATA_SIMPLESUBEXPR))
1145 child->child->child->mempool = mempool;
1148 setup_memory_pooling(child, mempool);
1149 child = child->next;
1155 * Prepares the selection (sub)tree for evaluation.
1157 * \param[in,out] sel Root of the selection subtree to prepare.
1159 * It also allocates memory for the \p sel->v.u.g or \p sel->v.u.p
1160 * structure if required.
1163 init_item_evaloutput(const SelectionTreeElementPointer &sel)
1165 GMX_ASSERT(!(sel->child == NULL &&
1166 (sel->type == SEL_SUBEXPRREF || sel->type == SEL_SUBEXPR)),
1167 "Subexpression elements should always have a child element");
1169 /* Process children. */
1170 if (sel->type != SEL_SUBEXPRREF)
1172 SelectionTreeElementPointer child = sel->child;
1175 init_item_evaloutput(child);
1176 child = child->next;
1180 if (sel->type == SEL_SUBEXPR
1181 && (sel->cdata->flags & SEL_CDATA_SIMPLESUBEXPR))
1183 sel->flags &= ~(SEL_ALLOCVAL | SEL_ALLOCDATA);
1184 if (sel->v.type == GROUP_VALUE || sel->v.type == POS_VALUE)
1186 _gmx_selvalue_setstore(&sel->v, sel->child->v.u.ptr);
1189 else if (sel->type == SEL_SUBEXPR
1190 && (sel->cdata->flags & SEL_CDATA_FULLEVAL))
1192 sel->evaluate = &_gmx_sel_evaluate_subexpr_staticeval;
1193 sel->cdata->evaluate = sel->evaluate;
1194 sel->child->mempool = NULL;
1195 sel->flags &= ~(SEL_ALLOCVAL | SEL_ALLOCDATA);
1196 if (sel->v.type == GROUP_VALUE || sel->v.type == POS_VALUE)
1198 _gmx_selvalue_setstore(&sel->v, sel->child->v.u.ptr);
1201 else if (sel->type == SEL_SUBEXPRREF
1202 && (sel->cdata->flags & SEL_CDATA_SIMPLESUBEXPR))
1206 _gmx_selvalue_setstore(&sel->child->v, sel->v.u.ptr);
1207 sel->child->child->freeValues();
1208 sel->child->child->flags &= ~(SEL_ALLOCVAL | SEL_ALLOCDATA);
1209 sel->child->child->flags |= (sel->flags & SEL_ALLOCDATA);
1210 _gmx_selvalue_setstore(&sel->child->child->v, sel->v.u.ptr);
1212 else if (sel->v.type == GROUP_VALUE || sel->v.type == POS_VALUE)
1214 _gmx_selvalue_setstore(&sel->v, sel->child->child->v.u.ptr);
1216 sel->flags &= ~(SEL_ALLOCVAL | SEL_ALLOCDATA);
1219 /* Make sure that the group/position structure is allocated. */
1220 if (!sel->v.u.ptr && (sel->flags & SEL_ALLOCVAL))
1222 if (sel->v.type == GROUP_VALUE || sel->v.type == POS_VALUE)
1224 _gmx_selvalue_reserve(&sel->v, 1);
1231 /********************************************************************
1232 * COMPILER DATA INITIALIZATION
1233 ********************************************************************/
1236 * Allocates memory for the compiler data and initializes the structure.
1238 * \param sel Root of the selection subtree to process.
1241 init_item_compilerdata(const SelectionTreeElementPointer &sel)
1243 /* Allocate the compiler data structure */
1244 snew(sel->cdata, 1);
1246 /* Store the real evaluation method because the compiler will replace it */
1247 sel->cdata->evaluate = sel->evaluate;
1249 /* This will be computed separately. */
1250 sel->cdata->refcount = 0;
1252 /* Initialize the flags */
1253 sel->cdata->flags = SEL_CDATA_STATICEVAL;
1254 if (!(sel->flags & SEL_DYNAMIC))
1256 sel->cdata->flags |= SEL_CDATA_STATIC;
1258 if (sel->type == SEL_SUBEXPR)
1260 sel->cdata->flags |= SEL_CDATA_EVALMAX;
1262 /* Set the full evaluation flag for subexpressions that require it;
1263 * the subexpression has already been initialized, so we can simply
1264 * access its compilation flags.*/
1265 if (sel->type == SEL_EXPRESSION || sel->type == SEL_MODIFIER)
1267 SelectionTreeElementPointer child = sel->child;
1270 if (!(child->flags & SEL_ATOMVAL) && child->child)
1272 child->child->cdata->flags |= SEL_CDATA_FULLEVAL;
1274 child = child->next;
1277 else if (sel->type == SEL_ROOT && sel->child->type == SEL_SUBEXPRREF)
1279 sel->child->child->cdata->flags |= SEL_CDATA_FULLEVAL;
1282 /* Initialize children */
1283 if (sel->type != SEL_SUBEXPRREF)
1285 SelectionTreeElementPointer child = sel->child;
1288 init_item_compilerdata(child);
1289 child = child->next;
1293 /* Determine whether we should evaluate the minimum or the maximum
1294 * for the children of this element. */
1295 if (sel->type == SEL_BOOLEAN)
1299 bEvalMax = (sel->u.boolt == BOOL_AND);
1300 SelectionTreeElementPointer child = sel->child;
1305 child->cdata->flags |= SEL_CDATA_EVALMAX;
1307 else if (child->type == SEL_BOOLEAN && child->u.boolt == BOOL_NOT)
1309 child->child->cdata->flags |= SEL_CDATA_EVALMAX;
1311 child = child->next;
1314 else if (sel->type == SEL_EXPRESSION || sel->type == SEL_MODIFIER
1315 || sel->type == SEL_SUBEXPR)
1317 SelectionTreeElementPointer child = sel->child;
1320 child->cdata->flags |= SEL_CDATA_EVALMAX;
1321 child = child->next;
1327 * Initializes the static evaluation flag for a selection subtree.
1329 * \param[in,out] sel Root of the selection subtree to process.
1331 * Sets the \c bStaticEval in the compiler data structure:
1332 * for any element for which the evaluation group may depend on the trajectory
1333 * frame, the flag is cleared.
1335 * reorder_boolean_static_children() should have been called.
1338 init_item_staticeval(const SelectionTreeElementPointer &sel)
1340 /* Subexpressions with full evaluation should always have bStaticEval,
1341 * so don't do anything if a reference to them is encountered. */
1342 if (sel->type == SEL_SUBEXPRREF
1343 && (sel->child->cdata->flags & SEL_CDATA_FULLEVAL))
1348 /* Propagate the bStaticEval flag to children if it is not set */
1349 if (!(sel->cdata->flags & SEL_CDATA_STATICEVAL))
1351 SelectionTreeElementPointer child = sel->child;
1354 if ((sel->type != SEL_EXPRESSION && sel->type != SEL_MODIFIER)
1355 || (child->flags & SEL_ATOMVAL))
1357 if (child->cdata->flags & SEL_CDATA_STATICEVAL)
1359 child->cdata->flags &= ~SEL_CDATA_STATICEVAL;
1360 init_item_staticeval(child);
1363 child = child->next;
1366 else /* bStaticEval is set */
1368 /* For boolean expressions, any expression after the first dynamic
1369 * expression should not have bStaticEval. */
1370 if (sel->type == SEL_BOOLEAN)
1372 SelectionTreeElementPointer child = sel->child;
1373 while (child && !(child->flags & SEL_DYNAMIC))
1375 child = child->next;
1379 child = child->next;
1383 child->cdata->flags &= ~SEL_CDATA_STATICEVAL;
1384 child = child->next;
1388 /* Process the children */
1389 SelectionTreeElementPointer child = sel->child;
1392 init_item_staticeval(child);
1393 child = child->next;
1399 * Compute reference counts for subexpressions.
1401 * \param sel Root of the selection subtree to process.
1404 init_item_subexpr_refcount(const SelectionTreeElementPointer &sel)
1406 // Reset the counter when the subexpression is first encountered.
1407 if (sel->type == SEL_ROOT && sel->child->type == SEL_SUBEXPR
1408 && sel->child->cdata)
1410 sel->child->cdata->refcount = 0;
1413 if (sel->type == SEL_SUBEXPRREF)
1415 ++sel->child->cdata->refcount;
1419 SelectionTreeElementPointer child = sel->child;
1422 init_item_subexpr_refcount(child);
1423 child = child->next;
1429 * Initializes compiler flags for subexpressions.
1431 * \param sel Root of the selection subtree to process.
1434 init_item_subexpr_flags(const SelectionTreeElementPointer &sel)
1436 if (sel->type == SEL_SUBEXPR)
1438 if (sel->cdata->refcount == 1)
1440 sel->cdata->flags |= SEL_CDATA_SIMPLESUBEXPR;
1442 else if (!(sel->cdata->flags & SEL_CDATA_FULLEVAL))
1444 sel->cdata->flags |= SEL_CDATA_COMMONSUBEXPR;
1447 else if (sel->type == SEL_SUBEXPRREF
1448 && (sel->child->cdata->flags & SEL_CDATA_SIMPLESUBEXPR))
1450 sel->cdata->flags |= SEL_CDATA_SIMPLESUBEXPR;
1453 /* Process children, but only follow subexpression references if the
1454 * common subexpression flag needs to be propagated. */
1455 if (sel->type != SEL_SUBEXPRREF
1456 || ((sel->cdata->flags & SEL_CDATA_COMMONSUBEXPR)
1457 && !(sel->child->cdata->flags & SEL_CDATA_SIMPLESUBEXPR)))
1459 SelectionTreeElementPointer child = sel->child;
1462 if (!(child->cdata->flags & SEL_CDATA_COMMONSUBEXPR))
1464 if (sel->type != SEL_EXPRESSION || (child->flags & SEL_ATOMVAL))
1466 child->cdata->flags |=
1467 (sel->cdata->flags & SEL_CDATA_COMMONSUBEXPR);
1469 init_item_subexpr_flags(child);
1471 child = child->next;
1477 * Initializes the gmin and gmax fields of the compiler data structure.
1479 * \param sel Root of the selection subtree to process.
1482 init_item_minmax_groups(const SelectionTreeElementPointer &sel)
1484 /* Process children. */
1485 if (sel->type != SEL_SUBEXPRREF)
1487 SelectionTreeElementPointer child = sel->child;
1490 init_item_minmax_groups(child);
1491 child = child->next;
1495 /* Initialize the minimum and maximum evaluation groups. */
1496 if (sel->type != SEL_ROOT && sel->v.type != NO_VALUE)
1498 if (sel->v.type == GROUP_VALUE
1499 && (sel->cdata->flags & SEL_CDATA_STATIC))
1501 sel->cdata->gmin = sel->v.u.g;
1502 sel->cdata->gmax = sel->v.u.g;
1504 else if (sel->type == SEL_SUBEXPR
1505 && ((sel->cdata->flags & SEL_CDATA_SIMPLESUBEXPR)
1506 || (sel->cdata->flags & SEL_CDATA_FULLEVAL)))
1508 GMX_ASSERT(sel->child,
1509 "Subexpression elements should always have a child element");
1510 sel->cdata->gmin = sel->child->cdata->gmin;
1511 sel->cdata->gmax = sel->child->cdata->gmax;
1515 sel->cdata->flags |= SEL_CDATA_MINMAXALLOC | SEL_CDATA_DOMINMAX;
1516 snew(sel->cdata->gmin, 1);
1517 snew(sel->cdata->gmax, 1);
1523 /********************************************************************
1524 * EVALUATION GROUP INITIALIZATION
1525 ********************************************************************/
1528 * Initializes evaluation groups for root items.
1530 * \param[in,out] sc Selection collection data.
1532 * The evaluation group of each \ref SEL_ROOT element corresponding to a
1533 * selection in \p sc is set to \p gall. The same is done for \ref SEL_ROOT
1534 * elements corresponding to subexpressions that need full evaluation.
1537 initialize_evalgrps(gmx_ana_selcollection_t *sc)
1539 SelectionTreeElementPointer root = sc->root;
1542 GMX_RELEASE_ASSERT(root->child,
1543 "Root elements should always have a child");
1544 if (root->child->type != SEL_SUBEXPR
1545 || (root->child->cdata->flags & SEL_CDATA_FULLEVAL))
1547 gmx_ana_index_set(&root->u.cgrp, sc->gall.isize, sc->gall.index,
1548 root->u.cgrp.name, 0);
1555 /********************************************************************
1557 ********************************************************************/
1560 * Marks a subtree completely dynamic or undoes such a change.
1562 * \param sel Selection subtree to mark.
1563 * \param[in] bDynamic If true, the \p bStatic flag of the whole
1564 * selection subtree is cleared. If false, the flag is restored to
1565 * using \ref SEL_DYNAMIC.
1567 * Does not descend into parameters of methods unless the parameters
1568 * are evaluated for each atom.
1571 mark_subexpr_dynamic(const SelectionTreeElementPointer &sel,
1574 if (!bDynamic && !(sel->flags & SEL_DYNAMIC))
1576 sel->cdata->flags |= SEL_CDATA_STATIC;
1580 sel->cdata->flags &= ~SEL_CDATA_STATIC;
1582 SelectionTreeElementPointer child = sel->child;
1585 if (sel->type != SEL_EXPRESSION || child->type != SEL_SUBEXPRREF
1586 || (child->u.param->flags & SPAR_ATOMVAL))
1588 mark_subexpr_dynamic(child, bDynamic);
1590 child = child->next;
1595 * Frees memory for subexpressions that are no longer needed.
1597 * \param sel Selection subtree to check.
1599 * Checks whether the subtree rooted at \p sel refers to any \ref SEL_SUBEXPR
1600 * elements that are not referred to by anything else except their own root
1601 * element. If such elements are found, all memory allocated for them is freed
1602 * except the actual element. The element is left because otherwise a dangling
1603 * pointer would be left at the root element, which is not traversed by this
1604 * function. Later compilation passes remove the stub elements.
1607 release_subexpr_memory(const SelectionTreeElementPointer &sel)
1609 if (sel->type == SEL_SUBEXPRREF)
1611 const SelectionTreeElementPointer &subexpr = sel->child;
1612 if (subexpr.use_count() == 2)
1614 release_subexpr_memory(subexpr);
1616 subexpr->child.reset();
1617 subexpr->freeValues();
1618 subexpr->freeExpressionData();
1619 subexpr->freeCompilerData();
1624 SelectionTreeElementPointer child = sel->child;
1627 release_subexpr_memory(child);
1628 child = child->next;
1634 * Makes an evaluated selection element static.
1636 * \param sel Selection element to make static.
1638 * The evaluated value becomes the value of the static element.
1639 * The element type is changed to SEL_CONST and the children are
1643 make_static(const SelectionTreeElementPointer &sel)
1645 /* If this is a subexpression reference and the data is stored in the
1646 * child, we transfer data ownership before doing anything else. */
1647 if (sel->type == SEL_SUBEXPRREF
1648 && (sel->cdata->flags & SEL_CDATA_SIMPLESUBEXPR))
1650 if (sel->child->child->flags & SEL_ALLOCDATA)
1652 sel->flags |= SEL_ALLOCDATA;
1653 sel->child->child->flags &= ~SEL_ALLOCDATA;
1655 if (sel->child->child->flags & SEL_ALLOCVAL)
1657 sel->flags |= SEL_ALLOCVAL;
1658 sel->v.nalloc = sel->child->child->v.nalloc;
1659 sel->child->child->flags &= ~SEL_ALLOCVAL;
1660 sel->child->child->v.nalloc = -1;
1663 /* Free the children. */
1664 release_subexpr_memory(sel);
1666 /* Free the expression data as it is no longer needed */
1667 sel->freeExpressionData();
1668 /* Make the item static */
1669 sel->type = SEL_CONST;
1670 sel->evaluate = NULL;
1671 sel->cdata->evaluate = NULL;
1672 /* Set the group value.
1673 * freeExpressionData() frees the cgrp group, so we can just override it.
1675 if (sel->v.type == GROUP_VALUE)
1677 gmx_ana_index_set(&sel->u.cgrp, sel->v.u.g->isize, sel->v.u.g->index, NULL, 0);
1682 * Evaluates a constant expression during analyze_static().
1684 * \param[in] data Evaluation data.
1685 * \param[in,out] sel Selection to process.
1686 * \param[in] g The evaluation group.
1687 * \returns 0 on success, a non-zero error code on error.
1690 process_const(gmx_sel_evaluate_t *data,
1691 const SelectionTreeElementPointer &sel,
1694 if (sel->v.type == GROUP_VALUE)
1696 if (sel->cdata->evaluate)
1698 sel->cdata->evaluate(data, sel, g);
1701 /* Other constant expressions do not need evaluation */
1705 * Sets the parameter value pointer for \ref SEL_SUBEXPRREF params.
1707 * \param[in,out] sel Selection to process.
1709 * Copies the value pointer of \p sel to \c sel->u.param if one is present
1710 * and should receive the value from the compiler
1711 * (most parameter values are handled during parsing).
1712 * If \p sel is not of type \ref SEL_SUBEXPRREF, or if \c sel->u.param is NULL,
1713 * the function does nothing.
1714 * Also, if the \c sel->u.param does not have \ref SPAR_VARNUM or
1715 * \ref SPAR_ATOMVAL, the function returns immediately.
1718 store_param_val(const SelectionTreeElementPointer &sel)
1720 /* Return immediately if there is no parameter. */
1721 if (sel->type != SEL_SUBEXPRREF || !sel->u.param)
1726 /* Or if the value does not need storing. */
1727 if (!(sel->u.param->flags & (SPAR_VARNUM | SPAR_ATOMVAL)))
1732 if (sel->v.type == INT_VALUE || sel->v.type == REAL_VALUE
1733 || sel->v.type == STR_VALUE)
1735 _gmx_selvalue_setstore(&sel->u.param->val, sel->v.u.ptr);
1740 * Handles the initialization of a selection method during analyze_static() pass.
1742 * \param[in,out] sel Selection element to process.
1743 * \param[in] top Topology structure.
1744 * \param[in] isize Size of the evaluation group for the element.
1745 * \returns 0 on success, a non-zero error code on return.
1747 * Calls sel_initfunc() (and possibly sel_outinitfunc()) to initialize the
1749 * If no \ref SPAR_ATOMVAL parameters are present, multiple initialization
1750 * is prevented by using \ref SEL_METHODINIT and \ref SEL_OUTINIT flags.
1753 init_method(const SelectionTreeElementPointer &sel, t_topology *top, int isize)
1755 /* Find out whether there are any atom-valued parameters */
1756 bool bAtomVal = false;
1757 SelectionTreeElementPointer child = sel->child;
1760 if (child->flags & SEL_ATOMVAL)
1764 child = child->next;
1767 /* Initialize the method */
1768 if (sel->u.expr.method->init
1769 && (bAtomVal || !(sel->flags & SEL_METHODINIT)))
1771 sel->flags |= SEL_METHODINIT;
1772 sel->u.expr.method->init(top, sel->u.expr.method->nparams,
1773 sel->u.expr.method->param, sel->u.expr.mdata);
1775 if (bAtomVal || !(sel->flags & SEL_OUTINIT))
1777 sel->flags |= SEL_OUTINIT;
1778 if (sel->u.expr.method->outinit)
1780 sel->u.expr.method->outinit(top, &sel->v, sel->u.expr.mdata);
1781 if (sel->v.type != POS_VALUE && sel->v.type != GROUP_VALUE)
1783 alloc_selection_data(sel, isize, true);
1788 alloc_selection_data(sel, isize, true);
1789 if ((sel->flags & SEL_DYNAMIC)
1790 && sel->v.type != GROUP_VALUE && sel->v.type != POS_VALUE)
1794 /* If the method is char-valued, pre-allocate the strings. */
1795 if (sel->u.expr.method->flags & SMETH_CHARVAL)
1799 /* A sanity check */
1800 if (sel->v.type != STR_VALUE)
1802 GMX_THROW(gmx::InternalError("Char-valued selection method in non-string element"));
1804 sel->flags |= SEL_ALLOCDATA;
1805 for (i = 0; i < isize; ++i)
1807 if (sel->v.u.s[i] == NULL)
1809 snew(sel->v.u.s[i], 2);
1814 /* Clear the values for dynamic output to avoid valgrind warnings. */
1815 if ((sel->flags & SEL_DYNAMIC) && sel->v.type == REAL_VALUE)
1819 for (i = 0; i < sel->v.nr; ++i)
1821 sel->v.u.r[i] = 0.0;
1828 * Evaluates the static part of a boolean expression.
1830 * \param[in] data Evaluation data.
1831 * \param[in,out] sel Boolean selection element whose children should be
1833 * \param[in] g The evaluation group.
1834 * \returns 0 on success, a non-zero error code on error.
1836 * reorder_item_static_children() should have been called.
1839 evaluate_boolean_static_part(gmx_sel_evaluate_t *data,
1840 const SelectionTreeElementPointer &sel,
1843 /* Find the last static subexpression */
1844 SelectionTreeElementPointer child = sel->child;
1845 while (child->next && (child->next->cdata->flags & SEL_CDATA_STATIC))
1847 child = child->next;
1849 if (!(child->cdata->flags & SEL_CDATA_STATIC))
1854 /* Evalute the static part if there is more than one expression */
1855 if (child != sel->child)
1857 SelectionTreeElementPointer next = child->next;
1858 child->next.reset();
1859 sel->cdata->evaluate(data, sel, g);
1860 /* Replace the subexpressions with the result */
1861 child.reset(new SelectionTreeElement(SEL_CONST));
1862 child->flags = SEL_FLAGSSET | SEL_SINGLEVAL | SEL_ALLOCVAL | SEL_ALLOCDATA;
1863 _gmx_selelem_set_vtype(child, GROUP_VALUE);
1864 child->evaluate = NULL;
1865 _gmx_selvalue_reserve(&child->v, 1);
1866 gmx_ana_index_copy(child->v.u.g, sel->v.u.g, true);
1867 init_item_compilerdata(child);
1868 init_item_minmax_groups(child);
1869 child->cdata->flags &= ~SEL_CDATA_STATICEVAL;
1870 child->cdata->flags |= sel->cdata->flags & SEL_CDATA_STATICEVAL;
1872 // Frees the old static subexpressions.
1875 else if (child->evaluate)
1877 child->evaluate(data, child, g);
1879 /* Set the evaluation function for the constant element.
1880 * We never need to evaluate the element again during compilation,
1881 * but we may need to evaluate the static part again if the
1882 * expression is not an OR with a static evaluation group.
1883 * If we reach here with a NOT expression, the NOT expression
1884 * is also static, and will be made a constant later, so don't waste
1885 * time copying the group. */
1886 child->evaluate = NULL;
1887 if (sel->u.boolt == BOOL_NOT
1888 || ((sel->cdata->flags & SEL_CDATA_STATICEVAL)
1889 && sel->u.boolt == BOOL_OR))
1891 child->cdata->evaluate = NULL;
1895 child->cdata->evaluate = &_gmx_sel_evaluate_static;
1896 /* The cgrp has only been allocated if it originated from an
1897 * external index group. In that case, we need special handling
1898 * to preserve the name of the group and to not leak memory.
1899 * If cgrp has been set in make_static(), it is not allocated,
1900 * and hence we can overwrite it safely. */
1901 if (child->u.cgrp.nalloc_index > 0)
1903 char *name = child->u.cgrp.name;
1904 gmx_ana_index_copy(&child->u.cgrp, child->v.u.g, false);
1905 gmx_ana_index_squeeze(&child->u.cgrp);
1906 child->u.cgrp.name = name;
1910 gmx_ana_index_copy(&child->u.cgrp, child->v.u.g, true);
1916 * Evaluates the minimum and maximum groups for a boolean expression.
1918 * \param[in] sel \ref SEL_BOOLEAN element currently being evaluated.
1919 * \param[in] g Group for which \p sel has been evaluated.
1920 * \param[out] gmin Largest subset of the possible values of \p sel.
1921 * \param[out] gmax Smallest superset of the possible values of \p sel.
1923 * This is a helper function for analyze_static() that is called for
1924 * dynamic \ref SEL_BOOLEAN elements after they have been evaluated.
1925 * It uses the minimum and maximum groups of the children to calculate
1926 * the minimum and maximum groups for \p sel, and also updates the static
1927 * part of \p sel (which is in the first child) if the children give
1930 * This function may allocate some extra memory for \p gmin and \p gmax,
1931 * but as these groups are freed at the end of analyze_static() (which is
1932 * reached shortly after this function returns), this should not be a major
1936 evaluate_boolean_minmax_grps(const SelectionTreeElementPointer &sel,
1938 gmx_ana_index_t *gmin, gmx_ana_index_t *gmax)
1940 SelectionTreeElementPointer child;
1942 switch (sel->u.boolt)
1945 gmx_ana_index_reserve(gmin, g->isize);
1946 gmx_ana_index_reserve(gmax, g->isize);
1947 gmx_ana_index_difference(gmax, g, sel->child->cdata->gmin);
1948 gmx_ana_index_difference(gmin, g, sel->child->cdata->gmax);
1952 gmx_ana_index_copy(gmin, sel->child->cdata->gmin, true);
1953 gmx_ana_index_copy(gmax, sel->child->cdata->gmax, true);
1954 child = sel->child->next;
1955 while (child && gmax->isize > 0)
1957 gmx_ana_index_intersection(gmin, gmin, child->cdata->gmin);
1958 gmx_ana_index_intersection(gmax, gmax, child->cdata->gmax);
1959 child = child->next;
1961 /* Update the static part if other expressions limit it */
1962 if ((sel->child->cdata->flags & SEL_CDATA_STATIC)
1963 && sel->child->v.u.g->isize > gmax->isize)
1965 gmx_ana_index_copy(sel->child->v.u.g, gmax, false);
1966 gmx_ana_index_squeeze(sel->child->v.u.g);
1967 if (sel->child->u.cgrp.isize > 0)
1969 gmx_ana_index_copy(&sel->child->u.cgrp, gmax, false);
1970 gmx_ana_index_squeeze(&sel->child->u.cgrp);
1976 /* We can assume here that the gmin of children do not overlap
1977 * because of the way _gmx_sel_evaluate_or() works. */
1978 gmx_ana_index_reserve(gmin, g->isize);
1979 gmx_ana_index_reserve(gmax, g->isize);
1980 gmx_ana_index_copy(gmin, sel->child->cdata->gmin, false);
1981 gmx_ana_index_copy(gmax, sel->child->cdata->gmax, false);
1982 child = sel->child->next;
1983 while (child && gmin->isize < g->isize)
1985 gmx_ana_index_merge(gmin, gmin, child->cdata->gmin);
1986 gmx_ana_index_union(gmax, gmax, child->cdata->gmax);
1987 child = child->next;
1989 /* Update the static part if other expressions have static parts
1990 * that are not included. */
1991 if ((sel->child->cdata->flags & SEL_CDATA_STATIC)
1992 && sel->child->v.u.g->isize < gmin->isize)
1994 GMX_RELEASE_ASSERT(sel->child->type == SEL_CONST,
1995 "The first child should have already been evaluated "
1996 "to a constant expression");
1997 gmx_ana_index_reserve(sel->child->v.u.g, gmin->isize);
1998 gmx_ana_index_copy(sel->child->v.u.g, gmin, false);
1999 if (sel->child->u.cgrp.nalloc_index > 0)
2001 /* Keep the name as in evaluate_boolean_static_part(). */
2002 char *name = sel->child->u.cgrp.name;
2003 gmx_ana_index_reserve(&sel->child->u.cgrp, gmin->isize);
2004 gmx_ana_index_copy(&sel->child->u.cgrp, gmin, false);
2005 sel->child->u.cgrp.name = name;
2009 GMX_RELEASE_ASSERT(sel->child->u.cgrp.index == sel->child->v.u.g->index,
2010 "If not allocated, the static group should equal the value");
2011 sel->child->u.cgrp.isize = sel->child->v.u.g->isize;
2016 case BOOL_XOR: /* Should not be reached */
2017 GMX_THROW(gmx::NotImplementedError("xor expressions not implemented"));
2023 * Evaluates the static parts of \p sel and analyzes the structure.
2025 * \param[in] data Evaluation data.
2026 * \param[in,out] sel Selection currently being evaluated.
2027 * \param[in] g Group for which \p sel should be evaluated.
2028 * \returns 0 on success, a non-zero error code on error.
2030 * This function is used as the replacement for the
2031 * gmx::SelectionTreeElement::evaluate function pointer.
2032 * It does the single most complex task in the compiler: after all elements
2033 * have been processed, the \p gmin and \p gmax fields of \p t_compiler_data
2034 * have been properly initialized, enough memory has been allocated for
2035 * storing the value of each expression, and the static parts of the
2036 * expressions have been evaluated.
2037 * The above is exactly true only for elements other than subexpressions:
2038 * another pass is required for subexpressions that are referred to more than
2039 * once and whose evaluation group is not known in advance.
2042 analyze_static(gmx_sel_evaluate_t *data,
2043 const SelectionTreeElementPointer &sel,
2048 if (sel->type != SEL_ROOT && g)
2050 alloc_selection_data(sel, g->isize, false);
2053 bDoMinMax = (sel->cdata->flags & SEL_CDATA_DOMINMAX);
2054 if (sel->type != SEL_SUBEXPR && bDoMinMax)
2056 gmx_ana_index_deinit(sel->cdata->gmin);
2057 gmx_ana_index_deinit(sel->cdata->gmax);
2060 /* TODO: This switch is awfully long... */
2064 process_const(data, sel, g);
2067 case SEL_EXPRESSION:
2069 GMX_ASSERT(g, "group cannot be null");
2070 _gmx_sel_evaluate_method_params(data, sel, g);
2071 init_method(sel, data->top, g->isize);
2072 if (!(sel->flags & SEL_DYNAMIC))
2074 sel->cdata->evaluate(data, sel, g);
2075 if (sel->cdata->flags & SEL_CDATA_STATIC)
2082 /* Modifiers need to be evaluated even though they process
2083 * positions to get the modified output groups from the
2084 * maximum possible selections. */
2085 if (sel->type == SEL_MODIFIER)
2087 sel->cdata->evaluate(data, sel, g);
2091 gmx_ana_index_copy(sel->cdata->gmax, g, true);
2097 if (!(sel->flags & SEL_DYNAMIC))
2099 sel->cdata->evaluate(data, sel, g);
2100 if (sel->cdata->flags & SEL_CDATA_STATIC)
2107 /* Evalute the static part if there is more than one expression */
2108 evaluate_boolean_static_part(data, sel, g);
2110 /* Evaluate the selection.
2111 * If the type is boolean, we must explicitly handle the
2112 * static part evaluated in evaluate_boolean_static_part()
2113 * here because g may be larger. */
2114 if (sel->u.boolt == BOOL_AND && sel->child->type == SEL_CONST)
2116 sel->cdata->evaluate(data, sel, sel->child->v.u.g);
2120 sel->cdata->evaluate(data, sel, g);
2123 /* Evaluate minimal and maximal selections */
2124 evaluate_boolean_minmax_grps(sel, g, sel->cdata->gmin,
2129 case SEL_ARITHMETIC:
2130 sel->cdata->evaluate(data, sel, g);
2131 if (!(sel->flags & SEL_DYNAMIC))
2133 if (sel->cdata->flags & SEL_CDATA_STATIC)
2140 gmx_ana_index_copy(sel->cdata->gmax, g, true);
2145 sel->cdata->evaluate(data, sel, g);
2149 if (sel->cdata->flags & (SEL_CDATA_SIMPLESUBEXPR | SEL_CDATA_FULLEVAL))
2151 sel->cdata->evaluate(data, sel, g);
2152 _gmx_selvalue_setstore(&sel->v, sel->child->v.u.ptr);
2154 else if (sel->u.cgrp.isize == 0)
2156 GMX_ASSERT(g, "group cannot be null");
2157 gmx_ana_index_reserve(&sel->u.cgrp, g->isize);
2158 sel->cdata->evaluate(data, sel, g);
2161 gmx_ana_index_copy(sel->cdata->gmin, sel->child->cdata->gmin, true);
2162 gmx_ana_index_copy(sel->cdata->gmax, sel->child->cdata->gmax, true);
2167 int isize = gmx_ana_index_difference_size(g, &sel->u.cgrp);
2170 isize += sel->u.cgrp.isize;
2171 gmx_ana_index_reserve(&sel->u.cgrp, isize);
2172 alloc_selection_data(sel, isize, false);
2174 sel->cdata->evaluate(data, sel, g);
2175 if (isize > 0 && bDoMinMax)
2177 gmx_ana_index_reserve(sel->cdata->gmin,
2178 sel->cdata->gmin->isize
2179 + sel->child->cdata->gmin->isize);
2180 gmx_ana_index_reserve(sel->cdata->gmax,
2181 sel->cdata->gmax->isize
2182 + sel->child->cdata->gmax->isize);
2183 gmx_ana_index_merge(sel->cdata->gmin, sel->cdata->gmin,
2184 sel->child->cdata->gmin);
2185 gmx_ana_index_merge(sel->cdata->gmax, sel->cdata->gmax,
2186 sel->child->cdata->gmax);
2191 case SEL_SUBEXPRREF:
2192 if (!g && !(sel->cdata->flags & SEL_CDATA_SIMPLESUBEXPR))
2194 /* The subexpression should have been evaluated if g is NULL
2195 * (i.e., this is a method parameter or a direct value of a
2197 alloc_selection_data(sel, sel->child->cdata->gmax->isize, true);
2199 sel->cdata->evaluate(data, sel, g);
2200 if ((sel->cdata->flags & SEL_CDATA_SIMPLESUBEXPR)
2201 && (sel->child->child->flags & SEL_ALLOCVAL))
2203 _gmx_selvalue_setstore(&sel->v, sel->child->child->v.u.ptr);
2205 /* Store the parameter value if required */
2206 store_param_val(sel);
2207 if (!(sel->flags & SEL_DYNAMIC))
2209 if (sel->cdata->flags & SEL_CDATA_STATIC)
2216 if ((sel->cdata->flags & SEL_CDATA_SIMPLESUBEXPR) || !g)
2218 gmx_ana_index_copy(sel->cdata->gmin, sel->child->cdata->gmin, true);
2219 gmx_ana_index_copy(sel->cdata->gmax, sel->child->cdata->gmax, true);
2223 gmx_ana_index_reserve(sel->cdata->gmin,
2224 min(g->isize, sel->child->cdata->gmin->isize));
2225 gmx_ana_index_reserve(sel->cdata->gmax,
2226 min(g->isize, sel->child->cdata->gmax->isize));
2227 gmx_ana_index_intersection(sel->cdata->gmin,
2228 sel->child->cdata->gmin, g);
2229 gmx_ana_index_intersection(sel->cdata->gmax,
2230 sel->child->cdata->gmax, g);
2235 case SEL_GROUPREF: /* Should not be reached */
2236 GMX_THROW(gmx::APIError("Unresolved group reference in compilation"));
2239 /* Update the minimal and maximal evaluation groups */
2242 gmx_ana_index_squeeze(sel->cdata->gmin);
2243 gmx_ana_index_squeeze(sel->cdata->gmax);
2244 sfree(sel->cdata->gmin->name);
2245 sfree(sel->cdata->gmax->name);
2246 sel->cdata->gmin->name = NULL;
2247 sel->cdata->gmax->name = NULL;
2250 /* Replace the result of the evaluation */
2251 /* This is not necessary for subexpressions or for boolean negations
2252 * because the evaluation function already has done it properly. */
2253 if (sel->v.type == GROUP_VALUE && (sel->flags & SEL_DYNAMIC)
2254 && sel->type != SEL_SUBEXPR
2255 && !(sel->type == SEL_BOOLEAN && sel->u.boolt == BOOL_NOT))
2257 if (sel->cdata->flags & SEL_CDATA_EVALMAX)
2259 gmx_ana_index_copy(sel->v.u.g, sel->cdata->gmax, false);
2263 gmx_ana_index_copy(sel->v.u.g, sel->cdata->gmin, false);
2269 /********************************************************************
2270 * EVALUATION GROUP INITIALIZATION
2271 ********************************************************************/
2274 * Initializes the evaluation group for a \ref SEL_ROOT element.
2276 * \param root Root element to initialize.
2277 * \param[in] gall Group of all atoms.
2279 * Checks whether it is necessary to evaluate anything through the root
2280 * element, and either clears the evaluation function or initializes the
2284 init_root_item(const SelectionTreeElementPointer &root,
2285 gmx_ana_index_t *gall)
2287 const SelectionTreeElementPointer &expr = root->child;
2288 /* Subexpressions with non-static evaluation group should not be
2289 * evaluated by the root, and neither should be single-reference
2290 * subexpressions that don't evaluate for all atoms. */
2291 if (expr->type == SEL_SUBEXPR
2292 && (!(root->child->cdata->flags & SEL_CDATA_STATICEVAL)
2293 || ((root->child->cdata->flags & SEL_CDATA_SIMPLESUBEXPR)
2294 && !(root->child->cdata->flags & SEL_CDATA_FULLEVAL))))
2296 root->evaluate = NULL;
2299 root->cdata->evaluate = NULL;
2303 /* Set the evaluation group */
2304 char *name = root->u.cgrp.name;
2307 /* Non-atom-valued non-group expressions don't care about the group, so
2308 * don't allocate any memory for it. */
2309 if ((expr->flags & SEL_VARNUMVAL)
2310 || ((expr->flags & SEL_SINGLEVAL) && expr->v.type != GROUP_VALUE))
2312 gmx_ana_index_set(&root->u.cgrp, -1, NULL, NULL, 0);
2314 else if (expr->cdata->gmax->isize == gall->isize)
2316 /* Save some memory by only referring to the global group. */
2317 gmx_ana_index_set(&root->u.cgrp, gall->isize, gall->index, NULL, 0);
2321 gmx_ana_index_copy(&root->u.cgrp, expr->cdata->gmax, true);
2323 /* For selections, store the maximum group for
2324 * gmx_ana_selcollection_evaluate_fin() as the value of the root
2325 * element (unused otherwise). */
2326 if (expr->type != SEL_SUBEXPR && expr->v.u.p->g)
2328 SelectionTreeElementPointer child = expr;
2330 /* TODO: This code is copied from parsetree.c; it would be better
2331 * to have this hardcoded only in one place. */
2332 while (child->type == SEL_MODIFIER)
2334 child = child->child;
2335 if (child->type == SEL_SUBEXPRREF)
2337 child = child->child->child;
2340 if (child->type == SEL_SUBEXPRREF)
2342 child = child->child->child;
2344 if (child->child->flags & SEL_DYNAMIC)
2346 _gmx_selelem_set_vtype(root, GROUP_VALUE);
2347 root->flags |= (SEL_ALLOCVAL | SEL_ALLOCDATA);
2348 _gmx_selvalue_reserve(&root->v, 1);
2349 gmx_ana_index_copy(root->v.u.g, expr->v.u.p->g, true);
2355 gmx_ana_index_clear(&root->u.cgrp);
2357 root->u.cgrp.name = name;
2361 /********************************************************************
2362 * FINAL SUBEXPRESSION OPTIMIZATION
2363 ********************************************************************/
2366 * Optimizes subexpression evaluation.
2368 * \param sel Root of the selection subtree to process.
2370 * Optimizes away some unnecessary evaluation of subexpressions that are only
2374 postprocess_item_subexpressions(const SelectionTreeElementPointer &sel)
2376 GMX_ASSERT(!(sel->child == NULL &&
2377 (sel->type == SEL_SUBEXPRREF || sel->type == SEL_SUBEXPR)),
2378 "Subexpression elements should always have a child element");
2380 /* Process children. */
2381 if (sel->type != SEL_SUBEXPRREF)
2383 SelectionTreeElementPointer child = sel->child;
2386 postprocess_item_subexpressions(child);
2387 child = child->next;
2391 /* Replace the evaluation function of statically evaluated subexpressions
2392 * for which the static group was not known in advance. */
2393 if (sel->type == SEL_SUBEXPR && sel->cdata->refcount > 1
2394 && (sel->cdata->flags & SEL_CDATA_STATICEVAL)
2395 && !(sel->cdata->flags & SEL_CDATA_FULLEVAL))
2399 /* We need to free memory allocated for the group, because it is no
2400 * longer needed (and would be lost on next call to the evaluation
2401 * function). But we need to preserve the name. */
2402 name = sel->u.cgrp.name;
2403 gmx_ana_index_deinit(&sel->u.cgrp);
2404 sel->u.cgrp.name = name;
2406 sel->evaluate = &_gmx_sel_evaluate_subexpr_staticeval;
2407 sel->cdata->evaluate = sel->evaluate;
2409 sel->child->freeValues();
2410 sel->child->mempool = NULL;
2411 _gmx_selvalue_setstore(&sel->child->v, sel->v.u.ptr);
2412 sel->child->flags &= ~(SEL_ALLOCVAL | SEL_ALLOCDATA);
2415 /* Adjust memory allocation flags for subexpressions that are used only
2416 * once. This is not strictly necessary, but we do it to have the memory
2417 * managed consistently for all types of subexpressions. */
2418 if (sel->type == SEL_SUBEXPRREF
2419 && (sel->cdata->flags & SEL_CDATA_SIMPLESUBEXPR))
2421 if (sel->child->child->flags & SEL_ALLOCVAL)
2423 sel->flags |= SEL_ALLOCVAL;
2424 sel->flags |= (sel->child->child->flags & SEL_ALLOCDATA);
2425 sel->v.nalloc = sel->child->child->v.nalloc;
2426 sel->child->child->flags &= ~(SEL_ALLOCVAL | SEL_ALLOCDATA);
2427 sel->child->child->v.nalloc = -1;
2431 /* Do the same for subexpressions that are evaluated at once for all atoms. */
2432 if (sel->type == SEL_SUBEXPR
2433 && !(sel->cdata->flags & SEL_CDATA_SIMPLESUBEXPR)
2434 && (sel->cdata->flags & SEL_CDATA_FULLEVAL))
2436 sel->flags |= SEL_ALLOCVAL;
2437 sel->flags |= (sel->child->flags & SEL_ALLOCDATA);
2438 sel->v.nalloc = sel->child->v.nalloc;
2439 sel->child->flags &= ~(SEL_ALLOCVAL | SEL_ALLOCDATA);
2440 sel->child->v.nalloc = -1;
2445 /********************************************************************
2446 * COM CALCULATION INITIALIZATION
2447 ********************************************************************/
2450 * Initializes COM/COG calculation for method expressions that require it.
2452 * \param sel Selection subtree to process.
2453 * \param[in,out] pcc Position calculation collection to use.
2454 * \param[in] type Default position calculation type.
2455 * \param[in] flags Flags for default position calculation.
2457 * Searches recursively through the selection tree for dynamic
2458 * \ref SEL_EXPRESSION elements that define the \c gmx_ana_selmethod_t::pupdate
2460 * For each such element found, position calculation is initialized
2461 * for the maximal evaluation group.
2462 * The type of the calculation is determined by \p type and \p flags.
2463 * No calculation is initialized if \p type equals \ref POS_ATOM and
2464 * the method also defines the \c gmx_ana_selmethod_t::update method.
2467 init_item_comg(const SelectionTreeElementPointer &sel,
2468 gmx::PositionCalculationCollection *pcc,
2469 e_poscalc_t type, int flags)
2471 /* Initialize COM calculation for dynamic selections now that we know the maximal evaluation group */
2472 if (sel->type == SEL_EXPRESSION && sel->u.expr.method
2473 && sel->u.expr.method->pupdate)
2475 if (!sel->u.expr.method->update || type != POS_ATOM)
2477 /* Create a default calculation if one does not yet exist */
2479 if (!(sel->cdata->flags & SEL_CDATA_STATICEVAL))
2481 cflags |= POS_DYNAMIC;
2483 if (!sel->u.expr.pc)
2486 sel->u.expr.pc = pcc->createCalculation(type, cflags);
2490 gmx_ana_poscalc_set_flags(sel->u.expr.pc, cflags);
2492 gmx_ana_poscalc_set_maxindex(sel->u.expr.pc, sel->cdata->gmax);
2493 snew(sel->u.expr.pos, 1);
2494 gmx_ana_poscalc_init_pos(sel->u.expr.pc, sel->u.expr.pos);
2498 /* Call recursively for all children unless the children have already been processed */
2499 if (sel->type != SEL_SUBEXPRREF)
2501 SelectionTreeElementPointer child = sel->child;
2504 init_item_comg(child, pcc, type, flags);
2505 child = child->next;
2511 /********************************************************************
2512 * COMPILER DATA FREEING
2513 ********************************************************************/
2516 * Frees the allocated compiler data recursively.
2518 * \param sel Root of the selection subtree to process.
2520 * Frees the data allocated for the compilation process.
2523 free_item_compilerdata(const SelectionTreeElementPointer &sel)
2525 /* Free compilation data */
2526 sel->freeCompilerData();
2528 /* Call recursively for all children unless the children have already been processed */
2529 if (sel->type != SEL_SUBEXPRREF)
2531 SelectionTreeElementPointer child = sel->child;
2534 free_item_compilerdata(child);
2535 child = child->next;
2541 /********************************************************************
2542 * MAIN COMPILATION FUNCTION
2543 ********************************************************************/
2548 SelectionCompiler::SelectionCompiler()
2553 * \param[in,out] coll Selection collection to be compiled.
2554 * \returns 0 on successful compilation, a non-zero error code on error.
2556 * Before compilation, the selection collection should have been initialized
2557 * with gmx_ana_selcollection_parse_*().
2558 * The compiled selection collection can be passed to
2559 * gmx_ana_selcollection_evaluate() to evaluate the selection for a frame.
2560 * If an error occurs, \p sc is cleared.
2562 * The covered fraction information in \p sc is initialized to
2566 SelectionCompiler::compile(SelectionCollection *coll)
2568 gmx_ana_selcollection_t *sc = &coll->impl_->sc_;
2569 gmx_sel_evaluate_t evaldata;
2570 SelectionTreeElementPointer item;
2574 bool bDebug = (coll->impl_->debugLevel_ >= 2
2575 && coll->impl_->debugLevel_ != 3);
2577 /* FIXME: Clean up the collection on exceptions */
2579 sc->mempool = _gmx_sel_mempool_create();
2580 _gmx_sel_evaluate_init(&evaldata, sc->mempool, &sc->gall,
2581 sc->top, NULL, NULL);
2583 /* Clear the symbol table because it is not possible to parse anything
2584 * after compilation, and variable references in the symbol table can
2585 * also mess up the compilation and/or become invalid.
2587 coll->impl_->clearSymbolTable();
2589 /* Loop through selections and initialize position keyword defaults if no
2590 * other value has been provided.
2592 for (i = 0; i < sc->sel.size(); ++i)
2594 gmx::internal::SelectionData &sel = *sc->sel[i];
2595 init_pos_keyword_defaults(&sel.rootElement(),
2596 coll->impl_->spost_.c_str(),
2597 coll->impl_->rpost_.c_str(),
2601 /* Remove any unused variables. */
2602 sc->root = remove_unused_subexpressions(sc->root);
2603 /* Extract subexpressions into separate roots */
2604 sc->root = extract_subexpressions(sc->root);
2606 /* Initialize the evaluation callbacks and process the tree structure
2607 * to conform to the expectations of the callback functions. */
2608 /* Also, initialize and allocate the compiler data structure */
2612 /* Process boolean and arithmetic expressions. */
2613 optimize_boolean_expressions(item);
2614 reorder_boolean_static_children(item);
2615 optimize_arithmetic_expressions(item);
2616 /* Initialize the compiler data */
2617 init_item_compilerdata(item);
2618 init_item_staticeval(item);
2619 init_item_subexpr_refcount(item);
2622 /* Initialize subexpression flags.
2623 * Requires compiler flags for the full tree. */
2627 init_item_subexpr_flags(item);
2630 /* Initialize evaluation.
2631 * Requires subexpression flags. */
2635 init_item_evalfunc(item);
2636 setup_memory_pooling(item, sc->mempool);
2637 init_item_evaloutput(item);
2640 /* Initialize minimum/maximum index groups.
2641 * Requires evaluation output for the full tree. */
2645 init_item_minmax_groups(item);
2648 /* Initialize the evaluation index groups */
2649 initialize_evalgrps(sc);
2653 fprintf(stderr, "\nTree after initial compiler processing:\n");
2654 coll->printTree(stderr, false);
2657 /* Evaluate all static parts of the selection and analyze the tree
2658 * to allocate enough memory to store the value of each dynamic subtree. */
2662 if (item->child->cdata->flags & SEL_CDATA_COMMONSUBEXPR)
2664 mark_subexpr_dynamic(item->child, true);
2666 set_evaluation_function(item, &analyze_static);
2667 item->evaluate(&evaldata, item, NULL);
2671 /* At this point, static subexpressions no longer have references to them,
2672 * so they can be removed. */
2673 sc->root = remove_unused_subexpressions(sc->root);
2674 // Update the reference counts for consistency (only used for the
2675 // debugging output below).
2679 init_item_subexpr_refcount(item);
2685 fprintf(stderr, "\nTree after first analysis pass:\n");
2686 coll->printTree(stderr, false);
2689 /* Do a second pass to evaluate static parts of common subexpressions */
2693 if (item->child->cdata->flags & SEL_CDATA_COMMONSUBEXPR)
2695 bool bMinMax = item->child->cdata->flags & SEL_CDATA_DOMINMAX;
2697 mark_subexpr_dynamic(item->child, false);
2698 item->child->u.cgrp.isize = 0;
2699 /* We won't clear item->child->v.u.g here, because it may
2700 * be static, and hence actually point to item->child->cdata->gmax,
2701 * which is used below. We could also check whether this is the
2702 * case and only clear the group otherwise, but because the value
2703 * is actually overwritten immediately in the evaluate call, we
2704 * won't, because similar problems may arise if gmax handling ever
2705 * changes and the check were not updated.
2706 * For the same reason, we clear the min/max flag so that the
2707 * evaluation group doesn't get messed up. */
2708 set_evaluation_function(item, &analyze_static);
2709 item->child->cdata->flags &= ~SEL_CDATA_DOMINMAX;
2710 item->evaluate(&evaldata, item->child, item->child->cdata->gmax);
2713 item->child->cdata->flags |= SEL_CDATA_DOMINMAX;
2719 /* We need a yet another pass of subexpression removal to remove static
2720 * subexpressions referred to by common dynamic subexpressions. */
2721 sc->root = remove_unused_subexpressions(sc->root);
2722 // Update the reference counts, used by postprocess_item_subexpressions().
2726 init_item_subexpr_refcount(item);
2732 fprintf(stderr, "\nTree after second analysis pass:\n");
2733 coll->printTree(stderr, false);
2736 /* Initialize evaluation groups, position calculations for methods, perform
2737 * some final optimization, and free the memory allocated for the
2739 /* By default, use whole residues/molecules. */
2740 flags = POS_COMPLWHOLE;
2741 PositionCalculationCollection::typeFromEnum(coll->impl_->rpost_.c_str(),
2746 init_root_item(item, &sc->gall);
2747 postprocess_item_subexpressions(item);
2748 init_item_comg(item, &sc->pcc, post, flags);
2749 free_item_compilerdata(item);
2753 /* Allocate memory for the evaluation memory pool. */
2754 _gmx_sel_mempool_reserve(sc->mempool, 0);
2756 /* Finish up by calculating total masses and charges. */
2757 for (i = 0; i < sc->sel.size(); ++i)
2759 sc->sel[i]->initializeMassesAndCharges(sc->top);