Merge release-5-0 into master
[alexxy/gromacs.git] / src / gromacs / selection / selectionoptionmanager.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 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::SelectionOptionManager.
38  *
39  * \author Teemu Murtola <teemu.murtola@gmail.com>
40  * \ingroup module_selection
41  */
42 #include "selectionoptionmanager.h"
43
44 #include <cstdio>
45
46 #include "gromacs/selection/selection.h"
47 #include "gromacs/selection/selectioncollection.h"
48 #include "gromacs/selection/selectionoption.h"
49 #include "gromacs/selection/selectionfileoption.h"
50 #include "gromacs/utility/exceptions.h"
51 #include "gromacs/utility/stringutil.h"
52
53 #include "selectionoptionstorage.h"
54
55 namespace gmx
56 {
57
58 /********************************************************************
59  * SelectionOptionManager::Impl
60  */
61
62 /*! \internal \brief
63  * Private implemention class for SelectionOptionManager.
64  *
65  * \ingroup module_selection
66  */
67 class SelectionOptionManager::Impl
68 {
69     public:
70         /*! \brief
71          * Request for postponed parsing of selections.
72          */
73         struct SelectionRequest
74         {
75             //! Initializes a request for the given option.
76             explicit SelectionRequest(SelectionOptionStorage *storage)
77                 : storage_(storage)
78             {
79             }
80
81             //! Returns name of the requested selection optin.
82             const std::string &name() const
83             {
84                 return storage_->name();
85             }
86             //! Returns description for the requested selection option.
87             const std::string &description() const
88             {
89                 return storage_->description();
90             }
91             /*! \brief
92              * Returns the number of selections requested in this request.
93              *
94              * -1 indicates no upper limit.
95              */
96             int count() const
97             {
98                 return storage_->maxValueCount();
99             }
100
101             //! Storage object to which the selections will be added.
102             SelectionOptionStorage     *storage_;
103         };
104
105         //! Collection for a list of selection requests.
106         typedef std::vector<SelectionRequest> RequestList;
107         //! Collection for list of option storage objects.
108         typedef std::vector<SelectionOptionStorage *> OptionList;
109
110         /*! \brief
111          * Helper class that clears a request list on scope exit.
112          *
113          * Methods in this class do not throw.
114          */
115         class RequestsClearer
116         {
117             public:
118                 //! Constructs an object that clears given list on scope exit.
119                 explicit RequestsClearer(RequestList *requests)
120                     : requests_(requests)
121                 {
122                 }
123                 //! Clears the request list given to the constructor.
124                 ~RequestsClearer()
125                 {
126                     requests_->clear();
127                 }
128
129             private:
130                 RequestList    *requests_;
131         };
132
133         /*! \brief
134          * Creates a new selection collection.
135          *
136          * \throws  std::bad_alloc if out of memory.
137          */
138         explicit Impl(SelectionCollection *collection);
139
140         /*! \brief
141          * Assign selections from a list to pending requests.
142          *
143          * \param[in] selections  List of selections to assign.
144          * \throws    std::bad_alloc if out of memory.
145          * \throws    InvalidInputError if the assignment cannot be done
146          *      (see parseRequestedFromFile() for documented conditions).
147          *
148          * Loops through \p selections and the pending requests lists in order,
149          * and for each requests, assigns the first yet unassigned selections
150          * from the list.
151          */
152         void placeSelectionsInRequests(const SelectionList &selections);
153         /*! \brief
154          * Adds a request for each required option that is not yet set.
155          *
156          * \throws    std::bad_alloc if out of memory.
157          */
158         void requestUnsetRequiredOptions();
159
160         //! Selection collection to which selections are stored.
161         SelectionCollection    &collection_;
162         //! List of selection options (storage objects) this manager manages.
163         OptionList              options_;
164         //! List of selections requested for later parsing.
165         RequestList             requests_;
166 };
167
168 SelectionOptionManager::Impl::Impl(SelectionCollection *collection)
169     : collection_(*collection)
170 {
171 }
172
173 void SelectionOptionManager::Impl::placeSelectionsInRequests(
174         const SelectionList &selections)
175 {
176     if (requests_.empty())
177     {
178         requestUnsetRequiredOptions();
179     }
180
181     RequestsClearer               clearRequestsOnExit(&requests_);
182
183     SelectionList::const_iterator first = selections.begin();
184     SelectionList::const_iterator last  = first;
185     RequestList::const_iterator   i;
186     for (i = requests_.begin(); i != requests_.end(); ++i)
187     {
188         const SelectionRequest &request = *i;
189         if (request.count() > 0)
190         {
191             int remaining = selections.end() - first;
192             if (remaining < request.count())
193             {
194                 int assigned = first - selections.begin();
195                 GMX_THROW(InvalidInputError(formatString(
196                                                     "Too few selections provided for '%s': "
197                                                     "Expected %d selections, but only %d left "
198                                                     "after assigning the first %d to other selections.",
199                                                     request.name().c_str(), request.count(),
200                                                     remaining, assigned)));
201             }
202             last = first + request.count();
203         }
204         else
205         {
206             RequestList::const_iterator nextRequest = i;
207             ++nextRequest;
208             if (nextRequest != requests_.end())
209             {
210                 const char *name         = request.name().c_str();
211                 const char *conflictName = nextRequest->name().c_str();
212                 GMX_THROW(InvalidInputError(formatString(
213                                                     "Ambiguous selections for '%s' and '%s': "
214                                                     "Any number of selections is acceptable for "
215                                                     "'%s', but you have requested subsequent "
216                                                     "selections to be assigned to '%s'. "
217                                                     "Resolution for such cases is not implemented, "
218                                                     "and may be impossible.",
219                                                     name, conflictName, name, conflictName)));
220             }
221             last = selections.end();
222         }
223         SelectionList curr(first, last);
224         request.storage_->addSelections(curr, true);
225         first = last;
226     }
227     if (last != selections.end())
228     {
229         int count     = selections.end() - selections.begin();
230         int remaining = selections.end() - last;
231         int assigned  = last - selections.begin();
232         GMX_THROW(InvalidInputError(formatString(
233                                             "Too many selections provided: "
234                                             "Expected %d selections, but %d provided. "
235                                             "Last %d selections could not be assigned to any option.",
236                                             assigned, count, remaining)));
237     }
238 }
239
240 void SelectionOptionManager::Impl::requestUnsetRequiredOptions()
241 {
242     OptionList::const_iterator i;
243     for (i = options_.begin(); i != options_.end(); ++i)
244     {
245         SelectionOptionStorage &storage = **i;
246         if (storage.isRequired() && !storage.isSet())
247         {
248             requests_.push_back(SelectionRequest(&storage));
249         }
250     }
251 }
252
253
254 /********************************************************************
255  * SelectionOptionManager
256  */
257
258 SelectionOptionManager::SelectionOptionManager(SelectionCollection *collection)
259     : impl_(new Impl(collection))
260 {
261 }
262
263 SelectionOptionManager::~SelectionOptionManager()
264 {
265 }
266
267 void
268 SelectionOptionManager::registerOption(SelectionOptionStorage *storage)
269 {
270     impl_->requests_.reserve(impl_->options_.size() + 1);
271     impl_->options_.push_back(storage);
272 }
273
274 void
275 SelectionOptionManager::convertOptionValue(SelectionOptionStorage *storage,
276                                            const std::string      &value,
277                                            bool                    bFullValue)
278 {
279     SelectionList selections = impl_->collection_.parseFromString(value);
280     storage->addSelections(selections, bFullValue);
281 }
282
283 void
284 SelectionOptionManager::requestOptionDelayedParsing(
285         SelectionOptionStorage *storage)
286 {
287     impl_->requests_.push_back(Impl::SelectionRequest(storage));
288 }
289
290 void
291 SelectionOptionManager::parseRequestedFromStdin(bool bInteractive)
292 {
293     Impl::RequestsClearer             clearRequestsOnExit(&impl_->requests_);
294
295     Impl::RequestList::const_iterator i;
296     for (i = impl_->requests_.begin(); i != impl_->requests_.end(); ++i)
297     {
298         const Impl::SelectionRequest &request = *i;
299         std::string                   context =
300             formatString("for option '%s'\n(%s)",
301                          request.name().c_str(), request.description().c_str());
302         SelectionList selections
303             = impl_->collection_.parseFromStdin(request.count(), bInteractive,
304                                                 context);
305         request.storage_->addSelections(selections, true);
306     }
307 }
308
309 void
310 SelectionOptionManager::parseRequestedFromFile(const std::string &filename)
311 {
312     SelectionList selections = impl_->collection_.parseFromFile(filename);
313     try
314     {
315         impl_->placeSelectionsInRequests(selections);
316     }
317     catch (GromacsException &ex)
318     {
319         ex.prependContext(formatString(
320                                   "Error in adding selections from file '%s'",
321                                   filename.c_str()));
322         throw;
323     }
324 }
325
326 void
327 SelectionOptionManager::parseRequestedFromString(const std::string &str)
328 {
329     SelectionList selections = impl_->collection_.parseFromString(str);
330     impl_->placeSelectionsInRequests(selections);
331 }
332
333 } // namespace gmx