File: gnuplot.c

package info (click to toggle)
plotdrop 0.5.2-3
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd, squeeze, wheezy
  • size: 236 kB
  • ctags: 130
  • sloc: ansic: 1,040; makefile: 63
file content (296 lines) | stat: -rw-r--r-- 7,932 bytes parent folder | download
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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
133
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
164
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
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

/* PlotDrop is free software, released under the GNU General Public License
 * See the COPYING file for licensing details.
 *
 * Copyright 2005 John Spray
 */

#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <locale.h>
#include <unistd.h>
#include <glib.h>

#include "gnuplot.h"

// Nasty, we have two arrays because not all formats support 'enhanced'
// Recall that 'enhanced' means doing things like superscripts and subscripts
static char* exportformats[] = {"postscript", "postscript color", "postscript eps", "postscript eps color", "png", "svg", "pslatex", "pslatex color", "fig"};
static char* exportformats_enhanced[] = {"postscript enhanced", "postscript enhanced color", "postscript enhanced eps", "postscript enhanced eps color", "png", "svg enhanced", "pslatex", "pslatex color", "fig"};

// This should be in stdio.h, I don't know why it's not.
extern FILE *popen (__const char *__command, __const char *__modes);
extern int pclose (FILE *__stream);

static gchar *gnuplot_prepstring (gchar const *in) {
		gchar *encoded = g_convert_with_fallback (
			in, -1, "ISO-8859-1", "UTF-8", "[]", NULL, NULL, NULL);
		gchar *const escaped = g_strescape (encoded, "");
		g_free (encoded);
		return escaped;
}

char *gnuplot_plot (
	plotdata const *data,
	unsigned int export,
	char *outfile,
	exportformat format)
{
	if (data->paths[0] == NULL || data->count < 1)
		return "Plotdrop: No data series found";

	char scriptname[256];
	snprintf (scriptname, 255, "/tmp/plotdrop_%d.gnu", getpid ());
	FILE *plotscript = fopen (scriptname, "w");

	if (!plotscript) {
		return "Plotdrop: Could not open temporary script file";
	}

	// Set encoding before selecting terminal
	fprintf (plotscript, "set encoding iso_8859_1\n");

	// Set which terminal to use for output
	if (export) {
		if (data->enhancedmode &&
		    !strcmp (exportformats_enhanced[format], exportformats[format]))
			fprintf (stderr, "gnuplot_export: Warning - enhanced mode was requested, "
			                 "but the selected format does not support it\n");
			//FIXME: tell the user


		fprintf (plotscript, "set term %s\nset output '%s'\n",
		         data->enhancedmode ?
		         exportformats_enhanced[format] : exportformats[format],
		         outfile);
	} else {
		fprintf (plotscript, "set term x11 %s\n",
			data->enhancedmode ? "enhanced" : "");
	}

	gnuplot_compose_script (plotscript, data);
	fprintf (stderr, "\n\nRunning GNUPlot with the following commands:\n");
	gnuplot_compose_script (stderr, data);

	fprintf (plotscript, "quit\n");
	fflush (plotscript);
	fclose (plotscript);

	// Compose the gnuplot command line
	char command[512];
	if (export)
		snprintf (command, 511, "gnuplot %s 2>&1", scriptname);
	else
		snprintf (command, 511, "gnuplot -persist %s 2>&1", scriptname);

	// Run gnuplot and get the return value
	FILE *instance = popen (command, "r");
	int error = pclose (instance);

	// In case of error:
	// We actually run gnuplot again in this case of an error, because
	// we only want to do the (potentially blocking) fread when there's
	// an error, and we only know if there's an error once we've closed
	// the original pipe.
	static char *log = NULL;
	if (error) {
		fprintf (stderr, "\nGNUPlot returned %d\n", error);
		if (!log)
			log = malloc (sizeof (char) * 2048);
		instance = popen (command, "r");
		// Get stdout and stderr all together
		int size = fread (log, 1, 2047, instance);
		pclose (instance);
		log[size] = '\0';
		if (size > 0)
			fprintf (stderr, "\n\nGNUPlot log:%d\n\"\"\"\n%s\n\n\"\"\"\n", size, log);
	}

	// Delete the plot script
	unlink (scriptname);

	if (error)
		return log;
	else
		return NULL;
}


