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