SYCL: Avoid using no_init read accessor in rocFFT
[alexxy/gromacs.git] / src / gromacs / trajectoryanalysis / analysismodule.h
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.
5  * Copyright (c) 2015,2018,2019,2020,2021, by the GROMACS development team, led by
6  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
7  * and including many others, as listed in the AUTHORS file in the
8  * top-level source directory and at http://www.gromacs.org.
9  *
10  * GROMACS is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Lesser General Public License
12  * as published by the Free Software Foundation; either version 2.1
13  * of the License, or (at your option) any later version.
14  *
15  * GROMACS is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public
21  * License along with GROMACS; if not, see
22  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
23  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
24  *
25  * If you want to redistribute modifications to GROMACS, please
26  * consider that scientific software is very special. Version
27  * control is crucial - bugs must be traceable. We will be happy to
28  * consider code for inclusion in the official distribution, but
29  * derived work must not be called official GROMACS. Details are found
30  * in the README & COPYING files - if they are missing, get the
31  * official version at http://www.gromacs.org.
32  *
33  * To help us fund GROMACS development, we humbly ask that you cite
34  * the research papers on the package. Check out http://www.gromacs.org.
35  */
36 /*! \file
37  * \brief
38  * Declares gmx::TrajectoryAnalysisModule and
39  * gmx::TrajectoryAnalysisModuleData.
40  *
41  * \author Teemu Murtola <teemu.murtola@gmail.com>
42  * \inpublicapi
43  * \ingroup module_trajectoryanalysis
44  */
45 #ifndef GMX_TRAJECTORYANALYSIS_ANALYSISMODULE_H
46 #define GMX_TRAJECTORYANALYSIS_ANALYSISMODULE_H
47
48 #include <memory>
49 #include <string>
50 #include <vector>
51
52 #include "gromacs/selection/selection.h" // For gmx::SelectionList
53
54 struct t_pbc;
55 struct t_trxframe;
56
57 namespace gmx
58 {
59
60 class AbstractAnalysisData;
61 class AnalysisData;
62 class AnalysisDataHandle;
63 class AnalysisDataParallelOptions;
64 class IOptionsContainer;
65 class Options;
66 class SelectionCollection;
67 class TopologyInformation;
68 class TrajectoryAnalysisModule;
69 class TrajectoryAnalysisSettings;
70
71 /*! \brief
72  * Base class for thread-local data storage during trajectory analysis.
73  *
74  * Thread-local storage of data handles and selections is implemented in this
75  * class; TrajectoryAnalysisModule instances can access the thread-local values
76  * in their TrajectoryAnalysisModule::analyzeFrame() method using dataHandle()
77  * and parallelSelection().
78  *
79  * \see TrajectoryAnalysisModule::startFrames()
80  * \see TrajectoryAnalysisModule::analyzeFrame()
81  * \see TrajectoryAnalysisModule::finishFrames()
82  *
83  * \inpublicapi
84  * \ingroup module_trajectoryanalysis
85  */
86 class TrajectoryAnalysisModuleData
87 {
88 public:
89     virtual ~TrajectoryAnalysisModuleData();
90
91     /*! \brief
92      * Performs any finishing actions after all frames have been processed.
93      *
94      * \throws  unspecified Implementation may throw exceptions to indicate
95      *      errors.
96      *
97      * This function is called immediately before the destructor, after
98      * TrajectoryAnalysisModule::finishFrames().
99      * Derived classes should implement any final operations that need to
100      * be done after successful analysis.
101      * All implementations should call finishDataHandles().
102      */
103     virtual void finish() = 0;
104
105     /*! \brief
106      * Returns a data handle for a given dataset.
107      *
108      * \param[in] data  Analysis data object.
109      * \returns   Data handle for \p data stored in this thread-local data.
110      *
111      * \p data should have previously been registered with
112      * TrajectoryAnalysisModule::registerAnalysisDataset().
113      * If \p data has zero columns in all data sets, the returned data
114      * handle is invalid.
115      *
116      * Does not throw.
117      */
118     AnalysisDataHandle dataHandle(const AnalysisData& data);
119     /*! \brief
120      * Returns a selection that corresponds to the given selection.
121      *
122      * \param[in] selection Global selection object.
123      * \returns   Selection object corresponding to this thread-local data.
124      *
125      * \p selection is the selection object that was obtained from
126      * SelectionOption.  The return value is the corresponding selection
127      * in the selection collection with which this data object was
128      * constructed with.
129      *
130      * Does not throw.
131      */
132     Selection parallelSelection(const Selection& selection);
133     /*! \brief
134      * Returns a set of selection that corresponds to the given selections.
135      *
136      * \throws std::bad_alloc if out of memory.
137      *
138      * Works as parallelSelection(), but for a list of selections at once.
139      *
140      * \see parallelSelection()
141      */
142     SelectionList parallelSelections(const SelectionList& selections);
143
144 protected:
145     /*! \brief
146      * Initializes thread-local storage for data handles and selections.
147      *
148      * \param[in] module     Analysis module to use for data objects.
149      * \param[in] opt        Data parallelization options.
150      * \param[in] selections Thread-local selection collection.
151      * \throws  std::bad_alloc if out of memory.
152      * \throws  unspecified Can throw any exception thrown by
153      *      AnalysisData::startData().
154      *
155      * Calls AnalysisData::startData() on all data objects registered with
156      * TrajectoryAnalysisModule::registerAnalysisDataset() in \p module.
157      * The handles are accessible through dataHandle().
158      */
159     TrajectoryAnalysisModuleData(TrajectoryAnalysisModule*          module,
160                                  const AnalysisDataParallelOptions& opt,
161                                  const SelectionCollection&         selections);
162
163     /*! \brief
164      * Calls finishData() on all data handles.
165      *
166      * \throws  unspecified Can throw any exception thrown by
167      *      AnalysisDataHandle::finishData().
168      *
169      * This function should be called from the implementation of finish()
170      * in all subclasses.
171      */
172     void finishDataHandles();
173
174 private:
175     class Impl;
176
177     std::unique_ptr<Impl> impl_;
178 };
179
180 //! Smart pointer to manage a TrajectoryAnalysisModuleData object.
181 typedef std::unique_ptr<TrajectoryAnalysisModuleData> TrajectoryAnalysisModuleDataPointer;
182
183 /*! \brief
184  * Base class for trajectory analysis modules.
185  *
186  * Trajectory analysis methods should derive from this class and override the
187  * necessary virtual methods to implement initialization (initOptions(),
188  * optionsFinished(), initAnalysis(), initAfterFirstFrame()), per-frame analysis
189  * (analyzeFrame()), and final processing (finishFrames(), finishAnalysis(),
190  * writeOutput()).
191  *
192  * For parallel analysis using threads, only a single object is constructed,
193  * but the methods startFrames(), analyzeFrame() and finishFrames() are called
194  * in each thread.  Frame-local data should be initialized in startFrames() and
195  * stored in a class derived from TrajectoryAnalysisModuleData that is passed
196  * to the other methods.  The default implementation of startFrames() can be
197  * used if only data handles and selections need to be thread-local.
198  *
199  * To get the full benefit from this class,
200  * \ref module_analysisdata "analysis data objects" and
201  * \ref module_selection "selections" should be used in the implementation.
202  * See the corresponding modules' documentation for details of how they work.
203  *
204  * Typical way of using AnalysisData in derived classes is to have the
205  * AnalysisData object as a member variable and register it using
206  * registerAnalysisDataset().  Analysis modules are initialized in
207  * initAnalysis() and the processing chain is initialized.  If any of the
208  * modules is required, e.g., for post-processing in finishAnalysis(), it can
209  * be stored in a member variable.  To add data to the data object in
210  * analyzeFrame(), a data handle is obtained using
211  * TrajectoryAnalysisModuleData::dataHandle().
212  *
213  * Typical way of using selections in derived classes is to have the required
214  * \ref Selection objects (or ::SelectionList objects) as member variables, and
215  * add the required selection options in initOptions().  These member variables
216  * can be accessed in initAnalysis() to get general information about the
217  * selections.  In analyzeFrame(), these selection objects should not be used
218  * directly, but instead TrajectoryAnalysisModuleData::parallelSelection()
219  * should be used to obtain a selection object that works correctly also for
220  * parallel analysis.
221  *
222  * Derived classes should use exceptions to indicate errors in the virtual
223  * methods.
224  *
225  * \inpublicapi
226  * \ingroup module_trajectoryanalysis
227  */
228 class TrajectoryAnalysisModule
229 {
230 public:
231     virtual ~TrajectoryAnalysisModule();
232
233     /*! \brief
234      * Initializes options understood by the module.
235      *
236      * \param[in,out] options  Options object to add the options to.
237      * \param[in,out] settings Settings to pass to and from the module.
238      *
239      * This method is called first after the constructor, and it should
240      * add options understood by the module to \p options.  Output values
241      * from options (including selections) should be stored in member
242      * variables.
243      *
244      * In addition to initializing the options, this method can also
245      * provide information about the module's requirements using the
246      * \p settings object; see TrajectoryAnalysisSettings for more details.
247      *
248      * If settings depend on the option values provided by the user, see
249      * optionsFinished().
250      */
251     virtual void initOptions(IOptionsContainer* options, TrajectoryAnalysisSettings* settings) = 0;
252     /*! \brief
253      * Called after all option values have been set.
254      *
255      * \param[in,out] settings Settings to pass to and from the module.
256      *
257      * This method is called after option values have been assigned (but
258      * interactive selection input has not yet been performed).
259      *
260      * If the module needs to change settings that affect topology loading
261      * (can be done using the \p settings object) or selection
262      * initialization (can be done using SelectionOptionInfo) based on
263      * option values, this method has to be overridden.
264      *
265      * The default implementation does nothing.
266      */
267     virtual void optionsFinished(TrajectoryAnalysisSettings* settings);
268     /*! \brief
269      * Initializes the analysis.
270      *
271      * \param[in]    settings Settings to pass to and from the module.
272      * \param[in]    top      Topology information.
273      *
274      * When this function is called, selections have been initialized based
275      * on user input, and a topology has been loaded if provided by the
276      * user.  For dynamic selections, the selections have been evaluated to
277      * the largest possible selection, i.e., the selections passed to
278      * analyzeFrame() are always a subset of the selections provided here.
279      */
280     virtual void initAnalysis(const TrajectoryAnalysisSettings& settings,
281                               const TopologyInformation&        top) = 0;
282     /*! \brief
283      * Performs additional initialization after reading the first frame.
284      *
285      * When this function is called, selections are the same as in
286      * initAnalysis(), i.e., they have not been evaluated for the first
287      * frame.
288      *
289      * It is necessary to override this method only if the module needs to
290      * do initialization for which it requires data from the first frame.
291      *
292      * The default implementation does nothing.
293      */
294     virtual void initAfterFirstFrame(const TrajectoryAnalysisSettings& settings, const t_trxframe& fr);
295
296     /*! \brief
297      * Starts the analysis of frames.
298      *
299      * \param[in]  opt         Parallel options
300      * \param[in]  selections  Frame-local selection collection object.
301      * \returns    Data structure for thread-local data.
302      *
303      * This function is necessary only for threaded parallelization.
304      * It is called once for each thread and should initialize a class that
305      * contains any required frame-local data in the returned value.
306      * The default implementation creates a basic data structure that holds
307      * thread-local data handles for all data objects registered with
308      * registerAnalysisDataset(), as well as the thread-local selection
309      * collection.  These can be accessed in analyzeFrame() using the
310      * methods in TrajectoryAnalysisModuleData.
311      * If other thread-local data is needed, this function should be
312      * overridden and it should create an instance of a class derived from
313      * TrajectoryAnalysisModuleData.
314      *
315      * \see TrajectoryAnalysisModuleData
316      */
317     virtual TrajectoryAnalysisModuleDataPointer startFrames(const AnalysisDataParallelOptions& opt,
318                                                             const SelectionCollection& selections);
319     /*! \brief
320      * Analyzes a single frame.
321      *
322      * \param[in]     frnr   Frame number, a zero-based index that
323      *      uniquely identifies the frame.
324      * \param[in]     fr     Current frame.
325      * \param[in]     pbc    Periodic boundary conditions for \p fr.
326      * \param[in,out] pdata  Data structure for frame-local data.
327      *
328      * This method is called once for each frame to be analyzed, and should
329      * analyze the positions provided in the selections.  Data handles and
330      * selections should be obtained from the \p pdata structure.
331      *
332      * For threaded analysis, this method is called asynchronously in
333      * different threads to analyze different frames.  The \p pdata
334      * structure is one of the structures created with startFrames(),
335      * but no assumptions should be made about which of these data
336      * structures is used.  It is guaranteed that two instances of
337      * analyzeFrame() are not running concurrently with the same \p pdata
338      * data structure.
339      * Any access to data structures not stored in \p pdata should be
340      * designed to be thread-safe.
341      */
342     virtual void analyzeFrame(int frnr, const t_trxframe& fr, t_pbc* pbc, TrajectoryAnalysisModuleData* pdata) = 0;
343     /*! \brief
344      * Finishes the analysis of frames.
345      *
346      * \param[in]  pdata    Data structure for thread-local data.
347      *
348      * This method is called once for each call of startFrames(), with the
349      * data structure returned by the corresponding startFrames().
350      * The \p pdata object should be destroyed by the caller after this
351      * function has been called.
352      *
353      * You only need to override this method if you need custom
354      * operations to combine data from the frame-local data structures
355      * to get the final result.  In such cases, the data should be
356      * aggregated in this function and stored in a member attribute.
357      *
358      * The default implementation does nothing.
359      *
360      * \see startFrames()
361      */
362     virtual void finishFrames(TrajectoryAnalysisModuleData* pdata);
363
364     /*! \brief
365      * Postprocesses data after frames have been read.
366      *
367      * \param[in]  nframes  Total number of frames processed.
368      *
369      * This function is called after all finishFrames() calls have been
370      * called.
371      * \p nframes will equal the number of calls to analyzeFrame() that
372      * have occurred.
373      */
374     virtual void finishAnalysis(int nframes) = 0;
375     /*! \brief
376      * Writes output into files and/or standard output/error.
377      *
378      * All output from the module, excluding data written out for each
379      * frame during analyzeFrame(), should be confined into this function.
380      * This function is guaranteed to be called only after
381      * finishAnalysis().
382      */
383     virtual void writeOutput() = 0;
384
385     /*! \brief
386      * Returns the number of datasets provided by the module.
387      *
388      * Does not throw.
389      */
390     int datasetCount() const;
391     /*! \brief
392      * Returns a vector with the names of datasets provided by the module.
393      *
394      * Does not throw.
395      */
396     const std::vector<std::string>& datasetNames() const;
397     /*! \brief
398      * Returns a pointer to the data set \p index.
399      *
400      * \param[in] index  Data set to query for.
401      * \returns   Reference to the requested data set.
402      * \throws    APIError if \p index is not valid.
403      *
404      * \p index should be >= 0 and < datasetCount().
405      *
406      * The return value is not const to allow callers to add modules to the
407      * data sets. However, the AbstractAnalysisData interface does not
408      * provide any means to alter the data, so the module does not need to
409      * care about external modifications.
410      */
411     AbstractAnalysisData& datasetFromIndex(int index) const;
412     /*! \brief
413      * Returns a pointer to the data set with name \p name
414      *
415      * \param[in] name  Data set to query for.
416      * \returns   Reference to the requested data set.
417      * \throws    APIError if \p name is not valid.
418      *
419      * \p name should be one of the names returned by datasetNames().
420      *
421      * The return value is not const to allow callers to add modules to the
422      * data sets. However, the AbstractAnalysisData interface does not
423      * provide any means to alter the data, so the module does not need to
424      * care about external modifications.
425      */
426     AbstractAnalysisData& datasetFromName(const char* name) const;
427     /*! \brief
428      * Processes data in AnalysisData objects in serial for each frame.
429      *
430      * \param[in] frameIndex  Index of the frame that has been finished.
431      *
432      * This method is called by the framework in order for each frame,
433      * after the analysis for that frame has been finished.  These calls
434      * always execute in serial and in sequential frame order, even during
435      * parallel analysis where multiple analyzeFrame() calls may be
436      * executing concurrently.
437      *
438      * \see AnalysisData::finishFrameSerial()
439      */
440     void finishFrameSerial(int frameIndex);
441
442 protected:
443     /*! \brief
444      * Initializes the dataset registration mechanism.
445      *
446      * \throws    std::bad_alloc if out of memory.
447      */
448     TrajectoryAnalysisModule();
449
450     /*! \brief
451      * Registers a dataset that exports data.
452      *
453      * \param     data  Data object to register.
454      * \param[in] name  Name to register the dataset with.
455      * \throws    std::bad_alloc if out of memory.
456      *
457      * Registers \p data as a dataset that provides output from the
458      * analysis module.  Callers for the module can access the dataset
459      * with datasetFromName() using \p name as an AbstractAnalysisData
460      * object.  This allows them to add their own data modules to do extra
461      * processing.
462      *
463      * \p name must be unique across all calls within the same
464      * TrajectoryAnalysisModule instance.
465      */
466     void registerBasicDataset(AbstractAnalysisData* data, const char* name);
467     /*! \brief
468      * Registers a parallelized dataset that exports data.
469      *
470      * \param     data  AnalysisData object to register.
471      * \param[in] name  Name to register the dataset with.
472      * \throws    std::bad_alloc if out of memory.
473      *
474      * This method works as registerBasicDataset(), but additionally allows
475      * data handles for \p data to be accessed using
476      * TrajectoryAnalysisData.
477      *
478      * \see registerBasicDataset()
479      */
480     void registerAnalysisDataset(AnalysisData* data, const char* name);
481
482 private:
483     class Impl;
484
485     std::unique_ptr<Impl> impl_;
486
487     /*! \brief
488      * Needed to access the registered analysis data sets.
489      */
490     friend class TrajectoryAnalysisModuleData;
491 };
492
493 //! Smart pointer to manage a TrajectoryAnalysisModule.
494 typedef std::unique_ptr<TrajectoryAnalysisModule> TrajectoryAnalysisModulePointer;
495
496 } // namespace gmx
497
498 #endif