void gnuplot_compose_script (FILE *plotscript, plotdata const *data)
{
	// GNUPlot wants values formatted with periods
	setlocale (LC_ALL, "C");

	gchar *escaped = NULL;
	if (data->xlabel) {
		escaped = gnuplot_prepstring (data->xlabel);
		fprintf (plotscript, "set xlabel \"%s\"\n", escaped);
		g_free (escaped);
	}

	if (data->ylabel) {
		escaped = gnuplot_prepstring (data->ylabel);
		fprintf (plotscript, "set ylabel \"%s\"\n", escaped);
		g_free (escaped);
	}

	if (data->title) {
		escaped = gnuplot_prepstring (data->title);
		fprintf (plotscript, "set title \"%s\"\n", escaped);
		g_free (escaped);
	}
	
	// Logscales
	if (data->logscaley)
		fprintf (plotscript, "set logscale y\n");
	if (data->logscalex)
		fprintf (plotscript, "set logscale x\n");

	if (data->zeroaxis)
		fprintf (plotscript, "set zeroaxis\n");

	if (data->grid)
		fprintf (plotscript, "set grid\n");

	if (data->extra)
		fprintf (plotscript, "%s\n", data->extra);
	
	char *plotcommand = "plot ";
	fprintf (plotscript, "%s", plotcommand);

	// X Limits
	fprintf (plotscript, "[");
	if (data->xminset)
		fprintf (plotscript, "%f", data->xmin);
	fprintf (plotscript, ":");
	if (data->xmaxset)
		fprintf (plotscript, "%f", data->xmax);
	fprintf (plotscript, "]");

	// Y Limits
	fprintf (plotscript, "[");
	if (data->yminset)
		fprintf (plotscript, "%f", data->ymin);
	fprintf (plotscript, ":");
	if (data->ymaxset)
		fprintf (plotscript, "%f", data->ymax);
	fprintf (plotscript, "]");
	
	// For cycling through point types "with points pt %d"
	int ptcounter = 0;

	for (int i = 0; i < data->count; ++i ) {
		char *path = data->paths[i];
		char *title = data->titles[i];
		int series = data->series[i];

		// Series separator
		if (i > 0)
			fprintf (plotscript, ",");

		// Filename
		if (path)
			fprintf (plotscript, " '%s' ", path);

		// 'Using' clause
		if (data->errorbars) {
			fprintf (plotscript, " using 1:%d:%d ", series, series + 1);
		} else {
			fprintf (plotscript, " using 1:%d ", series);
		}

		if (data->errorbars) {
			if (data->style == STYLE_POINTS)
				fprintf (plotscript, "with errorbars ");
			else if (data->style == STYLE_LINES || data->style == STYLE_LINESPOINTS)
				fprintf (plotscript, "with errorlines ");
		} else {
			switch (data->style) {
				case STYLE_POINTS:
					fprintf (plotscript, "with points ");
					break;
				case STYLE_LINES:
					fprintf (plotscript, "with lines ");
					break;
				case STYLE_LINESPOINTS:
					fprintf (plotscript, "with linespoints ");
					break;
				case STYLE_UNIQUE:
					fprintf (plotscript, "smooth unique ");
					break;
				case STYLE_FREQUENCY:
					fprintf (plotscript, "smooth frequency ");
					break;
				case STYLE_CSPLINES:
					fprintf (plotscript, "smooth csplines ");
					break;
				case STYLE_ACSPLINES:
					fprintf (plotscript, "smooth acsplines ");
					break;
				case STYLE_BEZIER:
					fprintf (plotscript, "smooth bezier ");
					break;
				case STYLE_SBEZIER:
					fprintf (plotscript, "smooth sbezier ");
					break;
			}
		}

		if (data->style == STYLE_POINTS
		    || data->style == STYLE_LINESPOINTS
		    || data->errorbars) {
		  // First use hollow shapes (4, 6, 8, 10, 12)
		  // Then use filled shapes (5, 7, 9, 11, 13)
		  // Then give up on being picky
			if (ptcounter < 5)
				fprintf (plotscript, "pt %d ", 4 + (ptcounter % 5) * 2);
			else if (ptcounter < 10)
				fprintf (plotscript, "pt %d ", 4 + (ptcounter % 5) * 2 + 1);
			else
				fprintf (plotscript, "pt %d ", ptcounter % 14);
			++ptcounter;
		}

		// Series label
		if (title) {
			title = gnuplot_prepstring (title);
			fprintf (plotscript, "title \"%s\"", title);
			g_free (title);
		}
	}

	fprintf (plotscript, "\n");

	setlocale (LC_ALL, "");
}

char* gnuplot_get_version ()
{
	FILE *prog = popen ("gnuplot --version", "r");
	if (!prog) {
		fprintf (stderr, "gnuplot_get_version: error opening pipe!\n");
		return NULL;		
	}

	char outp[255];
	int size = fread (outp, 1, 128, prog);
	outp[size] = '\0';

	int status = pclose (prog);
	if (status) {
		fprintf (stderr, "gnuplot_get_version: gnuplot not found!\n");
		return NULL;
	}		

	static char *version = NULL;
	if (!version)
		version = malloc (128);
	sscanf (outp, "gnuplot %s\n", version);

	if (strlen (version) == 0)
		return NULL;
	else
		return version;
}