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