Merge "Merge remote-tracking branch 'origin/release-4-6'"
[alexxy/gromacs.git] / src / gromacs / analysisdata / modules / plot.cpp
1 /*
2  *
3  *                This source code is part of
4  *
5  *                 G   R   O   M   A   C   S
6  *
7  *          GROningen MAchine for Chemical Simulations
8  *
9  * Written by David van der Spoel, Erik Lindahl, Berk Hess, and others.
10  * Copyright (c) 1991-2000, University of Groningen, The Netherlands.
11  * Copyright (c) 2001-2009, The GROMACS development team,
12  * check out http://www.gromacs.org for more information.
13
14  * This program is free software; you can redistribute it and/or
15  * modify it under the terms of the GNU General Public License
16  * as published by the Free Software Foundation; either version 2
17  * of the License, or (at your option) any later version.
18  *
19  * If you want to redistribute modifications, please consider that
20  * scientific software is very special. Version control is crucial -
21  * bugs must be traceable. We will be happy to consider code for
22  * inclusion in the official distribution, but derived work must not
23  * be called official GROMACS. Details are found in the README & COPYING
24  * files - if they are missing, get the official version at www.gromacs.org.
25  *
26  * To help us fund GROMACS development, we humbly ask that you cite
27  * the papers on the package - you can find them in the top README file.
28  *
29  * For more info, check our website at http://www.gromacs.org
30  */
31 /*! \internal \file
32  * \brief
33  * Implements classes in plot.h.
34  *
35  * \ingroup module_analysisdata
36  * \author Teemu Murtola <teemu.murtola@cbr.su.se>
37  */
38 #include "gromacs/analysisdata/modules/plot.h"
39
40 #ifdef HAVE_CONFIG_H
41 #include <config.h>
42 #endif
43
44 #include <string>
45 #include <vector>
46
47 #include <cstdio>
48 #include <cstring>
49
50 #include <boost/shared_ptr.hpp>
51
52 #include "gromacs/legacyheaders/gmxfio.h"
53 #include "gromacs/legacyheaders/oenv.h"
54 #include "gromacs/legacyheaders/vec.h"
55 #include "gromacs/legacyheaders/xvgr.h"
56
57 #include "gromacs/options/basicoptions.h"
58 #include "gromacs/analysisdata/dataframe.h"
59 #include "gromacs/options/options.h"
60 #include "gromacs/options/timeunitmanager.h"
61 #include "gromacs/selection/selectioncollection.h"
62 #include "gromacs/utility/exceptions.h"
63 #include "gromacs/utility/gmxassert.h"
64 #include "gromacs/utility/stringutil.h"
65
66 static const char *const g_plotFormats[] = {
67     "none", "xmgrace", "xmgr", NULL
68 };
69
70 namespace gmx
71 {
72
73 /********************************************************************
74  * AnalysisDataPlotSettings
75  */
76
77 AnalysisDataPlotSettings::AnalysisDataPlotSettings()
78     : selections_(NULL), timeUnit_(eTimeUnit_ps), plotFormat_(1)
79 {
80 }
81
82 void
83 AnalysisDataPlotSettings::setSelectionCollection(const SelectionCollection *selections)
84 {
85     selections_ = selections;
86 }
87
88
89 void
90 AnalysisDataPlotSettings::addOptions(Options *options)
91 {
92     options->addOption(StringOption("xvg").enumValue(g_plotFormats)
93                            .defaultValue("xmgrace")
94                            .storeEnumIndex(&plotFormat_)
95                            .description("Plot formatting"));
96 }
97
98
99 /********************************************************************
100  * AbstractPlotModule::Impl
101  */
102
103 class AbstractPlotModule::Impl
104 {
105     public:
106         explicit Impl(const AnalysisDataPlotSettings &settings);
107         ~Impl();
108
109         void closeFile();
110
111         AnalysisDataPlotSettings settings_;
112         std::string             filename_;
113         FILE                   *fp_;
114
115         bool                    bPlain_;
116         bool                    gOmitX_;
117         std::string             title_;
118         std::string             subtitle_;
119         std::string             xlabel_;
120         std::string             ylabel_;
121         std::vector<std::string>  legend_;
122         char                    xformat_[15];
123         char                    yformat_[15];
124         real                    xscale_;
125 };
126
127 AbstractPlotModule::Impl::Impl(const AnalysisDataPlotSettings &settings)
128     : settings_(settings), fp_(NULL), bPlain_(false), gOmitX_(false),
129       xscale_(1.0)
130 {
131     strcpy(xformat_, "%11.3f");
132     strcpy(yformat_, " %8.3f");
133 }
134
135 AbstractPlotModule::Impl::~Impl()
136 {
137     closeFile();
138 }
139
140
141 void
142 AbstractPlotModule::Impl::closeFile()
143 {
144     if (fp_ != NULL)
145     {
146         if (bPlain_)
147         {
148             gmx_fio_fclose(fp_);
149         }
150         else
151         {
152             xvgrclose(fp_);
153         }
154         fp_ = NULL;
155     }
156 }
157
158
159 /********************************************************************
160  * AbstractPlotModule
161  */
162 /*! \cond libapi */
163 AbstractPlotModule::AbstractPlotModule()
164     : impl_(new Impl(AnalysisDataPlotSettings()))
165 {
166 }
167
168 AbstractPlotModule::AbstractPlotModule(const AnalysisDataPlotSettings &settings)
169     : impl_(new Impl(settings))
170 {
171 }
172 //! \endcond
173
174 AbstractPlotModule::~AbstractPlotModule()
175 {
176 }
177
178
179 void
180 AbstractPlotModule::setSettings(const AnalysisDataPlotSettings &settings)
181 {
182     impl_->settings_ = settings;
183 }
184
185
186 void
187 AbstractPlotModule::setFileName(const std::string &filename)
188 {
189     impl_->filename_ = filename;
190 }
191
192
193 void
194 AbstractPlotModule::setPlainOutput(bool bPlain)
195 {
196     impl_->bPlain_ = bPlain;
197 }
198
199
200 void
201 AbstractPlotModule::setOmitX(bool bOmitX)
202 {
203     impl_->gOmitX_ = bOmitX;
204 }
205
206
207 void
208 AbstractPlotModule::setTitle(const char *title)
209 {
210     impl_->title_ = title;
211 }
212
213
214 void
215 AbstractPlotModule::setSubtitle(const char *subtitle)
216 {
217     impl_->subtitle_ = subtitle;
218 }
219
220
221 void
222 AbstractPlotModule::setXLabel(const char *label)
223 {
224     impl_->xlabel_ = label;
225 }
226
227
228 void
229 AbstractPlotModule::setXAxisIsTime()
230 {
231     TimeUnitManager manager(impl_->settings_.timeUnit());
232     impl_->xlabel_ = formatString("Time (%s)", manager.timeUnitAsString());
233     impl_->xscale_ = manager.inverseTimeScaleFactor();
234 }
235
236
237 void
238 AbstractPlotModule::setYLabel(const char *label)
239 {
240     impl_->ylabel_ = label;
241 }
242
243
244 void
245 AbstractPlotModule::setLegend(int nsets, const char * const *setname)
246 {
247     impl_->legend_.reserve(impl_->legend_.size() + nsets);
248     for (int i = 0; i < nsets; ++i)
249     {
250         appendLegend(setname[i]);
251     }
252 }
253
254
255 void
256 AbstractPlotModule::appendLegend(const char *setname)
257 {
258     impl_->legend_.push_back(setname);
259 }
260
261
262 void
263 AbstractPlotModule::setXFormat(int width, int precision, char format)
264 {
265     GMX_RELEASE_ASSERT(width >= 0 && precision >= 0
266                        && width <= 99 && precision <= 99,
267                        "Invalid width or precision");
268     GMX_RELEASE_ASSERT(strchr("eEfFgG", format) != NULL,
269                        "Invalid format specifier");
270     sprintf(impl_->xformat_, "%%%d.%d%c", width, precision, format);
271 }
272
273
274 void
275 AbstractPlotModule::setYFormat(int width, int precision, char format)
276 {
277     GMX_RELEASE_ASSERT(width >= 0 && precision >= 0
278                        && width <= 99 && precision <= 99,
279                        "Invalid width or precision");
280     GMX_RELEASE_ASSERT(strchr("eEfFgG", format) != NULL,
281                        "Invalid format specifier");
282     sprintf(impl_->yformat_, " %%%d.%d%c", width, precision, format);
283 }
284
285
286 int
287 AbstractPlotModule::flags() const
288 {
289     return efAllowMulticolumn | efAllowMultipoint;
290 }
291
292
293 void
294 AbstractPlotModule::dataStarted(AbstractAnalysisData *data)
295 {
296     if (!impl_->filename_.empty())
297     {
298         if (impl_->bPlain_)
299         {
300             impl_->fp_ = gmx_fio_fopen(impl_->filename_.c_str(), "w");
301         }
302         else
303         {
304             time_unit_t time_unit
305                 = static_cast<time_unit_t>(impl_->settings_.timeUnit() + 1);
306             xvg_format_t xvg_format
307                 = (impl_->settings_.plotFormat() > 0
308                     ? static_cast<xvg_format_t>(impl_->settings_.plotFormat())
309                     : exvgNONE);
310             output_env_t oenv;
311             output_env_init(&oenv, 0, NULL, time_unit, FALSE, xvg_format, 0, 0);
312             boost::shared_ptr<output_env> oenvGuard(oenv, &output_env_done);
313             impl_->fp_ = xvgropen(impl_->filename_.c_str(), impl_->title_.c_str(),
314                                   impl_->xlabel_.c_str(), impl_->ylabel_.c_str(),
315                                   oenv);
316             const SelectionCollection *selections
317                 = impl_->settings_.selectionCollection();
318             if (selections != NULL)
319             {
320                 selections->printXvgrInfo(impl_->fp_, oenv);
321             }
322             if (!impl_->subtitle_.empty())
323             {
324                 xvgr_subtitle(impl_->fp_, impl_->subtitle_.c_str(), oenv);
325             }
326             if (output_env_get_print_xvgr_codes(oenv)
327                 && !impl_->legend_.empty())
328             {
329                 std::vector<const char *> legend;
330                 legend.reserve(impl_->legend_.size());
331                 for (size_t i = 0; i < impl_->legend_.size(); ++i)
332                 {
333                     legend.push_back(impl_->legend_[i].c_str());
334                 }
335                 xvgr_legend(impl_->fp_, legend.size(), &legend[0], oenv);
336             }
337         }
338     }
339 }
340
341
342 void
343 AbstractPlotModule::frameStarted(const AnalysisDataFrameHeader &frame)
344 {
345     if (!isFileOpen())
346     {
347         return;
348     }
349     if (!impl_->gOmitX_)
350     {
351         std::fprintf(impl_->fp_, impl_->xformat_, frame.x() * impl_->xscale_);
352     }
353 }
354
355
356 void
357 AbstractPlotModule::frameFinished(const AnalysisDataFrameHeader & /*header*/)
358 {
359     if (!isFileOpen())
360     {
361         return;
362     }
363     std::fprintf(impl_->fp_, "\n");
364 }
365
366
367 void
368 AbstractPlotModule::dataFinished()
369 {
370     impl_->closeFile();
371 }
372
373 /*! \cond libapi */
374 bool
375 AbstractPlotModule::isFileOpen() const
376 {
377     return impl_->fp_ != NULL;
378 }
379
380
381 void
382 AbstractPlotModule::writeValue(real value) const
383 {
384     GMX_ASSERT(isFileOpen(), "File not opened, but write attempted");
385     std::fprintf(impl_->fp_, impl_->yformat_, value);
386 }
387 //! \endcond
388
389 /********************************************************************
390  * DataPlotModule
391  */
392
393 AnalysisDataPlotModule::AnalysisDataPlotModule()
394 {
395 }
396
397 AnalysisDataPlotModule::AnalysisDataPlotModule(
398         const AnalysisDataPlotSettings &settings)
399     : AbstractPlotModule(settings)
400 {
401 }
402
403
404 void
405 AnalysisDataPlotModule::pointsAdded(const AnalysisDataPointSetRef &points)
406 {
407     if (!isFileOpen())
408     {
409         return;
410     }
411     for (int i = 0; i < points.columnCount(); ++i)
412     {
413         writeValue(points.y(i));
414     }
415 }
416
417
418 /********************************************************************
419  * DataVectorPlotModule
420  */
421
422 AnalysisDataVectorPlotModule::AnalysisDataVectorPlotModule()
423 {
424     for (int i = 0; i < DIM; ++i)
425     {
426         bWrite_[i] = true;
427     }
428     bWrite_[DIM] = false;
429 }
430
431
432 AnalysisDataVectorPlotModule::AnalysisDataVectorPlotModule(
433         const AnalysisDataPlotSettings &settings)
434     : AbstractPlotModule(settings)
435 {
436     for (int i = 0; i < DIM; ++i)
437     {
438         bWrite_[i] = true;
439     }
440     bWrite_[DIM] = false;
441 }
442
443
444 void
445 AnalysisDataVectorPlotModule::setWriteX(bool bWrite)
446 {
447     bWrite_[XX] = bWrite;
448 }
449
450
451 void
452 AnalysisDataVectorPlotModule::setWriteY(bool bWrite)
453 {
454     bWrite_[YY] = bWrite;
455 }
456
457
458 void
459 AnalysisDataVectorPlotModule::setWriteZ(bool bWrite)
460 {
461     bWrite_[ZZ] = bWrite;
462 }
463
464
465 void
466 AnalysisDataVectorPlotModule::setWriteNorm(bool bWrite)
467 {
468     bWrite_[DIM] = bWrite;
469 }
470
471
472 void
473 AnalysisDataVectorPlotModule::setWriteMask(bool bWrite[DIM + 1])
474 {
475     for (int i = 0; i < DIM + 1; ++i)
476     {
477         bWrite_[i] = bWrite[i];
478     }
479 }
480
481
482 void
483 AnalysisDataVectorPlotModule::pointsAdded(const AnalysisDataPointSetRef &points)
484 {
485     if (points.firstColumn() % DIM != 0)
486     {
487         GMX_THROW(APIError("Partial data points"));
488     }
489     if (!isFileOpen())
490     {
491         return;
492     }
493     for (int i = 0; i < points.columnCount(); i += 3)
494     {
495         for (int d = 0; d < DIM; ++d)
496         {
497             if (bWrite_[i])
498             {
499                 writeValue(points.y(i + d));
500             }
501         }
502         if (bWrite_[DIM])
503         {
504             rvec y = { points.y(i), points.y(i + 1), points.y(i + 2) };
505             writeValue(norm(y));
506         }
507     }
508 }
509
510 } // namespace gmx