Sort all includes in src/gromacs
[alexxy/gromacs.git] / src / gromacs / selection / selectioncollection.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2010,2011,2012,2013,2014, by the GROMACS development team, led by
5  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
6  * and including many others, as listed in the AUTHORS file in the
7  * top-level source directory and at http://www.gromacs.org.
8  *
9  * GROMACS is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public License
11  * as published by the Free Software Foundation; either version 2.1
12  * of the License, or (at your option) any later version.
13  *
14  * GROMACS is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with GROMACS; if not, see
21  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
22  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
23  *
24  * If you want to redistribute modifications to GROMACS, please
25  * consider that scientific software is very special. Version
26  * control is crucial - bugs must be traceable. We will be happy to
27  * consider code for inclusion in the official distribution, but
28  * derived work must not be called official GROMACS. Details are found
29  * in the README & COPYING files - if they are missing, get the
30  * official version at http://www.gromacs.org.
31  *
32  * To help us fund GROMACS development, we humbly ask that you cite
33  * the research papers on the package. Check out http://www.gromacs.org.
34  */
35 /*! \internal \file
36  * \brief
37  * Implements gmx::SelectionCollection.
38  *
39  * \author Teemu Murtola <teemu.murtola@gmail.com>
40  * \ingroup module_selection
41  */
42 #include "gmxpre.h"
43
44 #include "selectioncollection.h"
45
46 #include <cctype>
47 #include <cstdio>
48
49 #include <string>
50 #include <vector>
51
52 #include <boost/shared_ptr.hpp>
53
54 #include "gromacs/fileio/trx.h"
55 #include "gromacs/legacyheaders/oenv.h"
56 #include "gromacs/onlinehelp/helpmanager.h"
57 #include "gromacs/onlinehelp/helpwritercontext.h"
58 #include "gromacs/options/basicoptions.h"
59 #include "gromacs/options/options.h"
60 #include "gromacs/selection/selection.h"
61 #include "gromacs/selection/selhelp.h"
62 #include "gromacs/topology/topology.h"
63 #include "gromacs/utility/exceptions.h"
64 #include "gromacs/utility/file.h"
65 #include "gromacs/utility/gmxassert.h"
66 #include "gromacs/utility/messagestringcollector.h"
67 #include "gromacs/utility/smalloc.h"
68 #include "gromacs/utility/stringutil.h"
69
70 #include "compiler.h"
71 #include "mempool.h"
72 #include "parser.h"
73 #include "poscalc.h"
74 #include "scanner.h"
75 #include "selectioncollection-impl.h"
76 #include "selelem.h"
77 #include "selmethod.h"
78 #include "symrec.h"
79
80 namespace gmx
81 {
82
83 /********************************************************************
84  * SelectionCollection::Impl
85  */
86
87 SelectionCollection::Impl::Impl()
88     : maxAtomIndex_(0), debugLevel_(0), bExternalGroupsSet_(false), grps_(NULL)
89 {
90     sc_.nvars     = 0;
91     sc_.varstrs   = NULL;
92     sc_.top       = NULL;
93     gmx_ana_index_clear(&sc_.gall);
94     sc_.mempool   = NULL;
95     sc_.symtab.reset(new SelectionParserSymbolTable);
96     gmx_ana_selmethod_register_defaults(sc_.symtab.get());
97 }
98
99
100 SelectionCollection::Impl::~Impl()
101 {
102     clearSymbolTable();
103     // The tree must be freed before the SelectionData objects, since the
104     // tree may hold references to the position data in SelectionData.
105     sc_.root.reset();
106     sc_.sel.clear();
107     for (int i = 0; i < sc_.nvars; ++i)
108     {
109         sfree(sc_.varstrs[i]);
110     }
111     sfree(sc_.varstrs);
112     gmx_ana_index_deinit(&sc_.gall);
113     if (sc_.mempool)
114     {
115         _gmx_sel_mempool_destroy(sc_.mempool);
116     }
117 }
118
119
120 void
121 SelectionCollection::Impl::clearSymbolTable()
122 {
123     sc_.symtab.reset();
124 }
125
126
127 namespace
128 {
129
130 /*! \brief
131  * Reads a single selection line from stdin.
132  *
133  * \param[in]  infile        File to read from (typically File::standardInput()).
134  * \param[in]  bInteractive  Whether to print interactive prompts.
135  * \param[out] line          The read line in stored here.
136  * \returns true if something was read, false if at end of input.
137  *
138  * Handles line continuation, reading also the continuing line(s) in one call.
139  */
140 bool promptLine(File *infile, bool bInteractive, std::string *line)
141 {
142     if (bInteractive)
143     {
144         fprintf(stderr, "> ");
145     }
146     if (!infile->readLineWithTrailingSpace(line))
147     {
148         return false;
149     }
150     while (endsWith(*line, "\\\n"))
151     {
152         line->resize(line->length() - 2);
153         if (bInteractive)
154         {
155             fprintf(stderr, "... ");
156         }
157         std::string buffer;
158         // Return value ignored, buffer remains empty and works correctly
159         // if there is nothing to read.
160         infile->readLineWithTrailingSpace(&buffer);
161         line->append(buffer);
162     }
163     if (endsWith(*line, "\n"))
164     {
165         line->resize(line->length() - 1);
166     }
167     else if (bInteractive)
168     {
169         fprintf(stderr, "\n");
170     }
171     return true;
172 }
173
174 /*! \brief
175  * Helper function for tokenizing the input and pushing them to the parser.
176  *
177  * \param     scanner       Tokenizer data structure.
178  * \param     parserState   Parser data structure.
179  * \param[in] bInteractive  Whether to operate in interactive mode.
180  *
181  * Repeatedly reads tokens using \p scanner and pushes them to the parser with
182  * \p parserState until there is no more input, or until enough input is given
183  * (only in interactive mode).
184  */
185 int runParserLoop(yyscan_t scanner, _gmx_sel_yypstate *parserState,
186                   bool bInteractive)
187 {
188     int status    = YYPUSH_MORE;
189     int prevToken = 0;
190     do
191     {
192         YYSTYPE value;
193         int     token = _gmx_sel_yylex(&value, scanner);
194         if (bInteractive)
195         {
196             if (token == 0)
197             {
198                 break;
199             }
200             // Empty commands cause the interactive parser to print out
201             // status information. This avoids producing those unnecessarily,
202             // e.g., from "resname RA;;".
203             if (prevToken == CMD_SEP && token == CMD_SEP)
204             {
205                 continue;
206             }
207             prevToken = token;
208         }
209         status = _gmx_sel_yypush_parse(parserState, token, &value, scanner);
210     }
211     while (status == YYPUSH_MORE);
212     _gmx_sel_lexer_rethrow_exception_if_occurred(scanner);
213     return status;
214 }
215
216 /*! \brief
217  * Print current status in response to empty line in interactive input.
218  *
219  * \param[in] sc             Selection collection data structure.
220  * \param[in] grps           Available index groups.
221  * \param[in] firstSelection Index of first selection from this interactive
222  *     session.
223  * \param[in] maxCount       Maximum number of selections.
224  * \param[in] context        Context to print for what the selections are for.
225  * \param[in] bFirst         Whether this is the header that is printed before
226  *     any user input.
227  *
228  * Prints the available index groups and currently provided selections.
229  */
230 void printCurrentStatus(gmx_ana_selcollection_t *sc, gmx_ana_indexgrps_t *grps,
231                         size_t firstSelection, int maxCount,
232                         const std::string &context, bool bFirst)
233 {
234     if (grps != NULL)
235     {
236         std::fprintf(stderr, "Available static index groups:\n");
237         gmx_ana_indexgrps_print(stderr, grps, 0);
238     }
239     std::fprintf(stderr, "Specify ");
240     if (maxCount < 0)
241     {
242         std::fprintf(stderr, "any number of selections");
243     }
244     else if (maxCount == 1)
245     {
246         std::fprintf(stderr, "a selection");
247     }
248     else
249     {
250         std::fprintf(stderr, "%d selections", maxCount);
251     }
252     std::fprintf(stderr, "%s%s:\n",
253                  context.empty() ? "" : " ", context.c_str());
254     std::fprintf(stderr,
255                  "(one per line, <enter> for status/groups, 'help' for help%s)\n",
256                  maxCount < 0 ? ", Ctrl-D to end" : "");
257     if (!bFirst && (sc->nvars > 0 || sc->sel.size() > firstSelection))
258     {
259         std::fprintf(stderr, "Currently provided selections:\n");
260         for (int i = 0; i < sc->nvars; ++i)
261         {
262             std::fprintf(stderr, "     %s\n", sc->varstrs[i]);
263         }
264         for (size_t i = firstSelection; i < sc->sel.size(); ++i)
265         {
266             std::fprintf(stderr, " %2d. %s\n",
267                          static_cast<int>(i - firstSelection + 1),
268                          sc->sel[i]->selectionText());
269         }
270         if (maxCount > 0)
271         {
272             const int remaining
273                 = maxCount - static_cast<int>(sc->sel.size() - firstSelection);
274             std::fprintf(stderr, "(%d more selection%s required)\n",
275                          remaining, remaining > 1 ? "s" : "");
276         }
277     }
278 }
279
280 /*! \brief
281  * Prints selection help in interactive selection input.
282  *
283  * \param[in] sc    Selection collection data structure.
284  * \param[in] line  Line of user input requesting help (starting with `help`).
285  *
286  * Initializes the selection help if not yet initialized, and finds the help
287  * topic based on words on the input line.
288  */
289 void printHelp(gmx_ana_selcollection_t *sc, const std::string &line)
290 {
291     if (sc->rootHelp.get() == NULL)
292     {
293         sc->rootHelp = createSelectionHelpTopic();
294     }
295     HelpWriterContext context(&File::standardError(),
296                               eHelpOutputFormat_Console);
297     HelpManager       manager(*sc->rootHelp, context);
298     try
299     {
300         std::vector<std::string>                 topic = splitString(line);
301         std::vector<std::string>::const_iterator value;
302         // First item in the list is the 'help' token.
303         for (value = topic.begin() + 1; value != topic.end(); ++value)
304         {
305             manager.enterTopic(*value);
306         }
307     }
308     catch (const InvalidInputError &ex)
309     {
310         fprintf(stderr, "%s\n", ex.what());
311         return;
312     }
313     manager.writeCurrentTopic();
314 }
315
316 /*! \brief
317  * Helper function that runs the parser once the tokenizer has been
318  * initialized.
319  *
320  * \param[in,out] scanner Scanner data structure.
321  * \param[in]     bStdIn  Whether to use a line-based reading
322  *      algorithm designed for interactive input.
323  * \param[in]     maxnr   Maximum number of selections to parse
324  *      (if -1, parse as many as provided by the user).
325  * \param[in]     context Context to print for what the selections are for.
326  * \returns       Vector of parsed selections.
327  * \throws        std::bad_alloc if out of memory.
328  * \throws        InvalidInputError if there is a parsing error.
329  *
330  * Used internally to implement parseFromStdin(), parseFromFile() and
331  * parseFromString().
332  */
333 SelectionList runParser(yyscan_t scanner, bool bStdIn, int maxnr,
334                         const std::string &context)
335 {
336     boost::shared_ptr<void>  scannerGuard(scanner, &_gmx_sel_free_lexer);
337     gmx_ana_selcollection_t *sc   = _gmx_sel_lexer_selcollection(scanner);
338     gmx_ana_indexgrps_t     *grps = _gmx_sel_lexer_indexgrps(scanner);
339
340     MessageStringCollector   errors;
341     _gmx_sel_set_lexer_error_reporter(scanner, &errors);
342
343     size_t oldCount = sc->sel.size();
344     bool   bOk      = false;
345     {
346         boost::shared_ptr<_gmx_sel_yypstate> parserState(
347                 _gmx_sel_yypstate_new(), &_gmx_sel_yypstate_delete);
348         if (bStdIn)
349         {
350             File       &stdinFile(File::standardInput());
351             const bool  bInteractive = _gmx_sel_is_lexer_interactive(scanner);
352             if (bInteractive)
353             {
354                 printCurrentStatus(sc, grps, oldCount, maxnr, context, true);
355             }
356             std::string line;
357             int         status;
358             while (promptLine(&stdinFile, bInteractive, &line))
359             {
360                 if (bInteractive)
361                 {
362                     line = stripString(line);
363                     if (line.empty())
364                     {
365                         printCurrentStatus(sc, grps, oldCount, maxnr, context, false);
366                         continue;
367                     }
368                     if (startsWith(line, "help")
369                         && (line[4] == 0 || std::isspace(line[4])))
370                     {
371                         printHelp(sc, line);
372                         continue;
373                     }
374                 }
375                 line.append("\n");
376                 _gmx_sel_set_lex_input_str(scanner, line.c_str());
377                 status = runParserLoop(scanner, parserState.get(), true);
378                 if (status != YYPUSH_MORE)
379                 {
380                     // TODO: Check if there is more input, and issue an
381                     // error/warning if some input was ignored.
382                     goto early_termination;
383                 }
384                 if (!errors.isEmpty() && bInteractive)
385                 {
386                     fprintf(stderr, "%s", errors.toString().c_str());
387                     errors.clear();
388                 }
389             }
390             status = _gmx_sel_yypush_parse(parserState.get(), 0, NULL,
391                                            scanner);
392             _gmx_sel_lexer_rethrow_exception_if_occurred(scanner);
393 early_termination:
394             bOk = (status == 0);
395         }
396         else
397         {
398             int status = runParserLoop(scanner, parserState.get(), false);
399             bOk = (status == 0);
400         }
401     }
402     scannerGuard.reset();
403     int nr = sc->sel.size() - oldCount;
404     if (maxnr > 0 && nr != maxnr)
405     {
406         bOk = false;
407         errors.append("Too few selections provided");
408     }
409
410     // TODO: Remove added selections from the collection if parsing failed?
411     if (!bOk || !errors.isEmpty())
412     {
413         GMX_ASSERT(!bOk && !errors.isEmpty(), "Inconsistent error reporting");
414         GMX_THROW(InvalidInputError(errors.toString()));
415     }
416
417     SelectionList                     result;
418     SelectionDataList::const_iterator i;
419     result.reserve(nr);
420     for (i = sc->sel.begin() + oldCount; i != sc->sel.end(); ++i)
421     {
422         result.push_back(Selection(i->get()));
423     }
424     return result;
425 }
426
427 /*! \brief
428  * Checks that index groups have valid atom indices.
429  *
430  * \param[in]    root    Root of selection tree to process.
431  * \param[in]    natoms  Maximum number of atoms that the selections are set
432  *     to evaluate.
433  * \param        errors  Object for reporting any error messages.
434  * \throws std::bad_alloc if out of memory.
435  *
436  * Recursively checks the selection tree for index groups.
437  * Each found group is checked that it only contains atom indices that match
438  * the topology/maximum number of atoms set for the selection collection.
439  * Any issues are reported to \p errors.
440  */
441 void checkExternalGroups(const SelectionTreeElementPointer &root,
442                          int                                natoms,
443                          ExceptionInitializer              *errors)
444 {
445     if (root->type == SEL_CONST && root->v.type == GROUP_VALUE)
446     {
447         try
448         {
449             root->checkIndexGroup(natoms);
450         }
451         catch (const UserInputError &)
452         {
453             errors->addCurrentExceptionAsNested();
454         }
455     }
456
457     SelectionTreeElementPointer child = root->child;
458     while (child)
459     {
460         checkExternalGroups(child, natoms, errors);
461         child = child->next;
462     }
463 }
464
465 }   // namespace
466
467
468 void SelectionCollection::Impl::resolveExternalGroups(
469         const SelectionTreeElementPointer &root,
470         ExceptionInitializer              *errors)
471 {
472
473     if (root->type == SEL_GROUPREF)
474     {
475         try
476         {
477             root->resolveIndexGroupReference(grps_, sc_.gall.isize);
478         }
479         catch (const UserInputError &)
480         {
481             errors->addCurrentExceptionAsNested();
482         }
483     }
484
485     SelectionTreeElementPointer child = root->child;
486     while (child)
487     {
488         resolveExternalGroups(child, errors);
489         root->flags |= (child->flags & SEL_UNSORTED);
490         child        = child->next;
491     }
492 }
493
494
495 /********************************************************************
496  * SelectionCollection
497  */
498
499 SelectionCollection::SelectionCollection()
500     : impl_(new Impl)
501 {
502 }
503
504
505 SelectionCollection::~SelectionCollection()
506 {
507 }
508
509
510 void
511 SelectionCollection::initOptions(Options *options)
512 {
513     const char * const debug_levels[]
514         = { "no", "basic", "compile", "eval", "full" };
515
516     bool bAllowNonAtomOutput = false;
517     SelectionDataList::const_iterator iter;
518     for (iter = impl_->sc_.sel.begin(); iter != impl_->sc_.sel.end(); ++iter)
519     {
520         const internal::SelectionData &sel = **iter;
521         if (!sel.hasFlag(efSelection_OnlyAtoms))
522         {
523             bAllowNonAtomOutput = true;
524         }
525     }
526
527     const char *const *postypes = PositionCalculationCollection::typeEnumValues;
528     options->addOption(StringOption("selrpos")
529                            .enumValueFromNullTerminatedArray(postypes)
530                            .store(&impl_->rpost_).defaultValue(postypes[0])
531                            .description("Selection reference positions"));
532     if (bAllowNonAtomOutput)
533     {
534         options->addOption(StringOption("seltype")
535                                .enumValueFromNullTerminatedArray(postypes)
536                                .store(&impl_->spost_).defaultValue(postypes[0])
537                                .description("Default selection output positions"));
538     }
539     else
540     {
541         impl_->spost_ = postypes[0];
542     }
543     GMX_RELEASE_ASSERT(impl_->debugLevel_ >= 0 && impl_->debugLevel_ <= 4,
544                        "Debug level out of range");
545     options->addOption(StringOption("seldebug").hidden(impl_->debugLevel_ == 0)
546                            .enumValue(debug_levels)
547                            .defaultValue(debug_levels[impl_->debugLevel_])
548                            .storeEnumIndex(&impl_->debugLevel_)
549                            .description("Print out selection trees for debugging"));
550 }
551
552
553 void
554 SelectionCollection::setReferencePosType(const char *type)
555 {
556     GMX_RELEASE_ASSERT(type != NULL, "Cannot assign NULL position type");
557     // Check that the type is valid, throw if it is not.
558     e_poscalc_t  dummytype;
559     int          dummyflags;
560     PositionCalculationCollection::typeFromEnum(type, &dummytype, &dummyflags);
561     impl_->rpost_ = type;
562 }
563
564
565 void
566 SelectionCollection::setOutputPosType(const char *type)
567 {
568     GMX_RELEASE_ASSERT(type != NULL, "Cannot assign NULL position type");
569     // Check that the type is valid, throw if it is not.
570     e_poscalc_t  dummytype;
571     int          dummyflags;
572     PositionCalculationCollection::typeFromEnum(type, &dummytype, &dummyflags);
573     impl_->spost_ = type;
574 }
575
576
577 void
578 SelectionCollection::setDebugLevel(int debugLevel)
579 {
580     impl_->debugLevel_ = debugLevel;
581 }
582
583
584 void
585 SelectionCollection::setTopology(t_topology *top, int natoms)
586 {
587     GMX_RELEASE_ASSERT(natoms > 0 || top != NULL,
588                        "The number of atoms must be given if there is no topology");
589     // Get the number of atoms from the topology if it is not given.
590     if (natoms <= 0)
591     {
592         natoms = top->atoms.nr;
593     }
594     if (impl_->bExternalGroupsSet_)
595     {
596         ExceptionInitializer        errors("Invalid index group references encountered");
597         SelectionTreeElementPointer root = impl_->sc_.root;
598         while (root)
599         {
600             checkExternalGroups(root, natoms, &errors);
601             root = root->next;
602         }
603         if (errors.hasNestedExceptions())
604         {
605             GMX_THROW(InconsistentInputError(errors));
606         }
607     }
608     gmx_ana_selcollection_t *sc = &impl_->sc_;
609     // Do this first, as it allocates memory, while the others don't throw.
610     gmx_ana_index_init_simple(&sc->gall, natoms);
611     sc->pcc.setTopology(top);
612     sc->top = top;
613 }
614
615
616 void
617 SelectionCollection::setIndexGroups(gmx_ana_indexgrps_t *grps)
618 {
619     GMX_RELEASE_ASSERT(grps == NULL || !impl_->bExternalGroupsSet_,
620                        "Can only set external groups once or clear them afterwards");
621     impl_->grps_               = grps;
622     impl_->bExternalGroupsSet_ = true;
623
624     ExceptionInitializer        errors("Invalid index group reference(s)");
625     SelectionTreeElementPointer root = impl_->sc_.root;
626     while (root)
627     {
628         impl_->resolveExternalGroups(root, &errors);
629         root->checkUnsortedAtoms(true, &errors);
630         root = root->next;
631     }
632     if (errors.hasNestedExceptions())
633     {
634         GMX_THROW(InconsistentInputError(errors));
635     }
636     for (size_t i = 0; i < impl_->sc_.sel.size(); ++i)
637     {
638         impl_->sc_.sel[i]->refreshName();
639     }
640 }
641
642
643 bool
644 SelectionCollection::requiresTopology() const
645 {
646     e_poscalc_t  type;
647     int          flags;
648
649     if (!impl_->rpost_.empty())
650     {
651         flags = 0;
652         // Should not throw, because has been checked earlier.
653         PositionCalculationCollection::typeFromEnum(impl_->rpost_.c_str(),
654                                                     &type, &flags);
655         if (type != POS_ATOM)
656         {
657             return true;
658         }
659     }
660     if (!impl_->spost_.empty())
661     {
662         flags = 0;
663         // Should not throw, because has been checked earlier.
664         PositionCalculationCollection::typeFromEnum(impl_->spost_.c_str(),
665                                                     &type, &flags);
666         if (type != POS_ATOM)
667         {
668             return true;
669         }
670     }
671
672     SelectionTreeElementPointer sel = impl_->sc_.root;
673     while (sel)
674     {
675         if (_gmx_selelem_requires_top(*sel))
676         {
677             return true;
678         }
679         sel = sel->next;
680     }
681     return false;
682 }
683
684
685 SelectionList
686 SelectionCollection::parseFromStdin(int nr, bool bInteractive,
687                                     const std::string &context)
688 {
689     yyscan_t scanner;
690
691     _gmx_sel_init_lexer(&scanner, &impl_->sc_, bInteractive, nr,
692                         impl_->bExternalGroupsSet_,
693                         impl_->grps_);
694     return runParser(scanner, true, nr, context);
695 }
696
697
698 SelectionList
699 SelectionCollection::parseFromFile(const std::string &filename)
700 {
701
702     try
703     {
704         yyscan_t scanner;
705         File     file(filename, "r");
706         // TODO: Exception-safe way of using the lexer.
707         _gmx_sel_init_lexer(&scanner, &impl_->sc_, false, -1,
708                             impl_->bExternalGroupsSet_,
709                             impl_->grps_);
710         _gmx_sel_set_lex_input_file(scanner, file.handle());
711         return runParser(scanner, false, -1, std::string());
712     }
713     catch (GromacsException &ex)
714     {
715         ex.prependContext(formatString(
716                                   "Error in parsing selections from file '%s'",
717                                   filename.c_str()));
718         throw;
719     }
720 }
721
722
723 SelectionList
724 SelectionCollection::parseFromString(const std::string &str)
725 {
726     yyscan_t scanner;
727
728     _gmx_sel_init_lexer(&scanner, &impl_->sc_, false, -1,
729                         impl_->bExternalGroupsSet_,
730                         impl_->grps_);
731     _gmx_sel_set_lex_input_str(scanner, str.c_str());
732     return runParser(scanner, false, -1, std::string());
733 }
734
735
736 void
737 SelectionCollection::compile()
738 {
739     if (impl_->sc_.top == NULL && requiresTopology())
740     {
741         GMX_THROW(InconsistentInputError("Selection requires topology information, but none provided"));
742     }
743     if (!impl_->bExternalGroupsSet_)
744     {
745         setIndexGroups(NULL);
746     }
747     if (impl_->debugLevel_ >= 1)
748     {
749         printTree(stderr, false);
750     }
751
752     SelectionCompiler compiler;
753     compiler.compile(this);
754
755     if (impl_->debugLevel_ >= 1)
756     {
757         std::fprintf(stderr, "\n");
758         printTree(stderr, false);
759         std::fprintf(stderr, "\n");
760         impl_->sc_.pcc.printTree(stderr);
761         std::fprintf(stderr, "\n");
762     }
763     impl_->sc_.pcc.initEvaluation();
764     if (impl_->debugLevel_ >= 1)
765     {
766         impl_->sc_.pcc.printTree(stderr);
767         std::fprintf(stderr, "\n");
768     }
769
770     // TODO: It would be nicer to associate the name of the selection option
771     // (if available) to the error message.
772     SelectionDataList::const_iterator iter;
773     for (iter = impl_->sc_.sel.begin(); iter != impl_->sc_.sel.end(); ++iter)
774     {
775         const internal::SelectionData &sel = **iter;
776         if (sel.hasFlag(efSelection_OnlyAtoms))
777         {
778             if (!sel.hasOnlyAtoms())
779             {
780                 std::string message = formatString(
781                             "Selection '%s' does not evaluate to individual atoms. "
782                             "This is not allowed in this context.",
783                             sel.selectionText());
784                 GMX_THROW(InvalidInputError(message));
785             }
786         }
787         if (sel.hasFlag(efSelection_DisallowEmpty))
788         {
789             if (sel.posCount() == 0)
790             {
791                 std::string message = formatString(
792                             "Selection '%s' never matches any atoms.",
793                             sel.selectionText());
794                 GMX_THROW(InvalidInputError(message));
795             }
796         }
797     }
798 }
799
800
801 void
802 SelectionCollection::evaluate(t_trxframe *fr, t_pbc *pbc)
803 {
804     if (fr->natoms <= impl_->maxAtomIndex_)
805     {
806         std::string message = formatString(
807                     "Trajectory has less atoms (%d) than what is required for "
808                     "evaluating the provided selections (atoms up to index %d "
809                     "are required).", fr->natoms, impl_->maxAtomIndex_ + 1);
810         GMX_THROW(InconsistentInputError(message));
811     }
812     impl_->sc_.pcc.initFrame();
813
814     SelectionEvaluator evaluator;
815     evaluator.evaluate(this, fr, pbc);
816
817     if (impl_->debugLevel_ >= 3)
818     {
819         std::fprintf(stderr, "\n");
820         printTree(stderr, true);
821     }
822 }
823
824
825 void
826 SelectionCollection::evaluateFinal(int nframes)
827 {
828     SelectionEvaluator evaluator;
829     evaluator.evaluateFinal(this, nframes);
830 }
831
832
833 void
834 SelectionCollection::printTree(FILE *fp, bool bValues) const
835 {
836     SelectionTreeElementPointer sel = impl_->sc_.root;
837     while (sel)
838     {
839         _gmx_selelem_print_tree(fp, *sel, bValues, 0);
840         sel = sel->next;
841     }
842 }
843
844
845 void
846 SelectionCollection::printXvgrInfo(FILE *out, output_env_t oenv) const
847 {
848     if (output_env_get_xvg_format(oenv) != exvgNONE)
849     {
850         const gmx_ana_selcollection_t &sc = impl_->sc_;
851         std::fprintf(out, "# Selections:\n");
852         for (int i = 0; i < sc.nvars; ++i)
853         {
854             std::fprintf(out, "#   %s\n", sc.varstrs[i]);
855         }
856         for (size_t i = 0; i < sc.sel.size(); ++i)
857         {
858             std::fprintf(out, "#   %s\n", sc.sel[i]->selectionText());
859         }
860         std::fprintf(out, "#\n");
861     }
862 }
863
864 } // namespace gmx