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