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 in
692 * gmx::SelectionTreeElement::name and gmx::SelectionTreeElement::u::cgrp::name; the latter
693 * is freed by _gmx_selelem_free().
696 create_subexpression_name(const SelectionTreeElementPointer &sel, int i)
698 char *name = strdup(gmx::formatString("SubExpr %d", i).c_str());
701 sel->u.cgrp.name = name;
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 * It also excludes subexpression elements that have already been
741 * processed, because they are given a name when they are first
743 * TODO: There should be a more robust mechanism (probably a dedicated
744 * flag) for detecting parser-generated subexpressions than relying on
745 * a NULL name field. Additional TODO: This mechanism doesn't seem to
746 * be currently used. */
747 if (child->type == SEL_SUBEXPRREF && (child->child->type != SEL_SUBEXPR
748 || child->child->name == NULL))
750 /* Create the root element for the subexpression */
753 root.reset(new SelectionTreeElement(SEL_ROOT));
758 subexpr->next.reset(new SelectionTreeElement(SEL_ROOT));
759 subexpr = subexpr->next;
761 /* Create the subexpression element and/or
762 * move the actual subexpression under the created element. */
763 if (child->child->type != SEL_SUBEXPR)
765 subexpr->child.reset(new SelectionTreeElement(SEL_SUBEXPR));
766 _gmx_selelem_set_vtype(subexpr->child, child->v.type);
767 subexpr->child->child = child->child;
768 child->child = subexpr->child;
772 subexpr->child = child->child;
774 create_subexpression_name(subexpr->child, ++*subexprn);
775 /* Set the flags for the created elements */
776 subexpr->flags |= (child->flags & SEL_VALFLAGMASK);
777 subexpr->child->flags |= (child->flags & SEL_VALFLAGMASK);
786 * Extracts subexpressions of the selection chain.
788 * \param sel First selection in the whole selection chain.
789 * \returns The new first element for the chain.
791 * Finds all the subexpressions (and their subexpressions) in the
792 * selection chain starting from \p sel and creates \ref SEL_SUBEXPR
794 * \ref SEL_ROOT elements are also created for each subexpression
795 * and inserted into the selection chain before the expressions that
798 static SelectionTreeElementPointer
799 extract_subexpressions(SelectionTreeElementPointer sel)
801 SelectionTreeElementPointer root;
802 SelectionTreeElementPointer next = sel;
806 SelectionTreeElementPointer item
807 = extract_item_subselections(next, &subexprn);
835 /********************************************************************
836 * BOOLEAN OPERATION REORDERING
837 ********************************************************************/
840 * Removes redundant boolean selection elements.
842 * \param sel Root of the selection subtree to optimize.
844 * This function merges similar boolean operations (e.g., (A or B) or C becomes
845 * a single OR operation with three operands).
848 optimize_boolean_expressions(const SelectionTreeElementPointer &sel)
850 /* Do recursively for children */
851 if (sel->type != SEL_SUBEXPRREF)
853 SelectionTreeElementPointer prev;
854 SelectionTreeElementPointer child = sel->child;
857 optimize_boolean_expressions(child);
858 /* Remove double negations */
859 if (child->type == SEL_BOOLEAN && child->u.boolt == BOOL_NOT
860 && child->child->type == SEL_BOOLEAN && child->child->u.boolt == BOOL_NOT)
862 /* Move the doubly negated expression up two levels */
865 sel->child = child->child->child;
870 prev->next = child->child->child;
873 child->child->child->next = child->next;
874 // Discards the two negations.
881 if (sel->type != SEL_BOOLEAN || sel->u.boolt == BOOL_NOT)
885 /* Merge subsequent binary operations */
886 SelectionTreeElementPointer prev;
887 SelectionTreeElementPointer child = sel->child;
890 if (child->type == SEL_BOOLEAN && child->u.boolt == sel->u.boolt)
894 sel->child = child->child;
899 prev->next = child->child;
905 prev->next = child->next;
906 // Discards the old child.
918 * Reorders children of boolean expressions such that static selections
921 * \param sel Root of the selection subtree to reorder.
923 * The relative order of static expressions does not change.
924 * The same is true for the dynamic expressions.
927 reorder_boolean_static_children(const SelectionTreeElementPointer &sel)
929 /* Do recursively for children */
930 if (sel->type != SEL_SUBEXPRREF)
932 SelectionTreeElementPointer child = sel->child;
935 reorder_boolean_static_children(child);
940 /* Reorder boolean expressions such that static selections come first */
941 if (sel->type == SEL_BOOLEAN && (sel->flags & SEL_DYNAMIC))
943 // Add a dummy head element that precedes the first child.
944 SelectionTreeElementPointer dummy(
945 new SelectionTreeElement(SEL_BOOLEAN));
946 dummy->next = sel->child;
947 SelectionTreeElementPointer prev = dummy;
948 SelectionTreeElementPointer child = dummy;
951 /* child is the last handled static expression */
952 /* prev is the last handled non-static expression */
953 SelectionTreeElementPointer next = prev->next;
954 while (next && (next->flags & SEL_DYNAMIC))
959 /* next is now the first static expression after child */
964 /* Reorder such that next comes after child */
967 prev->next = next->next;
968 next->next = child->next;
975 /* Advance child by one */
979 sel->child = dummy->next;
984 /********************************************************************
985 * ARITHMETIC EXPRESSION PROCESSING
986 ********************************************************************/
989 * Processes arithmetic expressions to simplify and speed up evaluation.
991 * \param sel Root of the selection subtree to process.
993 * Currently, this function only converts integer constants to reals
994 * within arithmetic expressions.
997 optimize_arithmetic_expressions(const SelectionTreeElementPointer &sel)
999 /* Do recursively for children. */
1000 if (sel->type != SEL_SUBEXPRREF)
1002 SelectionTreeElementPointer child = sel->child;
1005 optimize_arithmetic_expressions(child);
1006 child = child->next;
1010 if (sel->type != SEL_ARITHMETIC)
1015 /* Convert integer constants to reals. */
1016 SelectionTreeElementPointer child = sel->child;
1019 if (child->v.type == INT_VALUE)
1023 if (child->type != SEL_CONST)
1025 GMX_THROW(gmx::InconsistentInputError("Non-constant integer expressions not implemented in arithmetic evaluation"));
1028 r[0] = child->v.u.i[0];
1029 sfree(child->v.u.i);
1031 child->v.type = REAL_VALUE;
1033 else if (child->v.type != REAL_VALUE)
1035 GMX_THROW(gmx::InternalError("Non-numerical value in arithmetic expression"));
1037 child = child->next;
1042 /********************************************************************
1043 * EVALUATION PREPARATION COMPILER
1044 ********************************************************************/
1047 * Sets the evaluation functions for the selection (sub)tree.
1049 * \param[in,out] sel Root of the selection subtree to process.
1051 * This function sets the evaluation function
1052 * (gmx::SelectionTreeElement::evaluate) for the selection elements.
1055 init_item_evalfunc(const SelectionTreeElementPointer &sel)
1057 /* Process children. */
1058 if (sel->type != SEL_SUBEXPRREF)
1060 SelectionTreeElementPointer child = sel->child;
1063 init_item_evalfunc(child);
1064 child = child->next;
1068 /* Set the evaluation function */
1072 if (sel->v.type == GROUP_VALUE)
1074 sel->evaluate = &_gmx_sel_evaluate_static;
1078 case SEL_EXPRESSION:
1079 if (!(sel->flags & SEL_DYNAMIC) && sel->u.expr.method
1080 && sel->u.expr.method->init_frame)
1082 sel->flags |= SEL_INITFRAME;
1084 sel->evaluate = &_gmx_sel_evaluate_method;
1087 case SEL_ARITHMETIC:
1088 sel->evaluate = &_gmx_sel_evaluate_arithmetic;
1092 if (sel->v.type != NO_VALUE)
1094 sel->evaluate = &_gmx_sel_evaluate_modifier;
1099 switch (sel->u.boolt)
1101 case BOOL_NOT: sel->evaluate = &_gmx_sel_evaluate_not; break;
1102 case BOOL_AND: sel->evaluate = &_gmx_sel_evaluate_and; break;
1103 case BOOL_OR: sel->evaluate = &_gmx_sel_evaluate_or; break;
1105 GMX_THROW(gmx::NotImplementedError("xor expressions not implemented"));
1110 sel->evaluate = &_gmx_sel_evaluate_root;
1114 sel->evaluate = ((sel->cdata->flags & SEL_CDATA_SIMPLESUBEXPR)
1115 ? &_gmx_sel_evaluate_subexpr_simple
1116 : &_gmx_sel_evaluate_subexpr);
1119 case SEL_SUBEXPRREF:
1120 sel->name = sel->child->name;
1121 sel->evaluate = ((sel->cdata->flags & SEL_CDATA_SIMPLESUBEXPR)
1122 ? &_gmx_sel_evaluate_subexprref_simple
1123 : &_gmx_sel_evaluate_subexprref);
1127 GMX_THROW(gmx::APIError("Unresolved group reference in compilation"));
1129 sel->cdata->evaluate = sel->evaluate;
1133 * Sets the memory pool for selection elements that can use it.
1135 * \param sel Root of the selection subtree to process.
1136 * \param[in] mempool Memory pool to use.
1139 setup_memory_pooling(const SelectionTreeElementPointer &sel,
1140 gmx_sel_mempool_t *mempool)
1142 if (sel->type != SEL_SUBEXPRREF)
1144 SelectionTreeElementPointer child = sel->child;
1147 if ((sel->type == SEL_BOOLEAN && (child->flags & SEL_DYNAMIC))
1148 || (sel->type == SEL_ARITHMETIC && child->type != SEL_CONST
1149 && !(child->flags & SEL_SINGLEVAL))
1150 || (sel->type == SEL_SUBEXPR
1151 && !(sel->cdata->flags & SEL_CDATA_SIMPLESUBEXPR)))
1153 child->mempool = mempool;
1154 if (child->type == SEL_SUBEXPRREF
1155 && (child->child->cdata->flags & SEL_CDATA_SIMPLESUBEXPR))
1157 child->child->child->mempool = mempool;
1160 setup_memory_pooling(child, mempool);
1161 child = child->next;
1167 * Prepares the selection (sub)tree for evaluation.
1169 * \param[in,out] sel Root of the selection subtree to prepare.
1171 * It also allocates memory for the \p sel->v.u.g or \p sel->v.u.p
1172 * structure if required.
1175 init_item_evaloutput(const SelectionTreeElementPointer &sel)
1177 GMX_ASSERT(!(sel->child == NULL &&
1178 (sel->type == SEL_SUBEXPRREF || sel->type == SEL_SUBEXPR)),
1179 "Subexpression elements should always have a child element");
1181 /* Process children. */
1182 if (sel->type != SEL_SUBEXPRREF)
1184 SelectionTreeElementPointer child = sel->child;
1187 init_item_evaloutput(child);
1188 child = child->next;
1192 if (sel->type == SEL_SUBEXPR
1193 && (sel->cdata->flags & SEL_CDATA_SIMPLESUBEXPR))
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_SUBEXPR
1202 && (sel->cdata->flags & SEL_CDATA_FULLEVAL))
1204 sel->evaluate = &_gmx_sel_evaluate_subexpr_staticeval;
1205 sel->cdata->evaluate = sel->evaluate;
1206 sel->child->mempool = NULL;
1207 sel->flags &= ~(SEL_ALLOCVAL | SEL_ALLOCDATA);
1208 if (sel->v.type == GROUP_VALUE || sel->v.type == POS_VALUE)
1210 _gmx_selvalue_setstore(&sel->v, sel->child->v.u.ptr);
1213 else if (sel->type == SEL_SUBEXPRREF
1214 && (sel->cdata->flags & SEL_CDATA_SIMPLESUBEXPR))
1218 _gmx_selvalue_setstore(&sel->child->v, sel->v.u.ptr);
1219 sel->child->child->freeValues();
1220 sel->child->child->flags &= ~(SEL_ALLOCVAL | SEL_ALLOCDATA);
1221 sel->child->child->flags |= (sel->flags & SEL_ALLOCDATA);
1222 _gmx_selvalue_setstore(&sel->child->child->v, sel->v.u.ptr);
1224 else if (sel->v.type == GROUP_VALUE || sel->v.type == POS_VALUE)
1226 _gmx_selvalue_setstore(&sel->v, sel->child->child->v.u.ptr);
1228 sel->flags &= ~(SEL_ALLOCVAL | SEL_ALLOCDATA);
1231 /* Make sure that the group/position structure is allocated. */
1232 if (!sel->v.u.ptr && (sel->flags & SEL_ALLOCVAL))
1234 if (sel->v.type == GROUP_VALUE || sel->v.type == POS_VALUE)
1236 _gmx_selvalue_reserve(&sel->v, 1);
1243 /********************************************************************
1244 * COMPILER DATA INITIALIZATION
1245 ********************************************************************/
1248 * Allocates memory for the compiler data and initializes the structure.
1250 * \param sel Root of the selection subtree to process.
1253 init_item_compilerdata(const SelectionTreeElementPointer &sel)
1255 /* Allocate the compiler data structure */
1256 snew(sel->cdata, 1);
1258 /* Store the real evaluation method because the compiler will replace it */
1259 sel->cdata->evaluate = sel->evaluate;
1261 /* This will be computed separately. */
1262 sel->cdata->refcount = 0;
1264 /* Initialize the flags */
1265 sel->cdata->flags = SEL_CDATA_STATICEVAL;
1266 if (!(sel->flags & SEL_DYNAMIC))
1268 sel->cdata->flags |= SEL_CDATA_STATIC;
1270 if (sel->type == SEL_SUBEXPR)
1272 sel->cdata->flags |= SEL_CDATA_EVALMAX;
1274 /* Set the full evaluation flag for subexpressions that require it;
1275 * the subexpression has already been initialized, so we can simply
1276 * access its compilation flags.*/
1277 if (sel->type == SEL_EXPRESSION || sel->type == SEL_MODIFIER)
1279 SelectionTreeElementPointer child = sel->child;
1282 if (!(child->flags & SEL_ATOMVAL) && child->child)
1284 child->child->cdata->flags |= SEL_CDATA_FULLEVAL;
1286 child = child->next;
1289 else if (sel->type == SEL_ROOT && sel->child->type == SEL_SUBEXPRREF)
1291 sel->child->child->cdata->flags |= SEL_CDATA_FULLEVAL;
1294 /* Initialize children */
1295 if (sel->type != SEL_SUBEXPRREF)
1297 SelectionTreeElementPointer child = sel->child;
1300 init_item_compilerdata(child);
1301 child = child->next;
1305 /* Determine whether we should evaluate the minimum or the maximum
1306 * for the children of this element. */
1307 if (sel->type == SEL_BOOLEAN)
1311 bEvalMax = (sel->u.boolt == BOOL_AND);
1312 SelectionTreeElementPointer child = sel->child;
1317 child->cdata->flags |= SEL_CDATA_EVALMAX;
1319 else if (child->type == SEL_BOOLEAN && child->u.boolt == BOOL_NOT)
1321 child->child->cdata->flags |= SEL_CDATA_EVALMAX;
1323 child = child->next;
1326 else if (sel->type == SEL_EXPRESSION || sel->type == SEL_MODIFIER
1327 || sel->type == SEL_SUBEXPR)
1329 SelectionTreeElementPointer child = sel->child;
1332 child->cdata->flags |= SEL_CDATA_EVALMAX;
1333 child = child->next;
1339 * Initializes the static evaluation flag for a selection subtree.
1341 * \param[in,out] sel Root of the selection subtree to process.
1343 * Sets the \c bStaticEval in the compiler data structure:
1344 * for any element for which the evaluation group may depend on the trajectory
1345 * frame, the flag is cleared.
1347 * reorder_boolean_static_children() should have been called.
1350 init_item_staticeval(const SelectionTreeElementPointer &sel)
1352 /* Subexpressions with full evaluation should always have bStaticEval,
1353 * so don't do anything if a reference to them is encountered. */
1354 if (sel->type == SEL_SUBEXPRREF
1355 && (sel->child->cdata->flags & SEL_CDATA_FULLEVAL))
1360 /* Propagate the bStaticEval flag to children if it is not set */
1361 if (!(sel->cdata->flags & SEL_CDATA_STATICEVAL))
1363 SelectionTreeElementPointer child = sel->child;
1366 if ((sel->type != SEL_EXPRESSION && sel->type != SEL_MODIFIER)
1367 || (child->flags & SEL_ATOMVAL))
1369 if (child->cdata->flags & SEL_CDATA_STATICEVAL)
1371 child->cdata->flags &= ~SEL_CDATA_STATICEVAL;
1372 init_item_staticeval(child);
1375 child = child->next;
1378 else /* bStaticEval is set */
1380 /* For boolean expressions, any expression after the first dynamic
1381 * expression should not have bStaticEval. */
1382 if (sel->type == SEL_BOOLEAN)
1384 SelectionTreeElementPointer child = sel->child;
1385 while (child && !(child->flags & SEL_DYNAMIC))
1387 child = child->next;
1391 child = child->next;
1395 child->cdata->flags &= ~SEL_CDATA_STATICEVAL;
1396 child = child->next;
1400 /* Process the children */
1401 SelectionTreeElementPointer child = sel->child;
1404 init_item_staticeval(child);
1405 child = child->next;
1411 * Compute reference counts for subexpressions.
1413 * \param sel Root of the selection subtree to process.
1416 init_item_subexpr_refcount(const SelectionTreeElementPointer &sel)
1418 // Reset the counter when the subexpression is first encountered.
1419 if (sel->type == SEL_ROOT && sel->child->type == SEL_SUBEXPR
1420 && sel->child->cdata)
1422 sel->child->cdata->refcount = 0;
1425 if (sel->type == SEL_SUBEXPRREF)
1427 ++sel->child->cdata->refcount;
1431 SelectionTreeElementPointer child = sel->child;
1434 init_item_subexpr_refcount(child);
1435 child = child->next;
1441 * Initializes compiler flags for subexpressions.
1443 * \param sel Root of the selection subtree to process.
1446 init_item_subexpr_flags(const SelectionTreeElementPointer &sel)
1448 if (sel->type == SEL_SUBEXPR)
1450 if (sel->cdata->refcount == 1)
1452 sel->cdata->flags |= SEL_CDATA_SIMPLESUBEXPR;
1454 else if (!(sel->cdata->flags & SEL_CDATA_FULLEVAL))
1456 sel->cdata->flags |= SEL_CDATA_COMMONSUBEXPR;
1459 else if (sel->type == SEL_SUBEXPRREF
1460 && (sel->child->cdata->flags & SEL_CDATA_SIMPLESUBEXPR))
1462 sel->cdata->flags |= SEL_CDATA_SIMPLESUBEXPR;
1465 /* Process children, but only follow subexpression references if the
1466 * common subexpression flag needs to be propagated. */
1467 if (sel->type != SEL_SUBEXPRREF
1468 || ((sel->cdata->flags & SEL_CDATA_COMMONSUBEXPR)
1469 && !(sel->child->cdata->flags & SEL_CDATA_SIMPLESUBEXPR)))
1471 SelectionTreeElementPointer child = sel->child;
1474 if (!(child->cdata->flags & SEL_CDATA_COMMONSUBEXPR))
1476 if (sel->type != SEL_EXPRESSION || (child->flags & SEL_ATOMVAL))
1478 child->cdata->flags |=
1479 (sel->cdata->flags & SEL_CDATA_COMMONSUBEXPR);
1481 init_item_subexpr_flags(child);
1483 child = child->next;
1489 * Initializes the gmin and gmax fields of the compiler data structure.
1491 * \param sel Root of the selection subtree to process.
1494 init_item_minmax_groups(const SelectionTreeElementPointer &sel)
1496 /* Process children. */
1497 if (sel->type != SEL_SUBEXPRREF)
1499 SelectionTreeElementPointer child = sel->child;
1502 init_item_minmax_groups(child);
1503 child = child->next;
1507 /* Initialize the minimum and maximum evaluation groups. */
1508 if (sel->type != SEL_ROOT && sel->v.type != NO_VALUE)
1510 if (sel->v.type == GROUP_VALUE
1511 && (sel->cdata->flags & SEL_CDATA_STATIC))
1513 sel->cdata->gmin = sel->v.u.g;
1514 sel->cdata->gmax = sel->v.u.g;
1516 else if (sel->type == SEL_SUBEXPR
1517 && ((sel->cdata->flags & SEL_CDATA_SIMPLESUBEXPR)
1518 || (sel->cdata->flags & SEL_CDATA_FULLEVAL)))
1520 GMX_ASSERT(sel->child,
1521 "Subexpression elements should always have a child element");
1522 sel->cdata->gmin = sel->child->cdata->gmin;
1523 sel->cdata->gmax = sel->child->cdata->gmax;
1527 sel->cdata->flags |= SEL_CDATA_MINMAXALLOC | SEL_CDATA_DOMINMAX;
1528 snew(sel->cdata->gmin, 1);
1529 snew(sel->cdata->gmax, 1);
1535 /********************************************************************
1536 * EVALUATION GROUP INITIALIZATION
1537 ********************************************************************/
1540 * Initializes evaluation groups for root items.
1542 * \param[in,out] sc Selection collection data.
1544 * The evaluation group of each \ref SEL_ROOT element corresponding to a
1545 * selection in \p sc is set to \p gall. The same is done for \ref SEL_ROOT
1546 * elements corresponding to subexpressions that need full evaluation.
1549 initialize_evalgrps(gmx_ana_selcollection_t *sc)
1551 SelectionTreeElementPointer root = sc->root;
1554 GMX_RELEASE_ASSERT(root->child,
1555 "Root elements should always have a child");
1556 if (root->child->type != SEL_SUBEXPR
1557 || (root->child->cdata->flags & SEL_CDATA_FULLEVAL))
1559 gmx_ana_index_set(&root->u.cgrp, sc->gall.isize, sc->gall.index,
1560 root->u.cgrp.name, 0);
1567 /********************************************************************
1569 ********************************************************************/
1572 * Marks a subtree completely dynamic or undoes such a change.
1574 * \param sel Selection subtree to mark.
1575 * \param[in] bDynamic If true, the \p bStatic flag of the whole
1576 * selection subtree is cleared. If false, the flag is restored to
1577 * using \ref SEL_DYNAMIC.
1579 * Does not descend into parameters of methods unless the parameters
1580 * are evaluated for each atom.
1583 mark_subexpr_dynamic(const SelectionTreeElementPointer &sel,
1586 if (!bDynamic && !(sel->flags & SEL_DYNAMIC))
1588 sel->cdata->flags |= SEL_CDATA_STATIC;
1592 sel->cdata->flags &= ~SEL_CDATA_STATIC;
1594 SelectionTreeElementPointer child = sel->child;
1597 if (sel->type != SEL_EXPRESSION || child->type != SEL_SUBEXPRREF
1598 || (child->u.param->flags & SPAR_ATOMVAL))
1600 mark_subexpr_dynamic(child, bDynamic);
1602 child = child->next;
1607 * Frees memory for subexpressions that are no longer needed.
1609 * \param sel Selection subtree to check.
1611 * Checks whether the subtree rooted at \p sel refers to any \ref SEL_SUBEXPR
1612 * elements that are not referred to by anything else except their own root
1613 * element. If such elements are found, all memory allocated for them is freed
1614 * except the actual element. The element is left because otherwise a dangling
1615 * pointer would be left at the root element, which is not traversed by this
1616 * function. Later compilation passes remove the stub elements.
1619 release_subexpr_memory(const SelectionTreeElementPointer &sel)
1621 if (sel->type == SEL_SUBEXPRREF)
1623 const SelectionTreeElementPointer &subexpr = sel->child;
1624 if (subexpr.use_count() == 2)
1626 release_subexpr_memory(subexpr);
1627 subexpr->name = NULL;
1629 subexpr->child.reset();
1630 subexpr->freeValues();
1631 subexpr->freeExpressionData();
1632 subexpr->freeCompilerData();
1637 SelectionTreeElementPointer child = sel->child;
1640 release_subexpr_memory(child);
1641 child = child->next;
1647 * Makes an evaluated selection element static.
1649 * \param sel Selection element to make static.
1651 * The evaluated value becomes the value of the static element.
1652 * The element type is changed to SEL_CONST and the children are
1656 make_static(const SelectionTreeElementPointer &sel)
1658 /* If this is a subexpression reference and the data is stored in the
1659 * child, we transfer data ownership before doing anything else. */
1660 if (sel->type == SEL_SUBEXPRREF
1661 && (sel->cdata->flags & SEL_CDATA_SIMPLESUBEXPR))
1663 if (sel->child->child->flags & SEL_ALLOCDATA)
1665 sel->flags |= SEL_ALLOCDATA;
1666 sel->child->child->flags &= ~SEL_ALLOCDATA;
1668 if (sel->child->child->flags & SEL_ALLOCVAL)
1670 sel->flags |= SEL_ALLOCVAL;
1671 sel->v.nalloc = sel->child->child->v.nalloc;
1672 sel->child->child->flags &= ~SEL_ALLOCVAL;
1673 sel->child->child->v.nalloc = -1;
1676 /* Free the children. */
1677 release_subexpr_memory(sel);
1679 /* Free the expression data as it is no longer needed */
1680 sel->freeExpressionData();
1681 /* Make the item static */
1683 sel->type = SEL_CONST;
1684 sel->evaluate = NULL;
1685 sel->cdata->evaluate = NULL;
1686 /* Set the group value.
1687 * freeExpressionData() frees the cgrp group, so we can just override it.
1689 if (sel->v.type == GROUP_VALUE)
1691 gmx_ana_index_set(&sel->u.cgrp, sel->v.u.g->isize, sel->v.u.g->index, NULL, 0);
1696 * Evaluates a constant expression during analyze_static().
1698 * \param[in] data Evaluation data.
1699 * \param[in,out] sel Selection to process.
1700 * \param[in] g The evaluation group.
1701 * \returns 0 on success, a non-zero error code on error.
1704 process_const(gmx_sel_evaluate_t *data,
1705 const SelectionTreeElementPointer &sel,
1708 if (sel->v.type == GROUP_VALUE)
1710 if (sel->cdata->evaluate)
1712 sel->cdata->evaluate(data, sel, g);
1715 /* Other constant expressions do not need evaluation */
1719 * Sets the parameter value pointer for \ref SEL_SUBEXPRREF params.
1721 * \param[in,out] sel Selection to process.
1723 * Copies the value pointer of \p sel to \c sel->u.param if one is present
1724 * and should receive the value from the compiler
1725 * (most parameter values are handled during parsing).
1726 * If \p sel is not of type \ref SEL_SUBEXPRREF, or if \c sel->u.param is NULL,
1727 * the function does nothing.
1728 * Also, if the \c sel->u.param does not have \ref SPAR_VARNUM or
1729 * \ref SPAR_ATOMVAL, the function returns immediately.
1732 store_param_val(const SelectionTreeElementPointer &sel)
1734 /* Return immediately if there is no parameter. */
1735 if (sel->type != SEL_SUBEXPRREF || !sel->u.param)
1740 /* Or if the value does not need storing. */
1741 if (!(sel->u.param->flags & (SPAR_VARNUM | SPAR_ATOMVAL)))
1746 if (sel->v.type == INT_VALUE || sel->v.type == REAL_VALUE
1747 || sel->v.type == STR_VALUE)
1749 _gmx_selvalue_setstore(&sel->u.param->val, sel->v.u.ptr);
1754 * Handles the initialization of a selection method during analyze_static() pass.
1756 * \param[in,out] sel Selection element to process.
1757 * \param[in] top Topology structure.
1758 * \param[in] isize Size of the evaluation group for the element.
1759 * \returns 0 on success, a non-zero error code on return.
1761 * Calls sel_initfunc() (and possibly sel_outinitfunc()) to initialize the
1763 * If no \ref SPAR_ATOMVAL parameters are present, multiple initialization
1764 * is prevented by using \ref SEL_METHODINIT and \ref SEL_OUTINIT flags.
1767 init_method(const SelectionTreeElementPointer &sel, t_topology *top, int isize)
1769 /* Find out whether there are any atom-valued parameters */
1770 bool bAtomVal = false;
1771 SelectionTreeElementPointer child = sel->child;
1774 if (child->flags & SEL_ATOMVAL)
1778 child = child->next;
1781 /* Initialize the method */
1782 if (sel->u.expr.method->init
1783 && (bAtomVal || !(sel->flags & SEL_METHODINIT)))
1785 sel->flags |= SEL_METHODINIT;
1786 sel->u.expr.method->init(top, sel->u.expr.method->nparams,
1787 sel->u.expr.method->param, sel->u.expr.mdata);
1789 if (bAtomVal || !(sel->flags & SEL_OUTINIT))
1791 sel->flags |= SEL_OUTINIT;
1792 if (sel->u.expr.method->outinit)
1794 sel->u.expr.method->outinit(top, &sel->v, sel->u.expr.mdata);
1795 if (sel->v.type != POS_VALUE && sel->v.type != GROUP_VALUE)
1797 alloc_selection_data(sel, isize, true);
1802 alloc_selection_data(sel, isize, true);
1803 if ((sel->flags & SEL_DYNAMIC)
1804 && sel->v.type != GROUP_VALUE && sel->v.type != POS_VALUE)
1808 /* If the method is char-valued, pre-allocate the strings. */
1809 if (sel->u.expr.method->flags & SMETH_CHARVAL)
1813 /* A sanity check */
1814 if (sel->v.type != STR_VALUE)
1816 GMX_THROW(gmx::InternalError("Char-valued selection method in non-string element"));
1818 sel->flags |= SEL_ALLOCDATA;
1819 for (i = 0; i < isize; ++i)
1821 if (sel->v.u.s[i] == NULL)
1823 snew(sel->v.u.s[i], 2);
1828 /* Clear the values for dynamic output to avoid valgrind warnings. */
1829 if ((sel->flags & SEL_DYNAMIC) && sel->v.type == REAL_VALUE)
1833 for (i = 0; i < sel->v.nr; ++i)
1835 sel->v.u.r[i] = 0.0;
1842 * Evaluates the static part of a boolean expression.
1844 * \param[in] data Evaluation data.
1845 * \param[in,out] sel Boolean selection element whose children should be
1847 * \param[in] g The evaluation group.
1848 * \returns 0 on success, a non-zero error code on error.
1850 * reorder_item_static_children() should have been called.
1853 evaluate_boolean_static_part(gmx_sel_evaluate_t *data,
1854 const SelectionTreeElementPointer &sel,
1857 /* Find the last static subexpression */
1858 SelectionTreeElementPointer child = sel->child;
1859 while (child->next && (child->next->cdata->flags & SEL_CDATA_STATIC))
1861 child = child->next;
1863 if (!(child->cdata->flags & SEL_CDATA_STATIC))
1868 /* Evalute the static part if there is more than one expression */
1869 if (child != sel->child)
1871 SelectionTreeElementPointer next = child->next;
1872 child->next.reset();
1873 sel->cdata->evaluate(data, sel, g);
1874 /* Replace the subexpressions with the result */
1875 child.reset(new SelectionTreeElement(SEL_CONST));
1876 child->flags = SEL_FLAGSSET | SEL_SINGLEVAL | SEL_ALLOCVAL | SEL_ALLOCDATA;
1877 _gmx_selelem_set_vtype(child, GROUP_VALUE);
1878 child->evaluate = NULL;
1879 _gmx_selvalue_reserve(&child->v, 1);
1880 gmx_ana_index_copy(child->v.u.g, sel->v.u.g, true);
1881 init_item_compilerdata(child);
1882 init_item_minmax_groups(child);
1883 child->cdata->flags &= ~SEL_CDATA_STATICEVAL;
1884 child->cdata->flags |= sel->cdata->flags & SEL_CDATA_STATICEVAL;
1886 // Frees the old static subexpressions.
1889 else if (child->evaluate)
1891 child->evaluate(data, child, g);
1893 /* Set the evaluation function for the constant element.
1894 * We never need to evaluate the element again during compilation,
1895 * but we may need to evaluate the static part again if the
1896 * expression is not an OR with a static evaluation group.
1897 * If we reach here with a NOT expression, the NOT expression
1898 * is also static, and will be made a constant later, so don't waste
1899 * time copying the group. */
1900 child->evaluate = NULL;
1901 if (sel->u.boolt == BOOL_NOT
1902 || ((sel->cdata->flags & SEL_CDATA_STATICEVAL)
1903 && sel->u.boolt == BOOL_OR))
1905 child->cdata->evaluate = NULL;
1909 child->cdata->evaluate = &_gmx_sel_evaluate_static;
1910 /* The cgrp has only been allocated if it originated from an
1911 * external index group. In that case, we need special handling
1912 * to preserve the name of the group and to not leak memory.
1913 * If cgrp has been set in make_static(), it is not allocated,
1914 * and hence we can overwrite it safely. */
1915 if (child->u.cgrp.nalloc_index > 0)
1917 char *name = child->u.cgrp.name;
1918 gmx_ana_index_copy(&child->u.cgrp, child->v.u.g, false);
1919 gmx_ana_index_squeeze(&child->u.cgrp);
1920 child->u.cgrp.name = name;
1924 gmx_ana_index_copy(&child->u.cgrp, child->v.u.g, true);
1930 * Evaluates the minimum and maximum groups for a boolean expression.
1932 * \param[in] sel \ref SEL_BOOLEAN element currently being evaluated.
1933 * \param[in] g Group for which \p sel has been evaluated.
1934 * \param[out] gmin Largest subset of the possible values of \p sel.
1935 * \param[out] gmax Smallest superset of the possible values of \p sel.
1937 * This is a helper function for analyze_static() that is called for
1938 * dynamic \ref SEL_BOOLEAN elements after they have been evaluated.
1939 * It uses the minimum and maximum groups of the children to calculate
1940 * the minimum and maximum groups for \p sel, and also updates the static
1941 * part of \p sel (which is in the first child) if the children give
1944 * This function may allocate some extra memory for \p gmin and \p gmax,
1945 * but as these groups are freed at the end of analyze_static() (which is
1946 * reached shortly after this function returns), this should not be a major
1950 evaluate_boolean_minmax_grps(const SelectionTreeElementPointer &sel,
1952 gmx_ana_index_t *gmin, gmx_ana_index_t *gmax)
1954 SelectionTreeElementPointer child;
1956 switch (sel->u.boolt)
1959 gmx_ana_index_reserve(gmin, g->isize);
1960 gmx_ana_index_reserve(gmax, g->isize);
1961 gmx_ana_index_difference(gmax, g, sel->child->cdata->gmin);
1962 gmx_ana_index_difference(gmin, g, sel->child->cdata->gmax);
1966 gmx_ana_index_copy(gmin, sel->child->cdata->gmin, true);
1967 gmx_ana_index_copy(gmax, sel->child->cdata->gmax, true);
1968 child = sel->child->next;
1969 while (child && gmax->isize > 0)
1971 gmx_ana_index_intersection(gmin, gmin, child->cdata->gmin);
1972 gmx_ana_index_intersection(gmax, gmax, child->cdata->gmax);
1973 child = child->next;
1975 /* Update the static part if other expressions limit it */
1976 if ((sel->child->cdata->flags & SEL_CDATA_STATIC)
1977 && sel->child->v.u.g->isize > gmax->isize)
1979 gmx_ana_index_copy(sel->child->v.u.g, gmax, false);
1980 gmx_ana_index_squeeze(sel->child->v.u.g);
1981 if (sel->child->u.cgrp.isize > 0)
1983 gmx_ana_index_copy(&sel->child->u.cgrp, gmax, false);
1984 gmx_ana_index_squeeze(&sel->child->u.cgrp);
1990 /* We can assume here that the gmin of children do not overlap
1991 * because of the way _gmx_sel_evaluate_or() works. */
1992 gmx_ana_index_reserve(gmin, g->isize);
1993 gmx_ana_index_reserve(gmax, g->isize);
1994 gmx_ana_index_copy(gmin, sel->child->cdata->gmin, false);
1995 gmx_ana_index_copy(gmax, sel->child->cdata->gmax, false);
1996 child = sel->child->next;
1997 while (child && gmin->isize < g->isize)
1999 gmx_ana_index_merge(gmin, gmin, child->cdata->gmin);
2000 gmx_ana_index_union(gmax, gmax, child->cdata->gmax);
2001 child = child->next;
2003 /* Update the static part if other expressions have static parts
2004 * that are not included. */
2005 if ((sel->child->cdata->flags & SEL_CDATA_STATIC)
2006 && sel->child->v.u.g->isize < gmin->isize)
2008 GMX_RELEASE_ASSERT(sel->child->type == SEL_CONST,
2009 "The first child should have already been evaluated "
2010 "to a constant expression");
2011 gmx_ana_index_reserve(sel->child->v.u.g, gmin->isize);
2012 gmx_ana_index_copy(sel->child->v.u.g, gmin, false);
2013 if (sel->child->u.cgrp.nalloc_index > 0)
2015 /* Keep the name as in evaluate_boolean_static_part(). */
2016 char *name = sel->child->u.cgrp.name;
2017 gmx_ana_index_reserve(&sel->child->u.cgrp, gmin->isize);
2018 gmx_ana_index_copy(&sel->child->u.cgrp, gmin, false);
2019 sel->child->u.cgrp.name = name;
2023 GMX_RELEASE_ASSERT(sel->child->u.cgrp.index == sel->child->v.u.g->index,
2024 "If not allocated, the static group should equal the value");
2025 sel->child->u.cgrp.isize = sel->child->v.u.g->isize;
2030 case BOOL_XOR: /* Should not be reached */
2031 GMX_THROW(gmx::NotImplementedError("xor expressions not implemented"));
2037 * Evaluates the static parts of \p sel and analyzes the structure.
2039 * \param[in] data Evaluation data.
2040 * \param[in,out] sel Selection currently being evaluated.
2041 * \param[in] g Group for which \p sel should be evaluated.
2042 * \returns 0 on success, a non-zero error code on error.
2044 * This function is used as the replacement for the
2045 * gmx::SelectionTreeElement::evaluate function pointer.
2046 * It does the single most complex task in the compiler: after all elements
2047 * have been processed, the \p gmin and \p gmax fields of \p t_compiler_data
2048 * have been properly initialized, enough memory has been allocated for
2049 * storing the value of each expression, and the static parts of the
2050 * expressions have been evaluated.
2051 * The above is exactly true only for elements other than subexpressions:
2052 * another pass is required for subexpressions that are referred to more than
2053 * once and whose evaluation group is not known in advance.
2056 analyze_static(gmx_sel_evaluate_t *data,
2057 const SelectionTreeElementPointer &sel,
2062 if (sel->type != SEL_ROOT && g)
2064 alloc_selection_data(sel, g->isize, false);
2067 bDoMinMax = (sel->cdata->flags & SEL_CDATA_DOMINMAX);
2068 if (sel->type != SEL_SUBEXPR && bDoMinMax)
2070 gmx_ana_index_deinit(sel->cdata->gmin);
2071 gmx_ana_index_deinit(sel->cdata->gmax);
2074 /* TODO: This switch is awfully long... */
2078 process_const(data, sel, g);
2081 case SEL_EXPRESSION:
2083 GMX_ASSERT(g, "group cannot be null");
2084 _gmx_sel_evaluate_method_params(data, sel, g);
2085 init_method(sel, data->top, g->isize);
2086 if (!(sel->flags & SEL_DYNAMIC))
2088 sel->cdata->evaluate(data, sel, g);
2089 if (sel->cdata->flags & SEL_CDATA_STATIC)
2096 /* Modifiers need to be evaluated even though they process
2097 * positions to get the modified output groups from the
2098 * maximum possible selections. */
2099 if (sel->type == SEL_MODIFIER)
2101 sel->cdata->evaluate(data, sel, g);
2105 gmx_ana_index_copy(sel->cdata->gmax, g, true);
2111 if (!(sel->flags & SEL_DYNAMIC))
2113 sel->cdata->evaluate(data, sel, g);
2114 if (sel->cdata->flags & SEL_CDATA_STATIC)
2121 /* Evalute the static part if there is more than one expression */
2122 evaluate_boolean_static_part(data, sel, g);
2124 /* Evaluate the selection.
2125 * If the type is boolean, we must explicitly handle the
2126 * static part evaluated in evaluate_boolean_static_part()
2127 * here because g may be larger. */
2128 if (sel->u.boolt == BOOL_AND && sel->child->type == SEL_CONST)
2130 sel->cdata->evaluate(data, sel, sel->child->v.u.g);
2134 sel->cdata->evaluate(data, sel, g);
2137 /* Evaluate minimal and maximal selections */
2138 evaluate_boolean_minmax_grps(sel, g, sel->cdata->gmin,
2143 case SEL_ARITHMETIC:
2144 sel->cdata->evaluate(data, sel, g);
2145 if (!(sel->flags & SEL_DYNAMIC))
2147 if (sel->cdata->flags & SEL_CDATA_STATIC)
2154 gmx_ana_index_copy(sel->cdata->gmax, g, true);
2159 sel->cdata->evaluate(data, sel, g);
2163 if (sel->cdata->flags & (SEL_CDATA_SIMPLESUBEXPR | SEL_CDATA_FULLEVAL))
2165 sel->cdata->evaluate(data, sel, g);
2166 _gmx_selvalue_setstore(&sel->v, sel->child->v.u.ptr);
2168 else if (sel->u.cgrp.isize == 0)
2170 GMX_ASSERT(g, "group cannot be null");
2171 gmx_ana_index_reserve(&sel->u.cgrp, g->isize);
2172 sel->cdata->evaluate(data, sel, g);
2175 gmx_ana_index_copy(sel->cdata->gmin, sel->child->cdata->gmin, true);
2176 gmx_ana_index_copy(sel->cdata->gmax, sel->child->cdata->gmax, true);
2181 int isize = gmx_ana_index_difference_size(g, &sel->u.cgrp);
2184 isize += sel->u.cgrp.isize;
2185 gmx_ana_index_reserve(&sel->u.cgrp, isize);
2186 alloc_selection_data(sel, isize, false);
2188 sel->cdata->evaluate(data, sel, g);
2189 if (isize > 0 && bDoMinMax)
2191 gmx_ana_index_reserve(sel->cdata->gmin,
2192 sel->cdata->gmin->isize
2193 + sel->child->cdata->gmin->isize);
2194 gmx_ana_index_reserve(sel->cdata->gmax,
2195 sel->cdata->gmax->isize
2196 + sel->child->cdata->gmax->isize);
2197 gmx_ana_index_merge(sel->cdata->gmin, sel->cdata->gmin,
2198 sel->child->cdata->gmin);
2199 gmx_ana_index_merge(sel->cdata->gmax, sel->cdata->gmax,
2200 sel->child->cdata->gmax);
2205 case SEL_SUBEXPRREF:
2206 if (!g && !(sel->cdata->flags & SEL_CDATA_SIMPLESUBEXPR))
2208 /* The subexpression should have been evaluated if g is NULL
2209 * (i.e., this is a method parameter or a direct value of a
2211 alloc_selection_data(sel, sel->child->cdata->gmax->isize, true);
2213 sel->cdata->evaluate(data, sel, g);
2214 if ((sel->cdata->flags & SEL_CDATA_SIMPLESUBEXPR)
2215 && (sel->child->child->flags & SEL_ALLOCVAL))
2217 _gmx_selvalue_setstore(&sel->v, sel->child->child->v.u.ptr);
2219 /* Store the parameter value if required */
2220 store_param_val(sel);
2221 if (!(sel->flags & SEL_DYNAMIC))
2223 if (sel->cdata->flags & SEL_CDATA_STATIC)
2230 if ((sel->cdata->flags & SEL_CDATA_SIMPLESUBEXPR) || !g)
2232 gmx_ana_index_copy(sel->cdata->gmin, sel->child->cdata->gmin, true);
2233 gmx_ana_index_copy(sel->cdata->gmax, sel->child->cdata->gmax, true);
2237 gmx_ana_index_reserve(sel->cdata->gmin,
2238 min(g->isize, sel->child->cdata->gmin->isize));
2239 gmx_ana_index_reserve(sel->cdata->gmax,
2240 min(g->isize, sel->child->cdata->gmax->isize));
2241 gmx_ana_index_intersection(sel->cdata->gmin,
2242 sel->child->cdata->gmin, g);
2243 gmx_ana_index_intersection(sel->cdata->gmax,
2244 sel->child->cdata->gmax, g);
2249 case SEL_GROUPREF: /* Should not be reached */
2250 GMX_THROW(gmx::APIError("Unresolved group reference in compilation"));
2253 /* Update the minimal and maximal evaluation groups */
2256 gmx_ana_index_squeeze(sel->cdata->gmin);
2257 gmx_ana_index_squeeze(sel->cdata->gmax);
2258 sfree(sel->cdata->gmin->name);
2259 sfree(sel->cdata->gmax->name);
2260 sel->cdata->gmin->name = NULL;
2261 sel->cdata->gmax->name = NULL;
2264 /* Replace the result of the evaluation */
2265 /* This is not necessary for subexpressions or for boolean negations
2266 * because the evaluation function already has done it properly. */
2267 if (sel->v.type == GROUP_VALUE && (sel->flags & SEL_DYNAMIC)
2268 && sel->type != SEL_SUBEXPR
2269 && !(sel->type == SEL_BOOLEAN && sel->u.boolt == BOOL_NOT))
2271 if (sel->cdata->flags & SEL_CDATA_EVALMAX)
2273 gmx_ana_index_copy(sel->v.u.g, sel->cdata->gmax, false);
2277 gmx_ana_index_copy(sel->v.u.g, sel->cdata->gmin, false);
2283 /********************************************************************
2284 * EVALUATION GROUP INITIALIZATION
2285 ********************************************************************/
2288 * Initializes the evaluation group for a \ref SEL_ROOT element.
2290 * \param root Root element to initialize.
2291 * \param[in] gall Group of all atoms.
2293 * Checks whether it is necessary to evaluate anything through the root
2294 * element, and either clears the evaluation function or initializes the
2298 init_root_item(const SelectionTreeElementPointer &root,
2299 gmx_ana_index_t *gall)
2301 const SelectionTreeElementPointer &expr = root->child;
2302 /* Subexpressions with non-static evaluation group should not be
2303 * evaluated by the root, and neither should be single-reference
2304 * subexpressions that don't evaluate for all atoms. */
2305 if (expr->type == SEL_SUBEXPR
2306 && (!(root->child->cdata->flags & SEL_CDATA_STATICEVAL)
2307 || ((root->child->cdata->flags & SEL_CDATA_SIMPLESUBEXPR)
2308 && !(root->child->cdata->flags & SEL_CDATA_FULLEVAL))))
2310 root->evaluate = NULL;
2313 root->cdata->evaluate = NULL;
2317 /* Set the evaluation group */
2318 char *name = root->u.cgrp.name;
2321 /* Non-atom-valued non-group expressions don't care about the group, so
2322 * don't allocate any memory for it. */
2323 if ((expr->flags & SEL_VARNUMVAL)
2324 || ((expr->flags & SEL_SINGLEVAL) && expr->v.type != GROUP_VALUE))
2326 gmx_ana_index_set(&root->u.cgrp, -1, NULL, NULL, 0);
2328 else if (expr->cdata->gmax->isize == gall->isize)
2330 /* Save some memory by only referring to the global group. */
2331 gmx_ana_index_set(&root->u.cgrp, gall->isize, gall->index, NULL, 0);
2335 gmx_ana_index_copy(&root->u.cgrp, expr->cdata->gmax, true);
2337 /* For selections, store the maximum group for
2338 * gmx_ana_selcollection_evaluate_fin() as the value of the root
2339 * element (unused otherwise). */
2340 if (expr->type != SEL_SUBEXPR && expr->v.u.p->g)
2342 SelectionTreeElementPointer child = expr;
2344 /* TODO: This code is copied from parsetree.c; it would be better
2345 * to have this hardcoded only in one place. */
2346 while (child->type == SEL_MODIFIER)
2348 child = child->child;
2349 if (child->type == SEL_SUBEXPRREF)
2351 child = child->child->child;
2354 if (child->type == SEL_SUBEXPRREF)
2356 child = child->child->child;
2358 if (child->child->flags & SEL_DYNAMIC)
2360 _gmx_selelem_set_vtype(root, GROUP_VALUE);
2361 root->flags |= (SEL_ALLOCVAL | SEL_ALLOCDATA);
2362 _gmx_selvalue_reserve(&root->v, 1);
2363 gmx_ana_index_copy(root->v.u.g, expr->v.u.p->g, true);
2369 gmx_ana_index_clear(&root->u.cgrp);
2371 root->u.cgrp.name = name;
2375 /********************************************************************
2376 * FINAL SUBEXPRESSION OPTIMIZATION
2377 ********************************************************************/
2380 * Optimizes subexpression evaluation.
2382 * \param sel Root of the selection subtree to process.
2384 * Optimizes away some unnecessary evaluation of subexpressions that are only
2388 postprocess_item_subexpressions(const SelectionTreeElementPointer &sel)
2390 GMX_ASSERT(!(sel->child == NULL &&
2391 (sel->type == SEL_SUBEXPRREF || sel->type == SEL_SUBEXPR)),
2392 "Subexpression elements should always have a child element");
2394 /* Process children. */
2395 if (sel->type != SEL_SUBEXPRREF)
2397 SelectionTreeElementPointer child = sel->child;
2400 postprocess_item_subexpressions(child);
2401 child = child->next;
2405 /* Replace the evaluation function of statically evaluated subexpressions
2406 * for which the static group was not known in advance. */
2407 if (sel->type == SEL_SUBEXPR && sel->cdata->refcount > 1
2408 && (sel->cdata->flags & SEL_CDATA_STATICEVAL)
2409 && !(sel->cdata->flags & SEL_CDATA_FULLEVAL))
2413 /* We need to free memory allocated for the group, because it is no
2414 * longer needed (and would be lost on next call to the evaluation
2415 * function). But we need to preserve the name. */
2416 name = sel->u.cgrp.name;
2417 gmx_ana_index_deinit(&sel->u.cgrp);
2418 sel->u.cgrp.name = name;
2420 sel->evaluate = &_gmx_sel_evaluate_subexpr_staticeval;
2421 sel->cdata->evaluate = sel->evaluate;
2423 sel->child->freeValues();
2424 sel->child->mempool = NULL;
2425 _gmx_selvalue_setstore(&sel->child->v, sel->v.u.ptr);
2426 sel->child->flags &= ~(SEL_ALLOCVAL | SEL_ALLOCDATA);
2429 /* Adjust memory allocation flags for subexpressions that are used only
2430 * once. This is not strictly necessary, but we do it to have the memory
2431 * managed consistently for all types of subexpressions. */
2432 if (sel->type == SEL_SUBEXPRREF
2433 && (sel->cdata->flags & SEL_CDATA_SIMPLESUBEXPR))
2435 if (sel->child->child->flags & SEL_ALLOCVAL)
2437 sel->flags |= SEL_ALLOCVAL;
2438 sel->flags |= (sel->child->child->flags & SEL_ALLOCDATA);
2439 sel->v.nalloc = sel->child->child->v.nalloc;
2440 sel->child->child->flags &= ~(SEL_ALLOCVAL | SEL_ALLOCDATA);
2441 sel->child->child->v.nalloc = -1;
2445 /* Do the same for subexpressions that are evaluated at once for all atoms. */
2446 if (sel->type == SEL_SUBEXPR
2447 && !(sel->cdata->flags & SEL_CDATA_SIMPLESUBEXPR)
2448 && (sel->cdata->flags & SEL_CDATA_FULLEVAL))
2450 sel->flags |= SEL_ALLOCVAL;
2451 sel->flags |= (sel->child->flags & SEL_ALLOCDATA);
2452 sel->v.nalloc = sel->child->v.nalloc;
2453 sel->child->flags &= ~(SEL_ALLOCVAL | SEL_ALLOCDATA);
2454 sel->child->v.nalloc = -1;
2459 /********************************************************************
2460 * COM CALCULATION INITIALIZATION
2461 ********************************************************************/
2464 * Initializes COM/COG calculation for method expressions that require it.
2466 * \param sel Selection subtree to process.
2467 * \param[in,out] pcc Position calculation collection to use.
2468 * \param[in] type Default position calculation type.
2469 * \param[in] flags Flags for default position calculation.
2471 * Searches recursively through the selection tree for dynamic
2472 * \ref SEL_EXPRESSION elements that define the \c gmx_ana_selmethod_t::pupdate
2474 * For each such element found, position calculation is initialized
2475 * for the maximal evaluation group.
2476 * The type of the calculation is determined by \p type and \p flags.
2477 * No calculation is initialized if \p type equals \ref POS_ATOM and
2478 * the method also defines the \c gmx_ana_selmethod_t::update method.
2481 init_item_comg(const SelectionTreeElementPointer &sel,
2482 gmx::PositionCalculationCollection *pcc,
2483 e_poscalc_t type, int flags)
2485 /* Initialize COM calculation for dynamic selections now that we know the maximal evaluation group */
2486 if (sel->type == SEL_EXPRESSION && sel->u.expr.method
2487 && sel->u.expr.method->pupdate)
2489 if (!sel->u.expr.method->update || type != POS_ATOM)
2491 /* Create a default calculation if one does not yet exist */
2493 if (!(sel->cdata->flags & SEL_CDATA_STATICEVAL))
2495 cflags |= POS_DYNAMIC;
2497 if (!sel->u.expr.pc)
2500 sel->u.expr.pc = pcc->createCalculation(type, cflags);
2504 gmx_ana_poscalc_set_flags(sel->u.expr.pc, cflags);
2506 gmx_ana_poscalc_set_maxindex(sel->u.expr.pc, sel->cdata->gmax);
2507 snew(sel->u.expr.pos, 1);
2508 gmx_ana_poscalc_init_pos(sel->u.expr.pc, sel->u.expr.pos);
2512 /* Call recursively for all children unless the children have already been processed */
2513 if (sel->type != SEL_SUBEXPRREF)
2515 SelectionTreeElementPointer child = sel->child;
2518 init_item_comg(child, pcc, type, flags);
2519 child = child->next;
2525 /********************************************************************
2526 * COMPILER DATA FREEING
2527 ********************************************************************/
2530 * Frees the allocated compiler data recursively.
2532 * \param sel Root of the selection subtree to process.
2534 * Frees the data allocated for the compilation process.
2537 free_item_compilerdata(const SelectionTreeElementPointer &sel)
2539 /* Free compilation data */
2540 sel->freeCompilerData();
2542 /* Call recursively for all children unless the children have already been processed */
2543 if (sel->type != SEL_SUBEXPRREF)
2545 SelectionTreeElementPointer child = sel->child;
2548 free_item_compilerdata(child);
2549 child = child->next;
2555 /********************************************************************
2556 * MAIN COMPILATION FUNCTION
2557 ********************************************************************/
2562 SelectionCompiler::SelectionCompiler()
2567 * \param[in,out] coll Selection collection to be compiled.
2568 * \returns 0 on successful compilation, a non-zero error code on error.
2570 * Before compilation, the selection collection should have been initialized
2571 * with gmx_ana_selcollection_parse_*().
2572 * The compiled selection collection can be passed to
2573 * gmx_ana_selcollection_evaluate() to evaluate the selection for a frame.
2574 * If an error occurs, \p sc is cleared.
2576 * The covered fraction information in \p sc is initialized to
2580 SelectionCompiler::compile(SelectionCollection *coll)
2582 gmx_ana_selcollection_t *sc = &coll->impl_->sc_;
2583 gmx_sel_evaluate_t evaldata;
2584 SelectionTreeElementPointer item;
2588 bool bDebug = (coll->impl_->debugLevel_ >= 2
2589 && coll->impl_->debugLevel_ != 3);
2591 /* FIXME: Clean up the collection on exceptions */
2593 sc->mempool = _gmx_sel_mempool_create();
2594 _gmx_sel_evaluate_init(&evaldata, sc->mempool, &sc->gall,
2595 sc->top, NULL, NULL);
2597 /* Clear the symbol table because it is not possible to parse anything
2598 * after compilation, and variable references in the symbol table can
2599 * also mess up the compilation and/or become invalid.
2601 coll->impl_->clearSymbolTable();
2603 /* Loop through selections and initialize position keyword defaults if no
2604 * other value has been provided.
2606 for (i = 0; i < sc->sel.size(); ++i)
2608 gmx::internal::SelectionData &sel = *sc->sel[i];
2609 init_pos_keyword_defaults(&sel.rootElement(),
2610 coll->impl_->spost_.c_str(),
2611 coll->impl_->rpost_.c_str(),
2615 /* Remove any unused variables. */
2616 sc->root = remove_unused_subexpressions(sc->root);
2617 /* Extract subexpressions into separate roots */
2618 sc->root = extract_subexpressions(sc->root);
2620 /* Initialize the evaluation callbacks and process the tree structure
2621 * to conform to the expectations of the callback functions. */
2622 /* Also, initialize and allocate the compiler data structure */
2626 /* Process boolean and arithmetic expressions. */
2627 optimize_boolean_expressions(item);
2628 reorder_boolean_static_children(item);
2629 optimize_arithmetic_expressions(item);
2630 /* Initialize the compiler data */
2631 init_item_compilerdata(item);
2632 init_item_staticeval(item);
2633 init_item_subexpr_refcount(item);
2636 /* Initialize subexpression flags.
2637 * Requires compiler flags for the full tree. */
2641 init_item_subexpr_flags(item);
2644 /* Initialize evaluation.
2645 * Requires subexpression flags. */
2649 init_item_evalfunc(item);
2650 setup_memory_pooling(item, sc->mempool);
2651 init_item_evaloutput(item);
2654 /* Initialize minimum/maximum index groups.
2655 * Requires evaluation output for the full tree. */
2659 init_item_minmax_groups(item);
2662 /* Initialize the evaluation index groups */
2663 initialize_evalgrps(sc);
2667 fprintf(stderr, "\nTree after initial compiler processing:\n");
2668 coll->printTree(stderr, false);
2671 /* Evaluate all static parts of the selection and analyze the tree
2672 * to allocate enough memory to store the value of each dynamic subtree. */
2676 if (item->child->cdata->flags & SEL_CDATA_COMMONSUBEXPR)
2678 mark_subexpr_dynamic(item->child, true);
2680 set_evaluation_function(item, &analyze_static);
2681 item->evaluate(&evaldata, item, NULL);
2685 /* At this point, static subexpressions no longer have references to them,
2686 * so they can be removed. */
2687 sc->root = remove_unused_subexpressions(sc->root);
2688 // Update the reference counts for consistency (only used for the
2689 // debugging output below).
2693 init_item_subexpr_refcount(item);
2699 fprintf(stderr, "\nTree after first analysis pass:\n");
2700 coll->printTree(stderr, false);
2703 /* Do a second pass to evaluate static parts of common subexpressions */
2707 if (item->child->cdata->flags & SEL_CDATA_COMMONSUBEXPR)
2709 bool bMinMax = item->child->cdata->flags & SEL_CDATA_DOMINMAX;
2711 mark_subexpr_dynamic(item->child, false);
2712 item->child->u.cgrp.isize = 0;
2713 /* We won't clear item->child->v.u.g here, because it may
2714 * be static, and hence actually point to item->child->cdata->gmax,
2715 * which is used below. We could also check whether this is the
2716 * case and only clear the group otherwise, but because the value
2717 * is actually overwritten immediately in the evaluate call, we
2718 * won't, because similar problems may arise if gmax handling ever
2719 * changes and the check were not updated.
2720 * For the same reason, we clear the min/max flag so that the
2721 * evaluation group doesn't get messed up. */
2722 set_evaluation_function(item, &analyze_static);
2723 item->child->cdata->flags &= ~SEL_CDATA_DOMINMAX;
2724 item->evaluate(&evaldata, item->child, item->child->cdata->gmax);
2727 item->child->cdata->flags |= SEL_CDATA_DOMINMAX;
2733 /* We need a yet another pass of subexpression removal to remove static
2734 * subexpressions referred to by common dynamic subexpressions. */
2735 sc->root = remove_unused_subexpressions(sc->root);
2736 // Update the reference counts, used by postprocess_item_subexpressions().
2740 init_item_subexpr_refcount(item);
2746 fprintf(stderr, "\nTree after second analysis pass:\n");
2747 coll->printTree(stderr, false);
2750 /* Initialize evaluation groups, position calculations for methods, perform
2751 * some final optimization, and free the memory allocated for the
2753 /* By default, use whole residues/molecules. */
2754 flags = POS_COMPLWHOLE;
2755 PositionCalculationCollection::typeFromEnum(coll->impl_->rpost_.c_str(),
2760 init_root_item(item, &sc->gall);
2761 postprocess_item_subexpressions(item);
2762 init_item_comg(item, &sc->pcc, post, flags);
2763 free_item_compilerdata(item);
2767 /* Allocate memory for the evaluation memory pool. */
2768 _gmx_sel_mempool_reserve(sc->mempool, 0);
2770 /* Finish up by calculating total masses and charges. */
2771 for (i = 0; i < sc->sel.size(); ++i)
2773 sc->sel[i]->initializeMassesAndCharges(sc->top);