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