Merge "Merge release-4-6 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, by the GROMACS development team, led by
5  * David van der Spoel, Berk Hess, Erik Lindahl, and including many
6  * others, as listed in the AUTHORS file in the top-level source
7  * 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/options/optionsvisitor.h"
47 #include "gromacs/selection/selection.h"
48 #include "gromacs/selection/selectioncollection.h"
49 #include "gromacs/selection/selectionoption.h"
50 #include "gromacs/selection/selectionfileoption.h"
51 #include "gromacs/utility/exceptions.h"
52 #include "gromacs/utility/stringutil.h"
53
54 #include "selectionoptionstorage.h"
55
56 namespace gmx
57 {
58
59 /********************************************************************
60  * SelectionOptionManager::Impl
61  */
62
63 /*! \internal \brief
64  * Private implemention class for SelectionOptionManager.
65  *
66  * \ingroup module_selection
67  */
68 class SelectionOptionManager::Impl
69 {
70     public:
71         /*! \brief
72          * Request for postponed parsing of selections.
73          */
74         struct SelectionRequest
75         {
76             //! Initializes a request for the given option.
77             explicit SelectionRequest(SelectionOptionStorage *storage)
78                 : storage_(storage)
79             {
80             }
81
82             //! Returns name of the requested selection optin.
83             const std::string &name() const
84             {
85                 return storage_->name();
86             }
87             //! Returns description for the requested selection option.
88             const std::string &description() const
89             {
90                 return storage_->description();
91             }
92             /*! \brief
93              * Returns the number of selections requested in this request.
94              *
95              * -1 indicates no upper limit.
96              */
97             int count() const
98             {
99                 return storage_->maxValueCount();
100             }
101
102             //! Storage object to which the selections will be added.
103             SelectionOptionStorage     *storage_;
104         };
105
106         //! Collection for a list of selection requests.
107         typedef std::vector<SelectionRequest> RequestList;
108         //! Collection for list of option storage objects.
109         typedef std::vector<SelectionOptionStorage *> OptionList;
110
111         /*! \brief
112          * Helper class that clears a request list on scope exit.
113          *
114          * Methods in this class do not throw.
115          */
116         class RequestsClearer
117         {
118             public:
119                 //! Constructs an object that clears given list on scope exit.
120                 explicit RequestsClearer(RequestList *requests)
121                     : requests_(requests)
122                 {
123                 }
124                 //! Clears the request list given to the constructor.
125                 ~RequestsClearer()
126                 {
127                     requests_->clear();
128                 }
129
130             private:
131                 RequestList    *requests_;
132         };
133
134         /*! \brief
135          * Creates a new selection collection.
136          *
137          * \throws  std::bad_alloc if out of memory.
138          */
139         explicit Impl(SelectionCollection *collection);
140
141         /*! \brief
142          * Assign selections from a list to pending requests.
143          *
144          * \param[in] selections  List of selections to assign.
145          * \throws    std::bad_alloc if out of memory.
146          * \throws    InvalidInputError if the assignment cannot be done
147          *      (see parseRequestedFromFile() for documented conditions).
148          *
149          * Loops through \p selections and the pending requests lists in order,
150          * and for each requests, assigns the first yet unassigned selections
151          * from the list.
152          */
153         void placeSelectionsInRequests(const SelectionList &selections);
154         /*! \brief
155          * Adds a request for each required option that is not yet set.
156          *
157          * \throws    std::bad_alloc if out of memory.
158          */
159         void requestUnsetRequiredOptions();
160
161         //! Selection collection to which selections are stored.
162         SelectionCollection    &collection_;
163         //! List of selection options (storage objects) this manager manages.
164         OptionList              options_;
165         //! List of selections requested for later parsing.
166         RequestList             requests_;
167 };
168
169 SelectionOptionManager::Impl::Impl(SelectionCollection *collection)
170     : collection_(*collection)
171 {
172 }
173
174 void SelectionOptionManager::Impl::placeSelectionsInRequests(
175         const SelectionList &selections)
176 {
177     if (requests_.empty())
178     {
179         requestUnsetRequiredOptions();
180     }
181
182     RequestsClearer               clearRequestsOnExit(&requests_);
183
184     SelectionList::const_iterator first = selections.begin();
185     SelectionList::const_iterator last  = first;
186     RequestList::const_iterator   i;
187     for (i = requests_.begin(); i != requests_.end(); ++i)
188     {
189         const SelectionRequest &request = *i;
190         if (request.count() > 0)
191         {
192             int remaining = selections.end() - first;
193             if (remaining < request.count())
194             {
195                 int assigned = first - selections.begin();
196                 GMX_THROW(InvalidInputError(formatString(
197                                                     "Too few selections provided for '%s': "
198                                                     "Expected %d selections, but only %d left "
199                                                     "after assigning the first %d to other selections.",
200                                                     request.name().c_str(), request.count(),
201                                                     remaining, assigned)));
202             }
203             last = first + request.count();
204         }
205         else
206         {
207             RequestList::const_iterator nextRequest = i;
208             ++nextRequest;
209             if (nextRequest != requests_.end())
210             {
211                 const char *name         = request.name().c_str();
212                 const char *conflictName = nextRequest->name().c_str();
213                 GMX_THROW(InvalidInputError(formatString(
214                                                     "Ambiguous selections for '%s' and '%s': "
215                                                     "Any number of selections is acceptable for "
216                                                     "'%s', but you have requested subsequent "
217                                                     "selections to be assigned to '%s'. "
218                                                     "Resolution for such cases is not implemented, "
219                                                     "and may be impossible.",
220                                                     name, conflictName, name, conflictName)));
221             }
222             last = selections.end();
223         }
224         SelectionList curr(first, last);
225         request.storage_->addSelections(curr, true);
226         first = last;
227     }
228     if (last != selections.end())
229     {
230         int count     = selections.end() - selections.begin();
231         int remaining = selections.end() - last;
232         int assigned  = last - selections.begin();
233         GMX_THROW(InvalidInputError(formatString(
234                                             "Too many selections provided: "
235                                             "Expected %d selections, but %d provided. "
236                                             "Last %d selections could not be assigned to any option.",
237                                             assigned, count, remaining)));
238     }
239 }
240
241 void SelectionOptionManager::Impl::requestUnsetRequiredOptions()
242 {
243     OptionList::const_iterator i;
244     for (i = options_.begin(); i != options_.end(); ++i)
245     {
246         SelectionOptionStorage &storage = **i;
247         if (storage.isRequired() && !storage.isSet())
248         {
249             requests_.push_back(SelectionRequest(&storage));
250         }
251     }
252 }
253
254
255 /********************************************************************
256  * SelectionOptionManager
257  */
258
259 SelectionOptionManager::SelectionOptionManager(SelectionCollection *collection)
260     : impl_(new Impl(collection))
261 {
262 }
263
264 SelectionOptionManager::~SelectionOptionManager()
265 {
266 }
267
268 void
269 SelectionOptionManager::registerOption(SelectionOptionStorage *storage)
270 {
271     impl_->requests_.reserve(impl_->options_.size() + 1);
272     impl_->options_.push_back(storage);
273 }
274
275 void
276 SelectionOptionManager::convertOptionValue(SelectionOptionStorage *storage,
277                                            const std::string      &value)
278 {
279     SelectionList selections = impl_->collection_.parseFromString(value);
280     storage->addSelections(selections, false);
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         if (bInteractive)
300         {
301             std::fprintf(stderr, "\nSpecify ");
302             if (request.count() < 0)
303             {
304                 std::fprintf(stderr, "any number of selections");
305             }
306             else if (request.count() == 1)
307             {
308                 std::fprintf(stderr, "a selection");
309             }
310             else
311             {
312                 std::fprintf(stderr, "%d selections", request.count());
313             }
314             std::fprintf(stderr, " for option '%s' (%s):\n",
315                          request.name().c_str(), request.description().c_str());
316             std::fprintf(stderr, "(one selection per line, 'help' for help%s)\n",
317                          request.count() < 0 ? ", Ctrl-D to end" : "");
318         }
319         SelectionList selections
320             = impl_->collection_.parseFromStdin(request.count(), bInteractive);
321         request.storage_->addSelections(selections, true);
322     }
323 }
324
325 void
326 SelectionOptionManager::parseRequestedFromFile(const std::string &filename)
327 {
328     SelectionList selections = impl_->collection_.parseFromFile(filename);
329     try
330     {
331         impl_->placeSelectionsInRequests(selections);
332     }
333     catch (GromacsException &ex)
334     {
335         ex.prependContext(formatString(
336                                   "Error in adding selections from file '%s'",
337                                   filename.c_str()));
338         throw;
339     }
340 }
341
342 void
343 SelectionOptionManager::parseRequestedFromString(const std::string &str)
344 {
345     SelectionList selections = impl_->collection_.parseFromString(str);
346     impl_->placeSelectionsInRequests(selections);
347 }
348
349 /********************************************************************
350  * Global functions
351  */
352
353 namespace
354 {
355
356 /*! \internal \brief
357  * Visitor that sets the manager for each selection option.
358  *
359  * \ingroup module_selection
360  */
361 class SelectionOptionManagerSetter : public OptionsModifyingVisitor
362 {
363     public:
364         //! Construct a visitor that sets given manager.
365         explicit SelectionOptionManagerSetter(SelectionOptionManager *manager)
366             : manager_(manager)
367         {
368         }
369
370         void visitSubSection(Options *section)
371         {
372             OptionsModifyingIterator iterator(section);
373             iterator.acceptSubSections(this);
374             iterator.acceptOptions(this);
375         }
376
377         void visitOption(OptionInfo *option)
378         {
379             SelectionOptionInfo *selOption
380                 = option->toType<SelectionOptionInfo>();
381             if (selOption != NULL)
382             {
383                 selOption->setManager(manager_);
384             }
385             SelectionFileOptionInfo *selFileOption
386                 = option->toType<SelectionFileOptionInfo>();
387             if (selFileOption != NULL)
388             {
389                 selFileOption->setManager(manager_);
390             }
391         }
392
393     private:
394         SelectionOptionManager *manager_;
395 };
396
397 }   // namespace
398
399 void setManagerForSelectionOptions(Options                *options,
400                                    SelectionOptionManager *manager)
401 {
402     SelectionOptionManagerSetter(manager).visitSubSection(options);
403 }
404
405 } // namespace gmx