Gnuplot.cc 11.2 KB
Newer Older
Jan Möbius's avatar
Jan Möbius committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
////////////////////////////////////////////
//
// A C++ interface to gnuplot. 
//
// This is a direct translation from the C interface
// written by N. Devillard (which is available from
// http://ndevilla.free.fr/gnuplot/).
//
// As in the C interface this uses pipes and so wont
// run on a system that does'nt have POSIX pipe 
// support
//
// Rajarshi Guha
// <rajarshi@presidency.com>
//
// 07/03/03
//
////////////////////////////////////////////

#include "Gnuplot.hh"
#include <stdarg.h>
#ifdef WIN32
#  include <io.h>
#else
#  include <fcntl.h>  // X_OK
#  include <unistd.h> // access
#  define PATH_MAXNAMESZ       4096
#endif
#include <iostream>
#include <fstream>
#include <sstream>
#include <list>
Matthias Möller's avatar
Matthias Möller committed
33
#include <algorithm>
Jan Möbius's avatar
Jan Möbius committed
34
35
36
37
38
39
40

#if defined(WIN32)
#  define pclose _pclose
#  define popen  _popen
#  define access _access
#  define ACCESS_OK 0
#  define PATH_SEP ";"
Jan Möbius's avatar
Jan Möbius committed
41
#  define MKTEMP_AND_CHECK_FAILED(name) (_mktemp(name) == nullptr)
Jan Möbius's avatar
Jan Möbius committed
42
43
44
45
46
47
48
#else
#  define ACCESS_OK X_OK
#  define PATH_SEP ":"
#  define MKTEMP_AND_CHECK_FAILED(name) (mkstemp(name) == -1)
#endif

#ifndef WIN32
49
50

#include <string.h>
Jan Möbius's avatar
Jan Möbius committed
51
52
53
54
55
#else
  #ifdef __MINGW32__
    #include <stdlib.h>
    #include <string.h>
  #endif
Jan Möbius's avatar
Jan Möbius committed
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
#endif

using namespace std;

/////////////////////////////
//
// A string tokenizer taken from
// http://www.sunsite.ualberta.ca/
//        Documentation/Gnu/libstdc++-2.90.8/html/21_strings/stringtok_std_h.txt
//
/////////////////////////////

template <typename Container>
void
stringtok (Container &container, string const &in,
           const char * const delimiters = " \t\n")
{
  const string::size_type len = in.length();

  string::size_type i = 0;

  while ( i < len )
  {
    // eat leading whitespace
    i = in.find_first_not_of (delimiters, i);
    if (i == string::npos)
      return;   // nothing left but white space
    
    // find the end of the token
    string::size_type j = in.find_first_of (delimiters, i);
    
    // push token
    if (j == string::npos) 
    {
      container.push_back (in.substr(i));
      return;
    } else
      container.push_back (in.substr(i, j-i));
    
    // set up for next loop
    i = j + 1;
  }
}

// ----------------------------------------------------------------------------

#ifdef WIN32
  std::string Gnuplot::gnuplot_executable_ = "pgnuplot.exe";
#else
  std::string Gnuplot::gnuplot_executable_ = "gnuplot";
#endif

// ----------------------------------------------------------------------------

Gnuplot::Gnuplot(void)
{
  init();
  set_style("points");
}

// ----------------------------------------------------------------------------

Gnuplot::Gnuplot(const string &style)
{
  init();
  set_style(style);
}

// ----------------------------------------------------------------------------

Gnuplot::Gnuplot(const string &title,
                 const string &style,
                 const string &labelx,  const string &labely,
                 vector<double> x, vector<double> y)
{
  init();
		
Jan Möbius's avatar
Jan Möbius committed
133
  if (x.empty() || y.empty() )
Jan Möbius's avatar
Jan Möbius committed
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
    throw GnuplotException("vectors too small");
  
  if (style == "")
    this->set_style("lines");
  else
    this->set_style(style);
  
  if (labelx == "")
    this->set_xlabel("X");
  else
    this->set_xlabel(labelx);
  if (labely == "")
    this->set_ylabel("Y");
  else
    this->set_ylabel(labely);
  
  this->plot_xy(x,y,title);
  
  cout << "Press enter to continue" << endl;
  while (getchar() != '\n'){}
}

// ----------------------------------------------------------------------------

