2 * This file is part of the GROMACS molecular simulation package.
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.
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.
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.
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.
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.
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.
37 * Implements gmx::SelectionCollection.
39 * \author Teemu Murtola <teemu.murtola@gmail.com>
40 * \ingroup module_selection
42 #include "selectioncollection.h"
50 #include <boost/shared_ptr.hpp>
52 #include "gromacs/legacyheaders/oenv.h"
54 #include "gromacs/onlinehelp/helpmanager.h"
55 #include "gromacs/onlinehelp/helpwritercontext.h"
56 #include "gromacs/options/basicoptions.h"
57 #include "gromacs/options/options.h"
58 #include "gromacs/selection/selection.h"
59 #include "gromacs/utility/exceptions.h"
60 #include "gromacs/utility/file.h"
61 #include "gromacs/utility/gmxassert.h"
62 #include "gromacs/utility/messagestringcollector.h"
63 #include "gromacs/utility/smalloc.h"
64 #include "gromacs/utility/stringutil.h"
71 #include "selection.h"
72 #include "selectioncollection-impl.h"
75 #include "selmethod.h"
81 /********************************************************************
82 * SelectionCollection::Impl
85 SelectionCollection::Impl::Impl()
86 : debugLevel_(0), bExternalGroupsSet_(false), grps_(NULL)
91 gmx_ana_index_clear(&sc_.gall);
93 sc_.symtab.reset(new SelectionParserSymbolTable);
94 gmx_ana_selmethod_register_defaults(sc_.symtab.get());
98 SelectionCollection::Impl::~Impl()
101 // The tree must be freed before the SelectionData objects, since the
102 // tree may hold references to the position data in SelectionData.
105 for (int i = 0; i < sc_.nvars; ++i)
107 sfree(sc_.varstrs[i]);
110 gmx_ana_index_deinit(&sc_.gall);
113 _gmx_sel_mempool_destroy(sc_.mempool);
119 SelectionCollection::Impl::clearSymbolTable()
129 * Reads a single selection line from stdin.
131 * \param[in] infile File to read from (typically File::standardInput()).
132 * \param[in] bInteractive Whether to print interactive prompts.
133 * \param[out] line The read line in stored here.
134 * \returns true if something was read, false if at end of input.
136 * Handles line continuation, reading also the continuing line(s) in one call.
138 bool promptLine(File *infile, bool bInteractive, std::string *line)
142 fprintf(stderr, "> ");
144 if (!infile->readLineWithTrailingSpace(line))
148 while (endsWith(*line, "\\\n"))
150 line->resize(line->length() - 2);
153 fprintf(stderr, "... ");
156 // Return value ignored, buffer remains empty and works correctly
157 // if there is nothing to read.
158 infile->readLineWithTrailingSpace(&buffer);
159 line->append(buffer);
161 if (endsWith(*line, "\n"))
163 line->resize(line->length() - 1);
165 else if (bInteractive)
167 fprintf(stderr, "\n");
173 * Helper function for tokenizing the input and pushing them to the parser.
175 * \param scanner Tokenizer data structure.
176 * \param parserState Parser data structure.
177 * \param[in] bInteractive Whether to operate in interactive mode.
179 * Repeatedly reads tokens using \p scanner and pushes them to the parser with
180 * \p parserState until there is no more input, or until enough input is given
181 * (only in interactive mode).
183 int runParserLoop(yyscan_t scanner, _gmx_sel_yypstate *parserState,
186 int status = YYPUSH_MORE;
191 int token = _gmx_sel_yylex(&value, scanner);
198 // Empty commands cause the interactive parser to print out
199 // status information. This avoids producing those unnecessarily,
200 // e.g., from "resname RA;;".
201 if (prevToken == CMD_SEP && token == CMD_SEP)
207 status = _gmx_sel_yypush_parse(parserState, token, &value, scanner);
209 while (status == YYPUSH_MORE);
210 _gmx_sel_lexer_rethrow_exception_if_occurred(scanner);
215 * Print current status in response to empty line in interactive input.
217 * \param[in] sc Selection collection data structure.
218 * \param[in] grps Available index groups.
219 * \param[in] firstSelection Index of first selection from this interactive
221 * \param[in] maxCount Maximum number of selections.
222 * \param[in] context Context to print for what the selections are for.
223 * \param[in] bFirst Whether this is the header that is printed before
226 * Prints the available index groups and currently provided selections.
228 void printCurrentStatus(gmx_ana_selcollection_t *sc, gmx_ana_indexgrps_t *grps,
229 size_t firstSelection, int maxCount,
230 const std::string &context, bool bFirst)
234 std::fprintf(stderr, "Available static index groups:\n");
235 gmx_ana_indexgrps_print(stderr, grps, 0);
237 std::fprintf(stderr, "Specify ");
240 std::fprintf(stderr, "any number of selections");
242 else if (maxCount == 1)
244 std::fprintf(stderr, "a selection");
248 std::fprintf(stderr, "%d selections", maxCount);
250 std::fprintf(stderr, "%s%s:\n",
251 context.empty() ? "" : " ", context.c_str());
253 "(one per line, <enter> for status/groups, 'help' for help%s)\n",
254 maxCount < 0 ? ", Ctrl-D to end" : "");
255 if (!bFirst && (sc->nvars > 0 || sc->sel.size() > firstSelection))
257 std::fprintf(stderr, "Currently provided selections:\n");
258 for (int i = 0; i < sc->nvars; ++i)
260 std::fprintf(stderr, " %s\n", sc->varstrs[i]);
262 for (size_t i = firstSelection; i < sc->sel.size(); ++i)
264 std::fprintf(stderr, " %2d. %s\n",
265 static_cast<int>(i - firstSelection + 1),
266 sc->sel[i]->selectionText());
271 = maxCount - static_cast<int>(sc->sel.size() - firstSelection);
272 std::fprintf(stderr, "(%d more selection%s required)\n",
273 remaining, remaining > 1 ? "s" : "");
279 * Prints selection help in interactive selection input.
281 * \param[in] sc Selection collection data structure.
282 * \param[in] line Line of user input requesting help (starting with `help`).
284 * Initializes the selection help if not yet initialized, and finds the help
285 * topic based on words on the input line.
287 void printHelp(gmx_ana_selcollection_t *sc, const std::string &line)
289 if (sc->rootHelp.get() == NULL)
291 sc->rootHelp = createSelectionHelpTopic();
293 HelpWriterContext context(&File::standardError(),
294 eHelpOutputFormat_Console);
295 HelpManager manager(*sc->rootHelp, context);
298 std::vector<std::string> topic = splitString(line);
299 std::vector<std::string>::const_iterator value;
300 // First item in the list is the 'help' token.
301 for (value = topic.begin() + 1; value != topic.end(); ++value)
303 manager.enterTopic(*value);
306 catch (const InvalidInputError &ex)
308 fprintf(stderr, "%s\n", ex.what());
311 manager.writeCurrentTopic();
315 * Helper function that runs the parser once the tokenizer has been
318 * \param[in,out] scanner Scanner data structure.
319 * \param[in] bStdIn Whether to use a line-based reading
320 * algorithm designed for interactive input.
321 * \param[in] maxnr Maximum number of selections to parse
322 * (if -1, parse as many as provided by the user).
323 * \param[in] context Context to print for what the selections are for.
324 * \returns Vector of parsed selections.
325 * \throws std::bad_alloc if out of memory.
326 * \throws InvalidInputError if there is a parsing error.
328 * Used internally to implement parseFromStdin(), parseFromFile() and
331 SelectionList runParser(yyscan_t scanner, bool bStdIn, int maxnr,
332 const std::string &context)
334 boost::shared_ptr<void> scannerGuard(scanner, &_gmx_sel_free_lexer);
335 gmx_ana_selcollection_t *sc = _gmx_sel_lexer_selcollection(scanner);
336 gmx_ana_indexgrps_t *grps = _gmx_sel_lexer_indexgrps(scanner);
338 MessageStringCollector errors;
339 _gmx_sel_set_lexer_error_reporter(scanner, &errors);
341 size_t oldCount = sc->sel.size();
344 boost::shared_ptr<_gmx_sel_yypstate> parserState(
345 _gmx_sel_yypstate_new(), &_gmx_sel_yypstate_delete);
348 File &stdinFile(File::standardInput());
349 const bool bInteractive = _gmx_sel_is_lexer_interactive(scanner);
352 printCurrentStatus(sc, grps, oldCount, maxnr, context, true);
356 while (promptLine(&stdinFile, bInteractive, &line))
360 line = stripString(line);
363 printCurrentStatus(sc, grps, oldCount, maxnr, context, false);
366 if (startsWith(line, "help")
367 && (line[4] == 0 || std::isspace(line[4])))
374 _gmx_sel_set_lex_input_str(scanner, line.c_str());
375 status = runParserLoop(scanner, parserState.get(), true);
376 if (status != YYPUSH_MORE)
378 // TODO: Check if there is more input, and issue an
379 // error/warning if some input was ignored.
380 goto early_termination;
382 if (!errors.isEmpty() && bInteractive)
384 fprintf(stderr, "%s", errors.toString().c_str());
388 status = _gmx_sel_yypush_parse(parserState.get(), 0, NULL,
390 _gmx_sel_lexer_rethrow_exception_if_occurred(scanner);
396 int status = runParserLoop(scanner, parserState.get(), false);
400 scannerGuard.reset();
401 int nr = sc->sel.size() - oldCount;
402 if (maxnr > 0 && nr != maxnr)
405 errors.append("Too few selections provided");
408 // TODO: Remove added selections from the collection if parsing failed?
409 if (!bOk || !errors.isEmpty())
411 GMX_ASSERT(!bOk && !errors.isEmpty(), "Inconsistent error reporting");
412 GMX_THROW(InvalidInputError(errors.toString()));
415 SelectionList result;
416 SelectionDataList::const_iterator i;
418 for (i = sc->sel.begin() + oldCount; i != sc->sel.end(); ++i)
420 result.push_back(Selection(i->get()));
428 void SelectionCollection::Impl::resolveExternalGroups(
429 const SelectionTreeElementPointer &root,
430 ExceptionInitializer *errors)
433 if (root->type == SEL_GROUPREF)
437 root->resolveIndexGroupReference(grps_);
439 catch (const UserInputError &)
441 errors->addCurrentExceptionAsNested();
445 SelectionTreeElementPointer child = root->child;
448 resolveExternalGroups(child, errors);
454 /********************************************************************
455 * SelectionCollection
458 SelectionCollection::SelectionCollection()
464 SelectionCollection::~SelectionCollection()
470 SelectionCollection::initOptions(Options *options)
472 const char * const debug_levels[]
473 = { "no", "basic", "compile", "eval", "full" };
475 bool bAllowNonAtomOutput = false;
476 SelectionDataList::const_iterator iter;
477 for (iter = impl_->sc_.sel.begin(); iter != impl_->sc_.sel.end(); ++iter)
479 const internal::SelectionData &sel = **iter;
480 if (!sel.hasFlag(efSelection_OnlyAtoms))
482 bAllowNonAtomOutput = true;
486 const char *const *postypes = PositionCalculationCollection::typeEnumValues;
487 options->addOption(StringOption("selrpos")
488 .enumValueFromNullTerminatedArray(postypes)
489 .store(&impl_->rpost_).defaultValue(postypes[0])
490 .description("Selection reference positions"));
491 if (bAllowNonAtomOutput)
493 options->addOption(StringOption("seltype")
494 .enumValueFromNullTerminatedArray(postypes)
495 .store(&impl_->spost_).defaultValue(postypes[0])
496 .description("Default selection output positions"));
500 impl_->spost_ = postypes[0];
502 GMX_RELEASE_ASSERT(impl_->debugLevel_ >= 0 && impl_->debugLevel_ <= 4,
503 "Debug level out of range");
504 options->addOption(StringOption("seldebug").hidden(impl_->debugLevel_ == 0)
505 .enumValue(debug_levels)
506 .defaultValue(debug_levels[impl_->debugLevel_])
507 .storeEnumIndex(&impl_->debugLevel_)
508 .description("Print out selection trees for debugging"));
513 SelectionCollection::setReferencePosType(const char *type)
515 GMX_RELEASE_ASSERT(type != NULL, "Cannot assign NULL position type");
516 // Check that the type is valid, throw if it is not.
517 e_poscalc_t dummytype;
519 PositionCalculationCollection::typeFromEnum(type, &dummytype, &dummyflags);
520 impl_->rpost_ = type;
525 SelectionCollection::setOutputPosType(const char *type)
527 GMX_RELEASE_ASSERT(type != NULL, "Cannot assign NULL position type");
528 // Check that the type is valid, throw if it is not.
529 e_poscalc_t dummytype;
531 PositionCalculationCollection::typeFromEnum(type, &dummytype, &dummyflags);
532 impl_->spost_ = type;
537 SelectionCollection::setDebugLevel(int debugLevel)
539 impl_->debugLevel_ = debugLevel;
544 SelectionCollection::setTopology(t_topology *top, int natoms)
546 GMX_RELEASE_ASSERT(natoms > 0 || top != NULL,
547 "The number of atoms must be given if there is no topology");
548 // Get the number of atoms from the topology if it is not given.
551 natoms = top->atoms.nr;
553 gmx_ana_selcollection_t *sc = &impl_->sc_;
554 // Do this first, as it allocates memory, while the others don't throw.
555 gmx_ana_index_init_simple(&sc->gall, natoms);
556 sc->pcc.setTopology(top);
562 SelectionCollection::setIndexGroups(gmx_ana_indexgrps_t *grps)
564 GMX_RELEASE_ASSERT(grps == NULL || !impl_->bExternalGroupsSet_,
565 "Can only set external groups once or clear them afterwards");
567 impl_->bExternalGroupsSet_ = true;
569 ExceptionInitializer errors("Unknown index group references encountered");
570 SelectionTreeElementPointer root = impl_->sc_.root;
573 impl_->resolveExternalGroups(root, &errors);
576 if (errors.hasNestedExceptions())
578 GMX_THROW(InconsistentInputError(errors));
580 for (size_t i = 0; i < impl_->sc_.sel.size(); ++i)
582 impl_->sc_.sel[i]->refreshName();
588 SelectionCollection::requiresTopology() const
593 if (!impl_->rpost_.empty())
596 // Should not throw, because has been checked earlier.
597 PositionCalculationCollection::typeFromEnum(impl_->rpost_.c_str(),
599 if (type != POS_ATOM)
604 if (!impl_->spost_.empty())
607 // Should not throw, because has been checked earlier.
608 PositionCalculationCollection::typeFromEnum(impl_->spost_.c_str(),
610 if (type != POS_ATOM)
616 SelectionTreeElementPointer sel = impl_->sc_.root;
619 if (_gmx_selelem_requires_top(*sel))
630 SelectionCollection::parseFromStdin(int nr, bool bInteractive,
631 const std::string &context)
635 _gmx_sel_init_lexer(&scanner, &impl_->sc_, bInteractive, nr,
636 impl_->bExternalGroupsSet_,
638 return runParser(scanner, true, nr, context);
643 SelectionCollection::parseFromFile(const std::string &filename)
649 File file(filename, "r");
650 // TODO: Exception-safe way of using the lexer.
651 _gmx_sel_init_lexer(&scanner, &impl_->sc_, false, -1,
652 impl_->bExternalGroupsSet_,
654 _gmx_sel_set_lex_input_file(scanner, file.handle());
655 return runParser(scanner, false, -1, std::string());
657 catch (GromacsException &ex)
659 ex.prependContext(formatString(
660 "Error in parsing selections from file '%s'",
668 SelectionCollection::parseFromString(const std::string &str)
672 _gmx_sel_init_lexer(&scanner, &impl_->sc_, false, -1,
673 impl_->bExternalGroupsSet_,
675 _gmx_sel_set_lex_input_str(scanner, str.c_str());
676 return runParser(scanner, false, -1, std::string());
681 SelectionCollection::compile()
683 if (impl_->sc_.top == NULL && requiresTopology())
685 GMX_THROW(InconsistentInputError("Selection requires topology information, but none provided"));
687 if (!impl_->bExternalGroupsSet_)
689 setIndexGroups(NULL);
691 if (impl_->debugLevel_ >= 1)
693 printTree(stderr, false);
696 SelectionCompiler compiler;
697 compiler.compile(this);
699 if (impl_->debugLevel_ >= 1)
701 std::fprintf(stderr, "\n");
702 printTree(stderr, false);
703 std::fprintf(stderr, "\n");
704 impl_->sc_.pcc.printTree(stderr);
705 std::fprintf(stderr, "\n");
707 impl_->sc_.pcc.initEvaluation();
708 if (impl_->debugLevel_ >= 1)
710 impl_->sc_.pcc.printTree(stderr);
711 std::fprintf(stderr, "\n");
714 // TODO: It would be nicer to associate the name of the selection option
715 // (if available) to the error message.
716 SelectionDataList::const_iterator iter;
717 for (iter = impl_->sc_.sel.begin(); iter != impl_->sc_.sel.end(); ++iter)
719 const internal::SelectionData &sel = **iter;
720 if (sel.hasFlag(efSelection_OnlyAtoms))
722 if (sel.type() != INDEX_ATOM)
724 std::string message = formatString(
725 "Selection '%s' does not evaluate to individual atoms. "
726 "This is not allowed in this context.",
727 sel.selectionText());
728 GMX_THROW(InvalidInputError(message));
731 if (sel.hasFlag(efSelection_DisallowEmpty))
733 if (sel.posCount() == 0)
735 std::string message = formatString(
736 "Selection '%s' never matches any atoms.",
737 sel.selectionText());
738 GMX_THROW(InvalidInputError(message));
746 SelectionCollection::evaluate(t_trxframe *fr, t_pbc *pbc)
748 impl_->sc_.pcc.initFrame();
750 SelectionEvaluator evaluator;
751 evaluator.evaluate(this, fr, pbc);
753 if (impl_->debugLevel_ >= 3)
755 std::fprintf(stderr, "\n");
756 printTree(stderr, true);
762 SelectionCollection::evaluateFinal(int nframes)
764 SelectionEvaluator evaluator;
765 evaluator.evaluateFinal(this, nframes);
770 SelectionCollection::printTree(FILE *fp, bool bValues) const
772 SelectionTreeElementPointer sel = impl_->sc_.root;
775 _gmx_selelem_print_tree(fp, *sel, bValues, 0);
782 SelectionCollection::printXvgrInfo(FILE *out, output_env_t oenv) const
784 if (output_env_get_xvg_format(oenv) != exvgNONE)
786 const gmx_ana_selcollection_t &sc = impl_->sc_;
787 std::fprintf(out, "# Selections:\n");
788 for (int i = 0; i < sc.nvars; ++i)
790 std::fprintf(out, "# %s\n", sc.varstrs[i]);
792 for (size_t i = 0; i < sc.sel.size(); ++i)
794 std::fprintf(out, "# %s\n", sc.sel[i]->selectionText());
796 std::fprintf(out, "#\n");
802 SelectionCollection::createDefaultHelpTopic()
804 return createSelectionHelpTopic();