Sort all includes in src/gromacs
[alexxy/gromacs.git] / src / gromacs / selection / selectioncollection.cpp
index 656ccb78c78b52bb3001f9e756460f2b03014737..f4bfd210a0663e69171982c1769970f3d5a9dc5f 100644 (file)
@@ -1,10 +1,10 @@
 /*
  * This file is part of the GROMACS molecular simulation package.
  *
- * Copyright (c) 2010,2011,2012,2013, by the GROMACS development team, led by
- * David van der Spoel, Berk Hess, Erik Lindahl, and including many
- * others, as listed in the AUTHORS file in the top-level source
- * directory and at http://www.gromacs.org.
+ * Copyright (c) 2010,2011,2012,2013,2014, by the GROMACS development team, led by
+ * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
+ * and including many others, as listed in the AUTHORS file in the
+ * top-level source directory and at http://www.gromacs.org.
  *
  * GROMACS is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public License
  * \author Teemu Murtola <teemu.murtola@gmail.com>
  * \ingroup module_selection
  */
+#include "gmxpre.h"
+
 #include "selectioncollection.h"
 
+#include <cctype>
 #include <cstdio>
 
+#include <string>
+#include <vector>
+
 #include <boost/shared_ptr.hpp>
 
+#include "gromacs/fileio/trx.h"
 #include "gromacs/legacyheaders/oenv.h"
-#include "gromacs/legacyheaders/smalloc.h"
-#include "gromacs/legacyheaders/xvgr.h"
-
+#include "gromacs/onlinehelp/helpmanager.h"
+#include "gromacs/onlinehelp/helpwritercontext.h"
 #include "gromacs/options/basicoptions.h"
 #include "gromacs/options/options.h"
 #include "gromacs/selection/selection.h"
+#include "gromacs/selection/selhelp.h"
+#include "gromacs/topology/topology.h"
 #include "gromacs/utility/exceptions.h"
 #include "gromacs/utility/file.h"
 #include "gromacs/utility/gmxassert.h"
 #include "gromacs/utility/messagestringcollector.h"
+#include "gromacs/utility/smalloc.h"
 #include "gromacs/utility/stringutil.h"
 
 #include "compiler.h"
 #include "parser.h"
 #include "poscalc.h"
 #include "scanner.h"
-#include "selection.h"
 #include "selectioncollection-impl.h"
 #include "selelem.h"
-#include "selhelp.h"
 #include "selmethod.h"
 #include "symrec.h"
 
@@ -78,7 +85,7 @@ namespace gmx
  */
 
 SelectionCollection::Impl::Impl()
-    : debugLevel_(0), bExternalGroupsSet_(false), grps_(NULL)
+    : maxAtomIndex_(0), debugLevel_(0), bExternalGroupsSet_(false), grps_(NULL)
 {
     sc_.nvars     = 0;
     sc_.varstrs   = NULL;
@@ -136,7 +143,7 @@ bool promptLine(File *infile, bool bInteractive, std::string *line)
     {
         fprintf(stderr, "> ");
     }
-    if (!infile->readLine(line))
+    if (!infile->readLineWithTrailingSpace(line))
     {
         return false;
     }
@@ -150,7 +157,7 @@ bool promptLine(File *infile, bool bInteractive, std::string *line)
         std::string buffer;
         // Return value ignored, buffer remains empty and works correctly
         // if there is nothing to read.
-        infile->readLine(&buffer);
+        infile->readLineWithTrailingSpace(&buffer);
         line->append(buffer);
     }
     if (endsWith(*line, "\n"))
@@ -206,6 +213,106 @@ int runParserLoop(yyscan_t scanner, _gmx_sel_yypstate *parserState,
     return status;
 }
 
