2 * This file is part of the GROMACS molecular simulation package.
4 * Copyright (c) 2010,2011,2012,2013, 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"
46 #include <boost/shared_ptr.hpp>
48 #include "gromacs/legacyheaders/oenv.h"
49 #include "gromacs/legacyheaders/smalloc.h"
50 #include "gromacs/legacyheaders/xvgr.h"
52 #include "gromacs/options/basicoptions.h"
53 #include "gromacs/options/options.h"
54 #include "gromacs/selection/selection.h"
55 #include "gromacs/utility/exceptions.h"
56 #include "gromacs/utility/file.h"
57 #include "gromacs/utility/gmxassert.h"
58 #include "gromacs/utility/messagestringcollector.h"
59 #include "gromacs/utility/stringutil.h"
66 #include "selection.h"
67 #include "selectioncollection-impl.h"
70 #include "selmethod.h"
76 /********************************************************************
77 * SelectionCollection::Impl
80 SelectionCollection::Impl::Impl()
81 : debugLevel_(0), bExternalGroupsSet_(false), grps_(NULL)
86 gmx_ana_index_clear(&sc_.gall);
88 sc_.symtab.reset(new SelectionParserSymbolTable);
89 gmx_ana_selmethod_register_defaults(sc_.symtab.get());
93 SelectionCollection::Impl::~Impl()
96 // The tree must be freed before the SelectionData objects, since the
97 // tree may hold references to the position data in SelectionData.
100 for (int i = 0; i < sc_.nvars; ++i)
102 sfree(sc_.varstrs[i]);
105 gmx_ana_index_deinit(&sc_.gall);
108 _gmx_sel_mempool_destroy(sc_.mempool);
114 SelectionCollection::Impl::clearSymbolTable()
124 * Reads a single selection line from stdin.
126 * \param[in] infile File to read from (typically File::standardInput()).
127 * \param[in] bInteractive Whether to print interactive prompts.
128 * \param[out] line The read line in stored here.
129 * \returns true if something was read, false if at end of input.
131 * Handles line continuation, reading also the continuing line(s) in one call.
133 bool promptLine(File *infile, bool bInteractive, std::string *line)
137 fprintf(stderr, "> ");
139 if (!infile->readLineWithTrailingSpace(line))
143 while (endsWith(*line, "\\\n"))
145 line->resize(line->length() - 2);
148 fprintf(stderr, "... ");
151 // Return value ignored, buffer remains empty and works correctly
152 // if there is nothing to read.
153 infile->readLineWithTrailingSpace(&buffer);
154 line->append(buffer);
156 if (endsWith(*line, "\n"))
158 line->resize(line->length() - 1);
160 else if (bInteractive)
162 fprintf(stderr, "\n");
168 * Helper function for tokenizing the input and pushing them to the parser.
170 * \param scanner Tokenizer data structure.
171 * \param parserState Parser data structure.
172 * \param[in] bInteractive Whether to operate in interactive mode.
174 * Repeatedly reads tokens using \p scanner and pushes them to the parser with
175 * \p parserState until there is no more input, or until enough input is given
176 * (only in interactive mode).
178 int runParserLoop(yyscan_t scanner, _gmx_sel_yypstate *parserState,
181 int status = YYPUSH_MORE;
186 int token = _gmx_sel_yylex(&value, scanner);
193 // Empty commands cause the interactive parser to print out
194 // status information. This avoids producing those unnecessarily,
195 // e.g., from "resname RA;;".
196 if (prevToken == CMD_SEP && token == CMD_SEP)
202 status = _gmx_sel_yypush_parse(parserState, token, &value, scanner);
204 while (status == YYPUSH_MORE);
205 _gmx_sel_lexer_rethrow_exception_if_occurred(scanner);
210 * Helper function that runs the parser once the tokenizer has been
213 * \param[in,out] scanner Scanner data structure.
214 * \param[in] bStdIn Whether to use a line-based reading
215 * algorithm designed for interactive input.
216 * \param[in] maxnr Maximum number of selections to parse
217 * (if -1, parse as many as provided by the user).
218 * \returns Vector of parsed selections.
219 * \throws std::bad_alloc if out of memory.
220 * \throws InvalidInputError if there is a parsing error.
222 * Used internally to implement parseFromStdin(), parseFromFile() and
225 SelectionList runParser(yyscan_t scanner, bool bStdIn, int maxnr)
227 boost::shared_ptr<void> scannerGuard(scanner, &_gmx_sel_free_lexer);
228 gmx_ana_selcollection_t *sc = _gmx_sel_lexer_selcollection(scanner);
230 MessageStringCollector errors;
231 _gmx_sel_set_lexer_error_reporter(scanner, &errors);
233 int oldCount = sc->sel.size();
236 boost::shared_ptr<_gmx_sel_yypstate> parserState(
237 _gmx_sel_yypstate_new(), &_gmx_sel_yypstate_delete);
240 File &stdinFile(File::standardInput());
241 bool bInteractive = _gmx_sel_is_lexer_interactive(scanner);
244 while (promptLine(&stdinFile, bInteractive, &line))
247 _gmx_sel_set_lex_input_str(scanner, line.c_str());
248 status = runParserLoop(scanner, parserState.get(), true);
249 if (status != YYPUSH_MORE)
251 // TODO: Check if there is more input, and issue an
252 // error/warning if some input was ignored.
253 goto early_termination;
255 if (!errors.isEmpty() && bInteractive)
257 fprintf(stderr, "%s", errors.toString().c_str());
261 status = _gmx_sel_yypush_parse(parserState.get(), 0, NULL,
263 _gmx_sel_lexer_rethrow_exception_if_occurred(scanner);
269 int status = runParserLoop(scanner, parserState.get(), false);
273 scannerGuard.reset();
274 int nr = sc->sel.size() - oldCount;
275 if (maxnr > 0 && nr != maxnr)
278 errors.append("Too few selections provided");
281 // TODO: Remove added selections from the collection if parsing failed?
282 if (!bOk || !errors.isEmpty())
284 GMX_ASSERT(!bOk && !errors.isEmpty(), "Inconsistent error reporting");
285 GMX_THROW(InvalidInputError(errors.toString()));
288 SelectionList result;
289 SelectionDataList::const_iterator i;
291 for (i = sc->sel.begin() + oldCount; i != sc->sel.end(); ++i)
293 result.push_back(Selection(i->get()));
301 void SelectionCollection::Impl::resolveExternalGroups(
302 const SelectionTreeElementPointer &root,
303 ExceptionInitializer *errors)
306 if (root->type == SEL_GROUPREF)
310 root->resolveIndexGroupReference(grps_);
312 catch (const UserInputError &)
314 errors->addCurrentExceptionAsNested();
318 SelectionTreeElementPointer child = root->child;
321 resolveExternalGroups(child, errors);
327 /********************************************************************
328 * SelectionCollection
331 SelectionCollection::SelectionCollection()
337 SelectionCollection::~SelectionCollection()
343 SelectionCollection::initOptions(Options *options)
345 const char * const debug_levels[]
346 = { "no", "basic", "compile", "eval", "full" };
348 bool bAllowNonAtomOutput = false;
349 SelectionDataList::const_iterator iter;
350 for (iter = impl_->sc_.sel.begin(); iter != impl_->sc_.sel.end(); ++iter)
352 const internal::SelectionData &sel = **iter;
353 if (!sel.hasFlag(efSelection_OnlyAtoms))
355 bAllowNonAtomOutput = true;
359 const char *const *postypes = PositionCalculationCollection::typeEnumValues;
360 options->addOption(StringOption("selrpos")
361 .enumValueFromNullTerminatedArray(postypes)
362 .store(&impl_->rpost_).defaultValue(postypes[0])
363 .description("Selection reference positions"));
364 if (bAllowNonAtomOutput)
366 options->addOption(StringOption("seltype")
367 .enumValueFromNullTerminatedArray(postypes)
368 .store(&impl_->spost_).defaultValue(postypes[0])
369 .description("Default selection output positions"));
373 impl_->spost_ = postypes[0];
375 GMX_RELEASE_ASSERT(impl_->debugLevel_ >= 0 && impl_->debugLevel_ <= 4,
376 "Debug level out of range");
377 options->addOption(StringOption("seldebug").hidden(impl_->debugLevel_ == 0)
378 .enumValue(debug_levels)
379 .defaultValue(debug_levels[impl_->debugLevel_])
380 .storeEnumIndex(&impl_->debugLevel_)
381 .description("Print out selection trees for debugging"));
386 SelectionCollection::setReferencePosType(const char *type)
388 GMX_RELEASE_ASSERT(type != NULL, "Cannot assign NULL position type");
389 // Check that the type is valid, throw if it is not.
390 e_poscalc_t dummytype;
392 PositionCalculationCollection::typeFromEnum(type, &dummytype, &dummyflags);
393 impl_->rpost_ = type;
398 SelectionCollection::setOutputPosType(const char *type)
400 GMX_RELEASE_ASSERT(type != NULL, "Cannot assign NULL position type");
401 // Check that the type is valid, throw if it is not.
402 e_poscalc_t dummytype;
404 PositionCalculationCollection::typeFromEnum(type, &dummytype, &dummyflags);
405 impl_->spost_ = type;
410 SelectionCollection::setDebugLevel(int debugLevel)
412 impl_->debugLevel_ = debugLevel;
417 SelectionCollection::setTopology(t_topology *top, int natoms)
419 GMX_RELEASE_ASSERT(natoms > 0 || top != NULL,
420 "The number of atoms must be given if there is no topology");
421 // Get the number of atoms from the topology if it is not given.
424 natoms = top->atoms.nr;
426 gmx_ana_selcollection_t *sc = &impl_->sc_;
427 // Do this first, as it allocates memory, while the others don't throw.
428 gmx_ana_index_init_simple(&sc->gall, natoms);
429 sc->pcc.setTopology(top);
435 SelectionCollection::setIndexGroups(gmx_ana_indexgrps_t *grps)
437 GMX_RELEASE_ASSERT(grps == NULL || !impl_->bExternalGroupsSet_,
438 "Can only set external groups once or clear them afterwards");
440 impl_->bExternalGroupsSet_ = true;
442 ExceptionInitializer errors("Unknown index group references encountered");
443 SelectionTreeElementPointer root = impl_->sc_.root;
446 impl_->resolveExternalGroups(root, &errors);
449 if (errors.hasNestedExceptions())
451 GMX_THROW(InconsistentInputError(errors));
453 for (size_t i = 0; i < impl_->sc_.sel.size(); ++i)
455 impl_->sc_.sel[i]->refreshName();
461 SelectionCollection::requiresTopology() const
466 if (!impl_->rpost_.empty())
469 // Should not throw, because has been checked earlier.
470 PositionCalculationCollection::typeFromEnum(impl_->rpost_.c_str(),
472 if (type != POS_ATOM)
477 if (!impl_->spost_.empty())
480 // Should not throw, because has been checked earlier.
481 PositionCalculationCollection::typeFromEnum(impl_->spost_.c_str(),
483 if (type != POS_ATOM)
489 SelectionTreeElementPointer sel = impl_->sc_.root;
492 if (_gmx_selelem_requires_top(*sel))
503 SelectionCollection::parseFromStdin(int nr, bool bInteractive)
507 _gmx_sel_init_lexer(&scanner, &impl_->sc_, bInteractive, nr,
508 impl_->bExternalGroupsSet_,
510 return runParser(scanner, true, nr);
515 SelectionCollection::parseFromFile(const std::string &filename)
521 File file(filename, "r");
522 // TODO: Exception-safe way of using the lexer.
523 _gmx_sel_init_lexer(&scanner, &impl_->sc_, false, -1,
524 impl_->bExternalGroupsSet_,
526 _gmx_sel_set_lex_input_file(scanner, file.handle());
527 return runParser(scanner, false, -1);
529 catch (GromacsException &ex)
531 ex.prependContext(formatString(
532 "Error in parsing selections from file '%s'",
540 SelectionCollection::parseFromString(const std::string &str)
544 _gmx_sel_init_lexer(&scanner, &impl_->sc_, false, -1,
545 impl_->bExternalGroupsSet_,
547 _gmx_sel_set_lex_input_str(scanner, str.c_str());
548 return runParser(scanner, false, -1);
553 SelectionCollection::compile()
555 if (impl_->sc_.top == NULL && requiresTopology())
557 GMX_THROW(InconsistentInputError("Selection requires topology information, but none provided"));
559 if (!impl_->bExternalGroupsSet_)
561 setIndexGroups(NULL);
563 if (impl_->debugLevel_ >= 1)
565 printTree(stderr, false);
568 SelectionCompiler compiler;
569 compiler.compile(this);
571 if (impl_->debugLevel_ >= 1)
573 std::fprintf(stderr, "\n");
574 printTree(stderr, false);
575 std::fprintf(stderr, "\n");
576 impl_->sc_.pcc.printTree(stderr);
577 std::fprintf(stderr, "\n");
579 impl_->sc_.pcc.initEvaluation();
580 if (impl_->debugLevel_ >= 1)
582 impl_->sc_.pcc.printTree(stderr);
583 std::fprintf(stderr, "\n");
586 // TODO: It would be nicer to associate the name of the selection option
587 // (if available) to the error message.
588 SelectionDataList::const_iterator iter;
589 for (iter = impl_->sc_.sel.begin(); iter != impl_->sc_.sel.end(); ++iter)
591 const internal::SelectionData &sel = **iter;
592 if (sel.hasFlag(efSelection_OnlyAtoms))
594 if (sel.type() != INDEX_ATOM)
596 std::string message = formatString(
597 "Selection '%s' does not evaluate to individual atoms. "
598 "This is not allowed in this context.",
599 sel.selectionText());
600 GMX_THROW(InvalidInputError(message));
603 if (sel.hasFlag(efSelection_DisallowEmpty))
605 if (sel.posCount() == 0)
607 std::string message = formatString(
608 "Selection '%s' never matches any atoms.",
609 sel.selectionText());
610 GMX_THROW(InvalidInputError(message));
618 SelectionCollection::evaluate(t_trxframe *fr, t_pbc *pbc)
620 impl_->sc_.pcc.initFrame();
622 SelectionEvaluator evaluator;
623 evaluator.evaluate(this, fr, pbc);
625 if (impl_->debugLevel_ >= 3)
627 std::fprintf(stderr, "\n");
628 printTree(stderr, true);
634 SelectionCollection::evaluateFinal(int nframes)
636 SelectionEvaluator evaluator;
637 evaluator.evaluateFinal(this, nframes);
642 SelectionCollection::printTree(FILE *fp, bool bValues) const
644 SelectionTreeElementPointer sel = impl_->sc_.root;
647 _gmx_selelem_print_tree(fp, *sel, bValues, 0);
654 SelectionCollection::printXvgrInfo(FILE *out, output_env_t oenv) const
656 if (output_env_get_xvg_format(oenv) != exvgNONE)
658 const gmx_ana_selcollection_t &sc = impl_->sc_;
659 std::fprintf(out, "# Selections:\n");
660 for (int i = 0; i < sc.nvars; ++i)
662 std::fprintf(out, "# %s\n", sc.varstrs[i]);
664 for (size_t i = 0; i < sc.sel.size(); ++i)
666 std::fprintf(out, "# %s\n", sc.sel[i]->selectionText());
668 std::fprintf(out, "#\n");
674 SelectionCollection::createDefaultHelpTopic()
676 return createSelectionHelpTopic();