Gnuplot::Gnuplot(const string &title,  const string &style,
                 const string &labelx, const string &labely,
                 vector<double> x)
{
  init();
  
Jan Möbius's avatar
Jan Möbius committed
164
  if (x.empty() )
Jan Möbius's avatar
Jan Möbius committed
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
    throw GnuplotException("vector too small");
  if (!this->gnucmd)
    throw GnuplotException("Could'nt open connection to gnuplot");
  
  if (style == "")
    this->set_style("lines");
    else
      this->set_style(style);
  
  if (labelx == "")
    this->set_xlabel("X");
  else
    this->set_xlabel(labelx);
  if (labely == "")
    this->set_ylabel("Y");
  else
    this->set_ylabel(labely);
  
  this->plot_x(x,title);
  
  cout << "Press enter to continue" << endl;
  while (getchar() != '\n'){}
}

// ----------------------------------------------------------------------------

Gnuplot::~Gnuplot()
{
Jan Möbius's avatar
Jan Möbius committed
193
  if ( !((this->to_delete).empty()) )
Jan Möbius's avatar
Jan Möbius committed
194
195
196
197
198
199
200
201
202
203
204
205
206
  {
    for (size_t i = 0; i < this->to_delete.size(); i++)
      remove(this->to_delete[i].c_str());
  }
  
  if (pclose(this->gnucmd) == -1)
    cerr << "Problem closing communication to gnuplot" << endl;
  
  return;
}

// ----------------------------------------------------------------------------

Jan Möbius's avatar
Jan Möbius committed
207
bool Gnuplot::get_program_path(const string& pname)
Jan Möbius's avatar
Jan Möbius committed
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
{
  list<string> ls;
  char *path;
  
  path = getenv("PATH");
  if (!path)
    return false;

  stringtok(ls, path, PATH_SEP);

  for (list<string>::const_iterator i = ls.begin(); i != ls.end(); ++i)
  {    
    string tmp = (*i) + "/" + pname;
    if ( access(tmp.c_str(), ACCESS_OK) == 0 )
      return true;
  }

  return false;
}

// ----------------------------------------------------------------------------

void Gnuplot::reset_plot(void)
{       
Jan Möbius's avatar
Jan Möbius committed
232
  if ( !(this->to_delete.empty()) )
Jan Möbius's avatar
Jan Möbius committed
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
  {
    for (size_t i = 0; i < this->to_delete.size(); i++)
      remove(this->to_delete[i].c_str());
  }
  this->nplots = 0;
  return;
}

// ----------------------------------------------------------------------------

void Gnuplot::set_style(const string &stylestr)
{
  if (stylestr != "lines" &&
      stylestr != "points" &&
      stylestr != "linespoints" &&
      stylestr != "impulses" &&
      stylestr != "dots" &&
      stylestr != "steps" &&
      stylestr != "errorbars" &&
      stylestr != "boxes" &&
      stylestr != "boxerrorbars")
    this->pstyle = string("points");
  else
    this->pstyle = stylestr;
}

// ----------------------------------------------------------------------------

void Gnuplot::cmd(const char *_cmd, ...)
{
    va_list ap;
    char local_cmd[GP_CMD_SIZE];

    va_start(ap, _cmd);
    vsprintf(local_cmd, _cmd, ap);
    va_end(ap);

    strcat(local_cmd,"\n");
    fputs(local_cmd,this->gnucmd);
    fflush(this->gnucmd);
    return;
}

// ----------------------------------------------------------------------------

void Gnuplot::set_ylabel(const string &label)
{
    ostringstream cmdstr;

    cmdstr << "set xlabel \"" << label << "\"";
    this->cmd(cmdstr.str().c_str());

    return;
}

// ----------------------------------------------------------------------------

void Gnuplot::set_xlabel(const string &label)
{
    ostringstream cmdstr;

    cmdstr << "set xlabel \"" << label << "\"";
    this->cmd(cmdstr.str().c_str());

    return;
}

// ----------------------------------------------------------------------------

// Plots a linear equation (where you supply the
// slope and intercept)
//
void Gnuplot::plot_slope(double a, double b, const string &title)
{
    ostringstream stitle;
    ostringstream cmdstr;

    if (title == "")
        stitle << "no title";
    else
        stitle << title;

    if (this->nplots > 0)
        cmdstr << "replot " << a << " * x + " << b << " title \"" << stitle.str() << "\" with " << pstyle;
    else
        cmdstr << "plot " << a << " * x + " << b << " title \"" << stitle.str() << "\" with " << pstyle;
    this->cmd(cmdstr.str().c_str());
    this->nplots++;
    return;
}

// ----------------------------------------------------------------------------