+/*! \brief
+ * Print current status in response to empty line in interactive input.
+ *
+ * \param[in] sc             Selection collection data structure.
+ * \param[in] grps           Available index groups.
+ * \param[in] firstSelection Index of first selection from this interactive
+ *     session.
+ * \param[in] maxCount       Maximum number of selections.
+ * \param[in] context        Context to print for what the selections are for.
+ * \param[in] bFirst         Whether this is the header that is printed before
+ *     any user input.
+ *
+ * Prints the available index groups and currently provided selections.
+ */
+void printCurrentStatus(gmx_ana_selcollection_t *sc, gmx_ana_indexgrps_t *grps,
+                        size_t firstSelection, int maxCount,
+                        const std::string &context, bool bFirst)
+{
+    if (grps != NULL)
+    {
+        std::fprintf(stderr, "Available static index groups:\n");
+        gmx_ana_indexgrps_print(stderr, grps, 0);
+    }
+    std::fprintf(stderr, "Specify ");
+    if (maxCount < 0)
+    {
+        std::fprintf(stderr, "any number of selections");
+    }
+    else if (maxCount == 1)
+    {
+        std::fprintf(stderr, "a selection");
+    }
+    else
+    {
+        std::fprintf(stderr, "%d selections", maxCount);
+    }
+    std::fprintf(stderr, "%s%s:\n",
+                 context.empty() ? "" : " ", context.c_str());
+    std::fprintf(stderr,
+                 "(one per line, <enter> for status/groups, 'help' for help%s)\n",
+                 maxCount < 0 ? ", Ctrl-D to end" : "");
+    if (!bFirst && (sc->nvars > 0 || sc->sel.size() > firstSelection))
+    {
+        std::fprintf(stderr, "Currently provided selections:\n");
+        for (int i = 0; i < sc->nvars; ++i)
+        {
+            std::fprintf(stderr, "     %s\n", sc->varstrs[i]);
+        }
+        for (size_t i = firstSelection; i < sc->sel.size(); ++i)
+        {
+            std::fprintf(stderr, " %2d. %s\n",
+                         static_cast<int>(i - firstSelection + 1),
+                         sc->sel[i]->selectionText());
+        }
+        if (maxCount > 0)
+        {
+            const int remaining
+                = maxCount - static_cast<int>(sc->sel.size() - firstSelection);
+            std::fprintf(stderr, "(%d more selection%s required)\n",
+                         remaining, remaining > 1 ? "s" : "");
+        }
+    }
+}
+
+/*! \brief
+ * Prints selection help in interactive selection input.
+ *
+ * \param[in] sc    Selection collection data structure.
+ * \param[in] line  Line of user input requesting help (starting with `help`).
+ *
+ * Initializes the selection help if not yet initialized, and finds the help
+ * topic based on words on the input line.
+ */
+void printHelp(gmx_ana_selcollection_t *sc, const std::string &line)
+{
+    if (sc->rootHelp.get() == NULL)
+    {
+        sc->rootHelp = createSelectionHelpTopic();
+    }
+    HelpWriterContext context(&File::standardError(),
+                              eHelpOutputFormat_Console);
+    HelpManager       manager(*sc->rootHelp, context);
+    try
+    {
+        std::vector<std::string>                 topic = splitString(line);
+        std::vector<std::string>::const_iterator value;
+        // First item in the list is the 'help' token.
+        for (value = topic.begin() + 1; value != topic.end(); ++value)
+        {
+            manager.enterTopic(*value);
+        }
+    }
+    catch (const InvalidInputError &ex)
+    {
+        fprintf(stderr, "%s\n", ex.what());
+        return;
+    }
+    manager.writeCurrentTopic();
+}
+
 /*! \brief
  * Helper function that runs the parser once the tokenizer has been
  * initialized.
@@ -215,6 +322,7 @@ int runParserLoop(yyscan_t scanner, _gmx_sel_yypstate *parserState,
  *      algorithm designed for interactive input.
  * \param[in]     maxnr   Maximum number of selections to parse
  *      (if -1, parse as many as provided by the user).
+ * \param[in]     context Context to print for what the selections are for.
  * \returns       Vector of parsed selections.
  * \throws        std::bad_alloc if out of memory.
  * \throws        InvalidInputError if there is a parsing error.
@@ -222,27 +330,48 @@ int runParserLoop(yyscan_t scanner, _gmx_sel_yypstate *parserState,
  * Used internally to implement parseFromStdin(), parseFromFile() and
  * parseFromString().
  */
