Merge branch release-4-6 into release-5-0
[alexxy/gromacs.git] / src / gromacs / analysisdata / datamodulemanager.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
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.
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::AnalysisDataModuleManager.
38  *
39  * \author Teemu Murtola <teemu.murtola@gmail.com>
40  * \ingroup module_analysisdata
41  */
42 #include "gromacs/analysisdata/datamodulemanager.h"
43
44 #include <vector>
45
46 #include "gromacs/analysisdata/abstractdata.h"
47 #include "gromacs/analysisdata/dataframe.h"
48 #include "gromacs/analysisdata/datamodule.h"
49 #include "gromacs/analysisdata/paralleloptions.h"
50 #include "gromacs/utility/exceptions.h"
51 #include "gromacs/utility/gmxassert.h"
52
53 namespace gmx
54 {
55
56 /********************************************************************
57  * AnalysisDataModuleManager::Impl
58  */
59
60 /*! \internal \brief
61  * Private implementation class for AnalysisDataModuleManager.
62  *
63  * \ingroup module_analysisdata
64  */
65 class AnalysisDataModuleManager::Impl
66 {
67     public:
68         //! Stores information about an attached module.
69         struct ModuleInfo
70         {
71             //! Initializes the module information.
72             explicit ModuleInfo(AnalysisDataModulePointer module)
73                 : module(module), bParallel(false)
74             {
75             }
76
77             //! Pointer to the actual module.
78             AnalysisDataModulePointer   module;
79             //! Whether the module supports parallel processing.
80             bool                        bParallel;
81         };
82
83         //! Shorthand for list of modules added to the data.
84         typedef std::vector<ModuleInfo> ModuleList;
85
86         //! Describes the current state of the notification methods.
87         enum State
88         {
89             eNotStarted, //!< Initial state (nothing called).
90             eInData,     //!< notifyDataStart() called, no frame in progress.
91             eInFrame,    //!< notifyFrameStart() called, but notifyFrameFinish() not.
92             eFinished    //!< notifyDataFinish() called.
93         };
94
95         Impl();
96
97         /*! \brief
98          * Checks whether a module is compatible with a given data property.
99          *
100          * \param[in] module   Module to check.
101          * \param[in] property Property to check.
102          * \param[in] bSet     Value of the property to check against.
103          * \throws    APIError if \p module is not compatible with the data.
104          */
105         void checkModuleProperty(const AnalysisDataModuleInterface &module,
106                                  DataProperty property, bool bSet) const;
107         /*! \brief
108          * Checks whether a module is compatible with the data properties.
109          *
110          * \param[in] module Module to check.
111          * \throws    APIError if \p module is not compatible with the data.
112          *
113          * Does not currently check the actual data (e.g., missing values), but
114          * only the dimensionality and other preset properties of the data.
115          */
116         void checkModuleProperties(const AnalysisDataModuleInterface &module) const;
117
118         /*! \brief
119          * Present data already added to the data object to a module.
120          *
121          * \param[in] data   Data object to read data from.
122          * \param[in] module Module to present the data to.
123          * \throws    APIError if \p module is not compatible with the data.
124          * \throws    APIError if all data is not available through
125          *      getDataFrame().
126          * \throws    unspecified Any exception thrown by \p module in its data
127          *      notification methods.
128          *
129          * Uses getDataFrame() in \p data to access all data in the object, and
130          * calls the notification functions in \p module as if the module had
131          * been registered to the data object when the data was added.
132          */
133         void presentData(AbstractAnalysisData        *data,
134                          AnalysisDataModuleInterface *module);
135
136         //! List of modules added to the data.
137         ModuleList              modules_;
138         //! Properties of the owning data for module checking.
139         bool                    bDataProperty_[eDataPropertyNR];
140         //! true if all modules support missing data.
141         bool                    bAllowMissing_;
142         //! true if there are modules that do not support parallel processing.
143         bool                    bSerialModules_;
144         //! true if there are modules that support parallel processing.
145         bool                    bParallelModules_;
146
147         /*! \brief
148          * Current state of the notification methods.
149          *
150          * This is used together with \a currIndex_ for sanity checks on the
151          * input data; invalid call sequences trigger asserts.
152          * The state of these variables does not otherwise affect the behavior
153          * of this class; this is the reason they can be changed in const
154          * methods.
155          */
156         //! Whether notifyDataStart() has been called.
157         mutable State           state_;
158         //! Index of currently active frame or the next frame if not in frame.
159         mutable int             currIndex_;
160 };
161
162 AnalysisDataModuleManager::Impl::Impl()
163     : bAllowMissing_(true), bSerialModules_(false), bParallelModules_(false),
164       state_(eNotStarted), currIndex_(0)
165 {
166     // This must be in sync with how AbstractAnalysisData is actually
167     // initialized.
168     for (int i = 0; i < eDataPropertyNR; ++i)
169     {
170         bDataProperty_[i] = false;
171     }
172 }
173
174 void
175 AnalysisDataModuleManager::Impl::checkModuleProperty(
176         const AnalysisDataModuleInterface &module,
177         DataProperty property, bool bSet) const
178 {
179     bool      bOk   = true;
180     const int flags = module.flags();
181     switch (property)
182     {
183         case eMultipleDataSets:
184             if (bSet && !(flags & AnalysisDataModuleInterface::efAllowMultipleDataSets))
185             {
186                 bOk = false;
187             }
188             break;
189         case eMultipleColumns:
190             if (bSet && !(flags & AnalysisDataModuleInterface::efAllowMulticolumn))
191             {
192                 bOk = false;
193             }
194             break;
195         case eMultipoint:
196             if ((bSet && !(flags & AnalysisDataModuleInterface::efAllowMultipoint))
197                 || (!bSet && (flags & AnalysisDataModuleInterface::efOnlyMultipoint)))
198             {
199                 bOk = false;
200             }
201             break;
202         default:
203             GMX_RELEASE_ASSERT(false, "Invalid data property enumeration");
204     }
205     if (!bOk)
206     {
207         GMX_THROW(APIError("Data module not compatible with data object properties"));
208     }
209 }
210
211 void
212 AnalysisDataModuleManager::Impl::checkModuleProperties(
213         const AnalysisDataModuleInterface &module) const
214 {
215     for (int i = 0; i < eDataPropertyNR; ++i)
216     {
217         checkModuleProperty(module, static_cast<DataProperty>(i), bDataProperty_[i]);
218     }
219 }
220
221 void
222 AnalysisDataModuleManager::Impl::presentData(AbstractAnalysisData        *data,
223                                              AnalysisDataModuleInterface *module)
224 {
225     if (state_ == eNotStarted)
226     {
227         return;
228     }
229     GMX_RELEASE_ASSERT(state_ != eInFrame,
230                        "Cannot apply a modules in mid-frame");
231     module->dataStarted(data);
232     const bool bCheckMissing = bAllowMissing_
233         && !(module->flags() & AnalysisDataModuleInterface::efAllowMissing);
234     for (int i = 0; i < data->frameCount(); ++i)
235     {
236         AnalysisDataFrameRef frame = data->getDataFrame(i);
237         GMX_RELEASE_ASSERT(frame.isValid(), "Invalid data frame returned");
238         // TODO: Check all frames before doing anything for slightly better
239         // exception behavior.
240         if (bCheckMissing && !frame.allPresent())
241         {
242             GMX_THROW(APIError("Missing data not supported by a module"));
243         }
244         module->frameStarted(frame.header());
245         for (int j = 0; j < frame.pointSetCount(); ++j)
246         {
247             module->pointsAdded(frame.pointSet(j));
248         }
249         module->frameFinished(frame.header());
250     }
251     if (state_ == eFinished)
252     {
253         module->dataFinished();
254     }
255 }
256
257 /********************************************************************
258  * AnalysisDataModuleManager
259  */
260
261 AnalysisDataModuleManager::AnalysisDataModuleManager()
262     : impl_(new Impl())
263 {
264 }
265
266 AnalysisDataModuleManager::~AnalysisDataModuleManager()
267 {
268 }
269
270 void
271 AnalysisDataModuleManager::dataPropertyAboutToChange(DataProperty property, bool bSet)
272 {
273     GMX_RELEASE_ASSERT(impl_->state_ == Impl::eNotStarted,
274                        "Cannot change data properties after data has been started");
275     if (impl_->bDataProperty_[property] != bSet)
276     {
277         Impl::ModuleList::const_iterator i;
278         for (i = impl_->modules_.begin(); i != impl_->modules_.end(); ++i)
279         {
280             impl_->checkModuleProperty(*i->module, property, bSet);
281         }
282         impl_->bDataProperty_[property] = bSet;
283     }
284 }
285
286 void
287 AnalysisDataModuleManager::addModule(AbstractAnalysisData      *data,
288                                      AnalysisDataModulePointer  module)
289 {
290     impl_->checkModuleProperties(*module);
291     // TODO: Ensure that the system does not end up in an inconsistent state by
292     // adding a module in mid-data during parallel processing (probably best to
293     // prevent alltogether).
294     GMX_RELEASE_ASSERT(impl_->state_ != Impl::eInFrame,
295                        "Cannot add a data module in mid-frame");
296     impl_->presentData(data, module.get());
297
298     if (!(module->flags() & AnalysisDataModuleInterface::efAllowMissing))
299     {
300         impl_->bAllowMissing_ = false;
301     }
302     impl_->modules_.push_back(Impl::ModuleInfo(module));
303 }
304
305 void
306 AnalysisDataModuleManager::applyModule(AbstractAnalysisData        *data,
307                                        AnalysisDataModuleInterface *module)
308 {
309     impl_->checkModuleProperties(*module);
310     GMX_RELEASE_ASSERT(impl_->state_ == Impl::eFinished,
311                        "Data module can only be applied to ready data");
312     impl_->presentData(data, module);
313 }
314
315
316 bool
317 AnalysisDataModuleManager::hasSerialModules() const
318 {
319     GMX_ASSERT(impl_->state_ != Impl::eNotStarted,
320                "Module state not accessible before data is started");
321     return impl_->bSerialModules_;
322 }
323
324
325 void
326 AnalysisDataModuleManager::notifyDataStart(AbstractAnalysisData *data)
327 {
328     GMX_RELEASE_ASSERT(impl_->state_ == Impl::eNotStarted,
329                        "notifyDataStart() called more than once");
330     for (int d = 0; d < data->dataSetCount(); ++d)
331     {
332         GMX_RELEASE_ASSERT(data->columnCount(d) > 0,
333                            "Data column count is not set");
334     }
335     impl_->state_            = Impl::eInData;
336     impl_->bSerialModules_   = !impl_->modules_.empty();
337     impl_->bParallelModules_ = false;
338
339     Impl::ModuleList::const_iterator i;
340     for (i = impl_->modules_.begin(); i != impl_->modules_.end(); ++i)
341     {
342         // This should not fail, since addModule() and
343         // dataPropertyAboutToChange() already do the checks, but kept here to
344         // catch potential bugs (perhaps it would be best to assert on failure).
345         impl_->checkModuleProperties(*i->module);
346         i->module->dataStarted(data);
347     }
348 }
349
350
351 void
352 AnalysisDataModuleManager::notifyParallelDataStart(
353         AbstractAnalysisData              *data,
354         const AnalysisDataParallelOptions &options)
355 {
356     GMX_RELEASE_ASSERT(impl_->state_ == Impl::eNotStarted,
357                        "notifyDataStart() called more than once");
358     for (int d = 0; d < data->dataSetCount(); ++d)
359     {
360         GMX_RELEASE_ASSERT(data->columnCount(d) > 0,
361                            "Data column count is not set");
362     }
363     impl_->state_            = Impl::eInData;
364     impl_->bSerialModules_   = false;
365     impl_->bParallelModules_ = false;
366
367     Impl::ModuleList::iterator i;
368     for (i = impl_->modules_.begin(); i != impl_->modules_.end(); ++i)
369     {
370         // This should not fail, since addModule() and
371         // dataPropertyAboutToChange() already do the checks, but kept here to
372         // catch potential bugs (perhaps it would be best to assert on failure).
373         impl_->checkModuleProperties(*i->module);
374         i->bParallel = i->module->parallelDataStarted(data, options);
375         if (i->bParallel)
376         {
377             impl_->bParallelModules_ = true;
378         }
379         else
380         {
381             impl_->bSerialModules_ = true;
382         }
383     }
384 }
385
386
387 void
388 AnalysisDataModuleManager::notifyFrameStart(const AnalysisDataFrameHeader &header) const
389 {
390     GMX_ASSERT(impl_->state_ == Impl::eInData, "Invalid call sequence");
391     GMX_ASSERT(header.index() == impl_->currIndex_, "Out of order frames");
392     impl_->state_     = Impl::eInFrame;
393
394     if (impl_->bSerialModules_)
395     {
396         Impl::ModuleList::const_iterator i;
397         for (i = impl_->modules_.begin(); i != impl_->modules_.end(); ++i)
398         {
399             if (!i->bParallel)
400             {
401                 i->module->frameStarted(header);
402             }
403         }
404     }
405 }
406
407 void
408 AnalysisDataModuleManager::notifyParallelFrameStart(
409         const AnalysisDataFrameHeader &header) const
410 {
411     if (impl_->bParallelModules_)
412     {
413         Impl::ModuleList::const_iterator i;
414         for (i = impl_->modules_.begin(); i != impl_->modules_.end(); ++i)
415         {
416             if (i->bParallel)
417             {
418                 i->module->frameStarted(header);
419             }
420         }
421     }
422 }
423
424
425 void
426 AnalysisDataModuleManager::notifyPointsAdd(const AnalysisDataPointSetRef &points) const
427 {
428     GMX_ASSERT(impl_->state_ == Impl::eInFrame, "notifyFrameStart() not called");
429     // TODO: Add checks for column spans (requires passing the information
430     // about the column counts from somewhere).
431     //GMX_ASSERT(points.lastColumn() < columnCount(points.dataSetIndex()),
432     //           "Invalid columns");
433     GMX_ASSERT(points.frameIndex() == impl_->currIndex_,
434                "Points do not correspond to current frame");
435     if (impl_->bSerialModules_)
436     {
437         if (!impl_->bAllowMissing_ && !points.allPresent())
438         {
439             GMX_THROW(APIError("Missing data not supported by a module"));
440         }
441
442         Impl::ModuleList::const_iterator i;
443         for (i = impl_->modules_.begin(); i != impl_->modules_.end(); ++i)
444         {
445             if (!i->bParallel)
446             {
447                 i->module->pointsAdded(points);
448             }
449         }
450     }
451 }
452
453
454 void
455 AnalysisDataModuleManager::notifyParallelPointsAdd(
456         const AnalysisDataPointSetRef &points) const
457 {
458     // TODO: Add checks for column spans (requires passing the information
459     // about the column counts from somewhere).
460     //GMX_ASSERT(points.lastColumn() < columnCount(points.dataSetIndex()),
461     //           "Invalid columns");
462     if (impl_->bParallelModules_)
463     {
464         if (!impl_->bAllowMissing_ && !points.allPresent())
465         {
466             GMX_THROW(APIError("Missing data not supported by a module"));
467         }
468
469         Impl::ModuleList::const_iterator i;
470         for (i = impl_->modules_.begin(); i != impl_->modules_.end(); ++i)
471         {
472             if (i->bParallel)
473             {
474                 i->module->pointsAdded(points);
475             }
476         }
477     }
478 }
479
480
481 void
482 AnalysisDataModuleManager::notifyFrameFinish(const AnalysisDataFrameHeader &header) const
483 {
484     GMX_ASSERT(impl_->state_ == Impl::eInFrame, "notifyFrameStart() not called");
485     GMX_ASSERT(header.index() == impl_->currIndex_,
486                "Header does not correspond to current frame");
487     // TODO: Add a check for the frame count in the source data including this
488     // frame.
489     impl_->state_ = Impl::eInData;
490     ++impl_->currIndex_;
491
492     if (impl_->bSerialModules_)
493     {
494         Impl::ModuleList::const_iterator i;
495         for (i = impl_->modules_.begin(); i != impl_->modules_.end(); ++i)
496         {
497             if (!i->bParallel)
498             {
499                 i->module->frameFinished(header);
500             }
501         }
502     }
503 }
504
505
506 void
507 AnalysisDataModuleManager::notifyParallelFrameFinish(
508         const AnalysisDataFrameHeader &header) const
509 {
510     if (impl_->bParallelModules_)
511     {
512         Impl::ModuleList::const_iterator i;
513         for (i = impl_->modules_.begin(); i != impl_->modules_.end(); ++i)
514         {
515             if (i->bParallel)
516             {
517                 i->module->frameFinished(header);
518             }
519         }
520     }
521 }
522
523
524 void
525 AnalysisDataModuleManager::notifyDataFinish() const
526 {
527     GMX_RELEASE_ASSERT(impl_->state_ == Impl::eInData, "Invalid call sequence");
528     impl_->state_ = Impl::eFinished;
529
530     Impl::ModuleList::const_iterator i;
531     for (i = impl_->modules_.begin(); i != impl_->modules_.end(); ++i)
532     {
533         i->module->dataFinished();
534     }
535 }
536
537 } // namespace gmx