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