-SelectionList runParser(yyscan_t scanner, bool bStdIn, int maxnr)
+SelectionList runParser(yyscan_t scanner, bool bStdIn, int maxnr,
+                        const std::string &context)
 {
     boost::shared_ptr<void>  scannerGuard(scanner, &_gmx_sel_free_lexer);
-    gmx_ana_selcollection_t *sc = _gmx_sel_lexer_selcollection(scanner);
+    gmx_ana_selcollection_t *sc   = _gmx_sel_lexer_selcollection(scanner);
+    gmx_ana_indexgrps_t     *grps = _gmx_sel_lexer_indexgrps(scanner);
 
     MessageStringCollector   errors;
     _gmx_sel_set_lexer_error_reporter(scanner, &errors);
 
-    int  oldCount = sc->sel.size();
-    bool bOk      = false;
+    size_t oldCount = sc->sel.size();
+    bool   bOk      = false;
     {
         boost::shared_ptr<_gmx_sel_yypstate> parserState(
                 _gmx_sel_yypstate_new(), &_gmx_sel_yypstate_delete);
         if (bStdIn)
         {
             File       &stdinFile(File::standardInput());
-            bool        bInteractive = _gmx_sel_is_lexer_interactive(scanner);
+            const bool  bInteractive = _gmx_sel_is_lexer_interactive(scanner);
+            if (bInteractive)
+            {
+                printCurrentStatus(sc, grps, oldCount, maxnr, context, true);
+            }
             std::string line;
             int         status;
             while (promptLine(&stdinFile, bInteractive, &line))
             {
+                if (bInteractive)
+                {
+                    line = stripString(line);
+                    if (line.empty())
+                    {
+                        printCurrentStatus(sc, grps, oldCount, maxnr, context, false);
+                        continue;
+                    }
+                    if (startsWith(line, "help")
+                        && (line[4] == 0 || std::isspace(line[4])))
+                    {
+                        printHelp(sc, line);
+                        continue;
+                    }
+                }
                 line.append("\n");
                 _gmx_sel_set_lex_input_str(scanner, line.c_str());
                 status = runParserLoop(scanner, parserState.get(), true);
@@ -295,50 +424,61 @@ early_termination:
     return result;
 }
 
+/*! \brief
+ * Checks that index groups have valid atom indices.
+ *
+ * \param[in]    root    Root of selection tree to process.
+ * \param[in]    natoms  Maximum number of atoms that the selections are set
+ *     to evaluate.
+ * \param        errors  Object for reporting any error messages.
+ * \throws std::bad_alloc if out of memory.
+ *
+ * Recursively checks the selection tree for index groups.
+ * Each found group is checked that it only contains atom indices that match
+ * the topology/maximum number of atoms set for the selection collection.
+ * Any issues are reported to \p errors.
+ */
+void checkExternalGroups(const SelectionTreeElementPointer &root,
+                         int                                natoms,
+                         ExceptionInitializer              *errors)
+{
+    if (root->type == SEL_CONST && root->v.type == GROUP_VALUE)
+    {
+        try
+        {
+            root->checkIndexGroup(natoms);
+        }
+        catch (const UserInputError &)
+        {
+            errors->addCurrentExceptionAsNested();
+        }
+    }
+
+    SelectionTreeElementPointer child = root->child;
+    while (child)
+    {
+        checkExternalGroups(child, natoms, errors);
+        child = child->next;
+    }
+}
+
 }   // namespace
 
 
 void SelectionCollection::Impl::resolveExternalGroups(
         const SelectionTreeElementPointer &root,
-        MessageStringCollector            *errors)
+        ExceptionInitializer              *errors)
 {
 
     if (root->type == SEL_GROUPREF)
     {
-        bool        bOk = true;
-        std::string foundName;
-        if (grps_ == NULL)
+        try
         {
-            // TODO: Improve error messages
-            errors->append("Unknown group referenced in a selection");
-            bOk = false;
+            root->resolveIndexGroupReference(grps_, sc_.gall.isize);
         }
-        else if (root->u.gref.name != NULL)
+        catch (const UserInputError &)
         {
-            char *name = root->u.gref.name;
-            bOk = gmx_ana_indexgrps_find(&root->u.cgrp, &foundName, grps_, name);
-            sfree(name);
-            root->u.gref.name = NULL;
-            if (!bOk)
-            {
-                // TODO: Improve error messages
-                errors->append("Unknown group referenced in a selection");
-            }
-        }
-        else
-        {
-            if (!gmx_ana_indexgrps_extract(&root->u.cgrp, &foundName, grps_,
-                                           root->u.gref.id))
-            {
-                // TODO: Improve error messages
-                errors->append("Unknown group referenced in a selection");
-                bOk = false;
-            }
-        }
-        if (bOk)
-        {
-            root->type = SEL_CONST;
-            root->setName(foundName);
+            errors->addCurrentExceptionAsNested();
         }
     }
 
@@ -346,7 +486,8 @@ void SelectionCollection::Impl::resolveExternalGroups(
     while (child)
     {
         resolveExternalGroups(child, errors);
-        child = child->next;
+        root->flags |= (child->flags & SEL_UNSORTED);
+        child        = child->next;
     }
 }
 
@@ -450,6 +591,20 @@ SelectionCollection::setTopology(t_topology *top, int natoms)
     {
         natoms = top->atoms.nr;
     }
+    if (impl_->bExternalGroupsSet_)
+    {
+        ExceptionInitializer        errors("Invalid index group references encountered");
+        SelectionTreeElementPointer root = impl_->sc_.root;
+        while (root)
+        {
+            checkExternalGroups(root, natoms, &errors);
+            root = root->next;
+        }
+        if (errors.hasNestedExceptions())
+        {
+            GMX_THROW(InconsistentInputError(errors));
+        }
+    }
     gmx_ana_selcollection_t *sc = &impl_->sc_;
     // Do this first, as it allocates memory, while the others don't throw.
     gmx_ana_index_init_simple(&sc->gall, natoms);
@@ -466,16 +621,21 @@ SelectionCollection::setIndexGroups(gmx_ana_indexgrps_t *grps)
     impl_->grps_               = grps;
     impl_->bExternalGroupsSet_ = true;
 
-    MessageStringCollector      errors;
+    ExceptionInitializer        errors("Invalid index group reference(s)");
     SelectionTreeElementPointer root = impl_->sc_.root;
     while (root)
     {
         impl_->resolveExternalGroups(root, &errors);
+        root->checkUnsortedAtoms(true, &errors);
         root = root->next;
     }
-    if (!errors.isEmpty())
+    if (errors.hasNestedExceptions())
     {
-        GMX_THROW(InvalidInputError(errors.toString()));
+        GMX_THROW(InconsistentInputError(errors));
+    }
+    for (size_t i = 0; i < impl_->sc_.sel.size(); ++i)
+    {
+        impl_->sc_.sel[i]->refreshName();
     }
 }
 
@@ -523,14 +683,15 @@ SelectionCollection::requiresTopology() const
 
 
 SelectionList
-SelectionCollection::parseFromStdin(int nr, bool bInteractive)
+SelectionCollection::parseFromStdin(int nr, bool bInteractive,
+                                    const std::string &context)
 {
     yyscan_t scanner;
 
     _gmx_sel_init_lexer(&scanner, &impl_->sc_, bInteractive, nr,
                         impl_->bExternalGroupsSet_,
                         impl_->grps_);
-    return runParser(scanner, true, nr);
+    return runParser(scanner, true, nr, context);
 }
 
 
@@ -547,7 +708,7 @@ SelectionCollection::parseFromFile(const std::string &filename)
                             impl_->bExternalGroupsSet_,
                             impl_->grps_);
         _gmx_sel_set_lex_input_file(scanner, file.handle());
