Merge branch release-5-1
[alexxy/gromacs.git] / src / gromacs / analysisdata / modules / plot.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 classes in plot.h.
38  *
39  * \ingroup module_analysisdata
40  * \author Teemu Murtola <teemu.murtola@gmail.com>
41  */
42 #include "gmxpre.h"
43
44 #include "plot.h"
45
46 #include <cstdio>
47 #include <cstring>
48
49 #include <string>
50 #include <vector>
51
52 #include <boost/shared_ptr.hpp>
53
54 #include "gromacs/analysisdata/dataframe.h"
55 #include "gromacs/fileio/gmxfio.h"
56 #include "gromacs/fileio/xvgr.h"
57 #include "gromacs/legacyheaders/oenv.h"
58 #include "gromacs/math/vec.h"
59 #include "gromacs/options/basicoptions.h"
60 #include "gromacs/options/options.h"
61 #include "gromacs/options/timeunitmanager.h"
62 #include "gromacs/selection/selectioncollection.h"
63 #include "gromacs/utility/exceptions.h"
64 #include "gromacs/utility/gmxassert.h"
65 #include "gromacs/utility/programcontext.h"
66 #include "gromacs/utility/stringutil.h"
67
68 namespace
69 {
70
71 //! Enum values for plot formats.
72 const char *const g_plotFormats[] = {
73     "none", "xmgrace", "xmgr"
74 };
75
76 } // namespace
77
78 namespace gmx
79 {
80
81 /********************************************************************
82  * AnalysisDataPlotSettings
83  */
84
85 AnalysisDataPlotSettings::AnalysisDataPlotSettings()
86     : selections_(NULL), timeUnit_(eTimeUnit_ps), plotFormat_(1)
87 {
88 }
89
90 void
91 AnalysisDataPlotSettings::setSelectionCollection(const SelectionCollection *selections)
92 {
93     selections_ = selections;
94 }
95
96
97 void
98 AnalysisDataPlotSettings::addOptions(Options *options)
99 {
100     options->addOption(StringOption("xvg").enumValue(g_plotFormats)
101                            .defaultValue("xmgrace")
102                            .storeEnumIndex(&plotFormat_)
103                            .description("Plot formatting"));
104 }
105
106
107 /********************************************************************
108  * AbstractPlotModule::Impl
109  */
110
111 class AbstractPlotModule::Impl
112 {
113     public:
114         explicit Impl(const AnalysisDataPlotSettings &settings);
115         ~Impl();
116
117         void closeFile();
118
119         AnalysisDataPlotSettings  settings_;
120         std::string               filename_;
121         FILE                     *fp_;
122
123         bool                      bPlain_;
124         bool                      bOmitX_;
125         bool                      bErrorsAsSeparateColumn_;
126         std::string               title_;
127         std::string               subtitle_;
128         std::string               xlabel_;
129         std::string               ylabel_;
130         std::vector<std::string>  legend_;
131         char                      xformat_[15];
132         char                      yformat_[15];
133         real                      xscale_;
134 };
135
136 AbstractPlotModule::Impl::Impl(const AnalysisDataPlotSettings &settings)
137     : settings_(settings), fp_(NULL), bPlain_(false), bOmitX_(false),
138       bErrorsAsSeparateColumn_(false), xscale_(1.0)
139 {
140     strcpy(xformat_, "%11.3f");
141     strcpy(yformat_, " %8.3f");
142 }
143
144 AbstractPlotModule::Impl::~Impl()
145 {
146     closeFile();
147 }
148
149
150 void
151 AbstractPlotModule::Impl::closeFile()
152 {
153     if (fp_ != NULL)
154     {
155         if (bPlain_)
156         {
157             gmx_fio_fclose(fp_);
158         }
159         else
160         {
161             xvgrclose(fp_);
162         }
163         fp_ = NULL;
164     }
165 }
166
167
168 /********************************************************************
169  * AbstractPlotModule
170  */
171 /*! \cond libapi */
172 AbstractPlotModule::AbstractPlotModule()
173     : impl_(new Impl(AnalysisDataPlotSettings()))
174 {
175 }
176
177 AbstractPlotModule::AbstractPlotModule(const AnalysisDataPlotSettings &settings)
178     : impl_(new Impl(settings))
179 {
180 }
181 //! \endcond
182
183 AbstractPlotModule::~AbstractPlotModule()
184 {
185 }
186
187
188 void
189 AbstractPlotModule::setSettings(const AnalysisDataPlotSettings &settings)
190 {
191     impl_->settings_ = settings;
192 }
193
194
195 void
196 AbstractPlotModule::setFileName(const std::string &filename)
197 {
198     impl_->filename_ = filename;
199 }
200
201
202 void
203 AbstractPlotModule::setPlainOutput(bool bPlain)
204 {
205     impl_->bPlain_ = bPlain;
206 }
207
208
209 void
210 AbstractPlotModule::setErrorsAsSeparateColumn(bool bSeparate)
211 {
212     impl_->bErrorsAsSeparateColumn_ = bSeparate;
213 }
214
215
216 void
217 AbstractPlotModule::setOmitX(bool bOmitX)
218 {
219     impl_->bOmitX_ = bOmitX;
220 }
221
222
223 void
224 AbstractPlotModule::setTitle(const char *title)
225 {
226     impl_->title_ = title;
227 }
228
229 void
230 AbstractPlotModule::setTitle(const std::string &title)
231 {
232     impl_->title_ = title;
233 }
234
235
236 void
237 AbstractPlotModule::setSubtitle(const char *subtitle)
238 {
239     impl_->subtitle_ = subtitle;
240 }
241
242
243 void
244 AbstractPlotModule::setSubtitle(const std::string &subtitle)
245 {
246     impl_->subtitle_ = subtitle;
247 }
248
249
250 void
251 AbstractPlotModule::setXLabel(const char *label)
252 {
253     impl_->xlabel_ = label;
254 }
255
256
257 void
258 AbstractPlotModule::setXAxisIsTime()
259 {
260     TimeUnitManager manager(impl_->settings_.timeUnit());
261     impl_->xlabel_ = formatString("Time (%s)", manager.timeUnitAsString());
262     impl_->xscale_ = manager.inverseTimeScaleFactor();
263 }
264
265
266 void
267 AbstractPlotModule::setYLabel(const char *label)
268 {
269     impl_->ylabel_ = label;
270 }
271
272
273 void
274 AbstractPlotModule::setLegend(int nsets, const char * const *setname)
275 {
276     impl_->legend_.reserve(impl_->legend_.size() + nsets);
277     for (int i = 0; i < nsets; ++i)
278     {
279         appendLegend(setname[i]);
280     }
281 }
282
283
284 void
285 AbstractPlotModule::appendLegend(const char *setname)
286 {
287     impl_->legend_.push_back(setname);
288 }
289
290
291 void
292 AbstractPlotModule::appendLegend(const std::string &setname)
293 {
294     impl_->legend_.push_back(setname);
295 }
296
297
298 void
299 AbstractPlotModule::setXFormat(int width, int precision, char format)
300 {
301     GMX_RELEASE_ASSERT(width >= 0 && precision >= 0
302                        && width <= 99 && precision <= 99,
303                        "Invalid width or precision");
304     GMX_RELEASE_ASSERT(strchr("eEfFgG", format) != NULL,
305                        "Invalid format specifier");
306     sprintf(impl_->xformat_, "%%%d.%d%c", width, precision, format);
307 }
308
309
310 void
311 AbstractPlotModule::setYFormat(int width, int precision, char format)
312 {
313     GMX_RELEASE_ASSERT(width >= 0 && precision >= 0
314                        && width <= 99 && precision <= 99,
315                        "Invalid width or precision");
316     GMX_RELEASE_ASSERT(strchr("eEfFgG", format) != NULL,
317                        "Invalid format specifier");
318     sprintf(impl_->yformat_, " %%%d.%d%c", width, precision, format);
319 }
320
321
322 int
323 AbstractPlotModule::flags() const
324 {
325     return efAllowMissing | efAllowMulticolumn | efAllowMultipoint
326            | efAllowMultipleDataSets;
327 }
328
329
330 void
331 AbstractPlotModule::dataStarted(AbstractAnalysisData * /* data */)
332 {
333     if (!impl_->filename_.empty())
334     {
335         if (impl_->bPlain_)
336         {
337             impl_->fp_ = gmx_fio_fopen(impl_->filename_.c_str(), "w");
338         }
339         else
340         {
341             time_unit_t  time_unit
342                 = static_cast<time_unit_t>(impl_->settings_.timeUnit() + 1);
343             xvg_format_t xvg_format
344                 = (impl_->settings_.plotFormat() > 0
345                    ? static_cast<xvg_format_t>(impl_->settings_.plotFormat())
346                    : exvgNONE);
347             output_env_t                  oenv;
348             output_env_init(&oenv, getProgramContext(), time_unit, FALSE, xvg_format, 0);
349             boost::shared_ptr<output_env> oenvGuard(oenv, &output_env_done);
350             impl_->fp_ = xvgropen(impl_->filename_.c_str(), impl_->title_.c_str(),
351                                   impl_->xlabel_.c_str(), impl_->ylabel_.c_str(),
352                                   oenv);
353             const SelectionCollection *selections
354                 = impl_->settings_.selectionCollection();
355             if (selections != NULL)
356             {
357                 selections->printXvgrInfo(impl_->fp_, oenv);
358             }
359             if (!impl_->subtitle_.empty())
360             {
361                 xvgr_subtitle(impl_->fp_, impl_->subtitle_.c_str(), oenv);
362             }
363             if (output_env_get_print_xvgr_codes(oenv)
364                 && !impl_->legend_.empty())
365             {
366                 std::vector<const char *> legend;
367                 legend.reserve(impl_->legend_.size());
368                 for (size_t i = 0; i < impl_->legend_.size(); ++i)
369                 {
370                     legend.push_back(impl_->legend_[i].c_str());
371                 }
372                 xvgr_legend(impl_->fp_, legend.size(), &legend[0], oenv);
373             }
374         }
375     }
376 }
377
378
379 void
380 AbstractPlotModule::frameStarted(const AnalysisDataFrameHeader &frame)
381 {
382     if (!isFileOpen())
383     {
384         return;
385     }
386     if (!impl_->bOmitX_)
387     {
388         std::fprintf(impl_->fp_, impl_->xformat_, frame.x() * impl_->xscale_);
389     }
390 }
391
392
393 void
394 AbstractPlotModule::frameFinished(const AnalysisDataFrameHeader & /*header*/)
395 {
396     if (!isFileOpen())
397     {
398         return;
399     }
400     std::fprintf(impl_->fp_, "\n");
401 }
402
403
404 void
405 AbstractPlotModule::dataFinished()
406 {
407     impl_->closeFile();
408 }
409
410 /*! \cond libapi */
411 bool
412 AbstractPlotModule::isFileOpen() const
413 {
414     return impl_->fp_ != NULL;
415 }
416
417
418 void
419 AbstractPlotModule::writeValue(const AnalysisDataValue &value) const
420 {
421     GMX_ASSERT(isFileOpen(), "File not opened, but write attempted");
422     const real y = value.isSet() ? value.value() : 0.0;
423     std::fprintf(impl_->fp_, impl_->yformat_, y);
424     if (impl_->bErrorsAsSeparateColumn_)
425     {
426         const real dy = value.isSet() ? value.error() : 0.0;
427         std::fprintf(impl_->fp_, impl_->yformat_, dy);
428     }
429 }
430 //! \endcond
431
432 /********************************************************************
433  * DataPlotModule
434  */
435
436 AnalysisDataPlotModule::AnalysisDataPlotModule()
437 {
438 }
439
440 AnalysisDataPlotModule::AnalysisDataPlotModule(
441         const AnalysisDataPlotSettings &settings)
442     : AbstractPlotModule(settings)
443 {
444 }
445
446
447 void
448 AnalysisDataPlotModule::pointsAdded(const AnalysisDataPointSetRef &points)
449 {
450     if (!isFileOpen())
451     {
452         return;
453     }
454     for (int i = 0; i < points.columnCount(); ++i)
455     {
456         writeValue(points.values()[i]);
457     }
458 }
459
460
461 /********************************************************************
462  * DataVectorPlotModule
463  */
464
465 AnalysisDataVectorPlotModule::AnalysisDataVectorPlotModule()
466 {
467     for (int i = 0; i < DIM; ++i)
468     {
469         bWrite_[i] = true;
470     }
471     bWrite_[DIM] = false;
472 }
473
474
475 AnalysisDataVectorPlotModule::AnalysisDataVectorPlotModule(
476         const AnalysisDataPlotSettings &settings)
477     : AbstractPlotModule(settings)
478 {
479     for (int i = 0; i < DIM; ++i)
480     {
481         bWrite_[i] = true;
482     }
483     bWrite_[DIM] = false;
484 }
485
486
487 void
488 AnalysisDataVectorPlotModule::setWriteX(bool bWrite)
489 {
490     bWrite_[XX] = bWrite;
491 }
492
493
494 void
495 AnalysisDataVectorPlotModule::setWriteY(bool bWrite)
496 {
497     bWrite_[YY] = bWrite;
498 }
499
500
501 void
502 AnalysisDataVectorPlotModule::setWriteZ(bool bWrite)
503 {
504     bWrite_[ZZ] = bWrite;
505 }
506
507
508 void
509 AnalysisDataVectorPlotModule::setWriteNorm(bool bWrite)
510 {
511     bWrite_[DIM] = bWrite;
512 }
513
514
515 void
516 AnalysisDataVectorPlotModule::setWriteMask(bool bWrite[DIM + 1])
517 {
518     for (int i = 0; i < DIM + 1; ++i)
519     {
520         bWrite_[i] = bWrite[i];
521     }
522 }
523
524
525 void
526 AnalysisDataVectorPlotModule::pointsAdded(const AnalysisDataPointSetRef &points)
527 {
528     if (points.firstColumn() % DIM != 0 || points.columnCount() % DIM != 0)
529     {
530         GMX_THROW(APIError("Partial data points"));
531     }
532     if (!isFileOpen())
533     {
534         return;
535     }
536     for (int i = 0; i < points.columnCount(); i += 3)
537     {
538         for (int d = 0; d < DIM; ++d)
539         {
540             if (bWrite_[i])
541             {
542                 writeValue(points.values()[i + d]);
543             }
544         }
545         if (bWrite_[DIM])
546         {
547             const rvec        y = { points.y(i), points.y(i + 1), points.y(i + 2) };
548             AnalysisDataValue value(norm(y));
549             writeValue(value);
550         }
551     }
552 }
553
554 } // namespace gmx