// Plot an equation which is supplied as a string
// 
void Gnuplot::plot_equation(const string &equation, const string &title)
{
    string titlestr, plotstr;
    ostringstream cmdstr;

    if (title == "")
        titlestr = "no title";
    else
        titlestr = title;

    if (this->nplots > 0)
        plotstr = "replot";
    else
        plotstr = "plot";

    cmdstr << plotstr << " " << equation << " " << "title \"" << titlestr << "\" with " << this->pstyle;
    this->cmd(cmdstr.str().c_str());
    this->nplots++;

    return;
}

// ----------------------------------------------------------------------------

void Gnuplot::plot_x(vector<double> d, const string &title)
{
  ofstream tmp;
  ostringstream cmdstr;
#ifdef WIN32
  char name[] = "gnuplotiXXXXXX";
#else
  char name[] = "/tmp/gnuplotiXXXXXX";
#endif

  if (this->to_delete.size() == GP_MAX_TMP_FILES - 1)
  {
    cerr << "Maximum number of temporary files reached (" << GP_MAX_TMP_FILES << "): cannot open more files" << endl;
    return;
  }
  
  //
  //open temporary files for output
#ifdef WIN32
Jan Möbius's avatar
Jan Möbius committed
371
  if ( _mktemp(name) == nullptr)
Jan Möbius's avatar
Jan Möbius committed
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
#else
  if ( mkstemp(name) == -1 )
#endif
  {
    cerr << "Cannot create temporary file: exiting plot" << endl;
    return;
  }
  tmp.open(name);
  if (tmp.bad())
  {
    cerr << "Cannot create temorary file: exiting plot" << endl;
    return;
  }

  //
  // Save the temporary filename
  // 
  this->to_delete.push_back(name);

  //
  // write the data to file
  //
  for (size_t i = 0; i < d.size(); i++)
    tmp << d[i] << endl;
  tmp.flush();    
  tmp.close();
  
  //
  // command to be sent to gnuplot
  //
  cmdstr << ( (this->nplots > 0) ? "replot " : "plot ");

  if (title.empty())
    cmdstr << "\"" << name << "\" with " << this->pstyle;
  else
    cmdstr << "\"" << name << "\" title \"" << title << "\" with " 
           << this->pstyle;
  
  //
  // Do the actual plot
  //
  this->cmd(cmdstr.str().c_str());
  this->nplots++;
  
  return;
}

// ----------------------------------------------------------------------------
    
void Gnuplot::plot_xy(vector<double> x, vector<double> y, const string &title)
{
  ofstream tmp;
  ostringstream cmdstr;
#ifdef WIN32
  char name[] = "gnuplotiXXXXXX";
#else
  char name[] = "/tmp/gnuplotiXXXXXX";
#endif
    
  // should raise an exception
  if (x.size() != y.size())
    return;
  
  if ((this->to_delete).size() == GP_MAX_TMP_FILES - 1)
  {
    std::stringstream s;
    s << "Maximum number of temporary files reached (" 
      << GP_MAX_TMP_FILES << "): cannot open more files" << endl;
    throw GnuplotException( s.str() );
  }

  //open temporary files for output
  //
  if (MKTEMP_AND_CHECK_FAILED(name))
    throw GnuplotException("Cannot create temporary file: exiting plot");

  tmp.open(name);
  if (tmp.bad())
    throw GnuplotException("Cannot create temorary file: exiting plot");
  
  // Save the temporary filename
  // 
  this->to_delete.push_back(name);
  
  // Write the data to file
  //
  size_t N = std::min(x.size(), y.size());
  for (size_t i = 0; i < N; i++)
    tmp << x[i] << " " << y[i] << endl;
  tmp.flush();    
  tmp.close();
  
  //
  // command to be sent to gnuplot
  //
  if (this->nplots > 0)
    cmdstr << "replot ";
  else cmdstr << "plot ";
  if (title == "")
    cmdstr << "\"" << name << "\" with " << this->pstyle;
  else
    cmdstr << "\"" << name << "\" title \"" << title << "\" with " << this->pstyle;
  
  //
  // Do the actual plot
  //
  this->cmd(cmdstr.str().c_str());
  this->nplots++;
  
  return;
}

// ----------------------------------------------------------------------------

void Gnuplot::init()
{
  if (!this->get_program_path(gnuplot_executable_))
  {
    this->valid = false;
    throw GnuplotException("Can't find gnuplot in your PATH");
  }
  
  this->gnucmd = popen(gnuplot_executable_.c_str(),"w");
  if (!this->gnucmd)
  {
    this->valid = false;
    throw GnuplotException("Couldn't open connection to gnuplot");
  }
  this->nplots = 0;
  this->valid = true;
}

// ============================================================================