-        return runParser(scanner, false, -1);
+        return runParser(scanner, false, -1, std::string());
     }
     catch (GromacsException &ex)
     {
@@ -568,7 +729,7 @@ SelectionCollection::parseFromString(const std::string &str)
                         impl_->bExternalGroupsSet_,
                         impl_->grps_);
     _gmx_sel_set_lex_input_str(scanner, str.c_str());
-    return runParser(scanner, false, -1);
+    return runParser(scanner, false, -1, std::string());
 }
 
 
@@ -614,7 +775,7 @@ SelectionCollection::compile()
         const internal::SelectionData &sel = **iter;
         if (sel.hasFlag(efSelection_OnlyAtoms))
         {
-            if (sel.type() != INDEX_ATOM)
+            if (!sel.hasOnlyAtoms())
             {
                 std::string message = formatString(
                             "Selection '%s' does not evaluate to individual atoms. "
@@ -640,6 +801,14 @@ SelectionCollection::compile()
 void
 SelectionCollection::evaluate(t_trxframe *fr, t_pbc *pbc)
 {
+    if (fr->natoms <= impl_->maxAtomIndex_)
+    {
+        std::string message = formatString(
+                    "Trajectory has less atoms (%d) than what is required for "
+                    "evaluating the provided selections (atoms up to index %d "
+                    "are required).", fr->natoms, impl_->maxAtomIndex_ + 1);
+        GMX_THROW(InconsistentInputError(message));
+    }
     impl_->sc_.pcc.initFrame();
 
     SelectionEvaluator evaluator;
@@ -692,11 +861,4 @@ SelectionCollection::printXvgrInfo(FILE *out, output_env_t oenv) const
     }
 }
 
-// static
-HelpTopicPointer
-SelectionCollection::createDefaultHelpTopic()
-{
-    return createSelectionHelpTopic();
-}
-
 } // namespace gmx