gnuplot-snippets 0.1.5__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,362 @@
1
+ # Copyright (c) 2025-2026 Neil Temperley
2
+ # SPDX-License-Identifier: MIT
3
+ # See the LICENSE file in the project root for full license text.
4
+ # https://github.com/neiltemperley/gnuplot-snippets
5
+ """Demo file for using GnuplotSnippets and GnuplotController
6
+ Note: You must have gnuplot installed on your system as an executable.
7
+ Usage: python -m gnuplot_snippets.demo
8
+ """
9
+ import logging
10
+ import random
11
+
12
+ import pandas as pd
13
+
14
+ from gnuplot_snippets import (GnuplotController, GnuplotSnippets, escape_str,
15
+ next_datablock_counter)
16
+
17
+ # ##############################################################
18
+ logger = logging.getLogger("gnuplot_snippets")
19
+ # Output to console:
20
+ handler = logging.StreamHandler()
21
+ formatter = logging.Formatter(
22
+ "%(asctime)s: %(levelname)-8s:%(name)-12s:%(lineno)4d: %(message)s")
23
+ handler.setFormatter(formatter)
24
+ logger.addHandler(handler)
25
+ logger.setLevel(logging.ERROR) # INFO, DEBUG, WARNING, ERROR
26
+ # ##############################################################
27
+
28
+
29
+ def velocity(t: float, coeff_a: float, coeff_b: float,
30
+ coeff_c: float) -> float:
31
+ """Dummy car performance."""
32
+ return coeff_a * t**3 + coeff_b * t**2 + coeff_c * t
33
+
34
+
35
+ def acceleration(t: float, coeff_a: float, coeff_b: float,
36
+ coeff_c: float) -> float:
37
+ """Dummy car performance."""
38
+ return 3 * coeff_a * t**2 + 2 * coeff_b * t + coeff_c
39
+
40
+
41
+ def noisy_velocity(time_start: float, time_end: float, coeff_a: float,
42
+ coeff_b: float, coeff_c: float,
43
+ noise_level: float) -> list[tuple[float, float, float]]:
44
+ """Create data time vs noisy velocity and smooth acceleration."""
45
+ data: list[tuple[float, float, float]] = []
46
+ n = 10
47
+ delta_time = (time_end - time_start) / n
48
+ for i in range(n + 1):
49
+ t = i * delta_time
50
+ noise = random.uniform(-noise_level, noise_level)
51
+ vel = velocity(t, coeff_a, coeff_b, coeff_c) + noise
52
+ accel = acceleration(t, coeff_a, coeff_b, coeff_c)
53
+ data.append((t, vel, accel))
54
+ return data
55
+
56
+
57
+ class Transport:
58
+ """DEMO"""
59
+
60
+ def __init__(self, name: str, time_start: float, time_end: float,
61
+ coeff_a: float, coeff_b: float, coeff_c: float,
62
+ noise_level: float):
63
+ """Set up performance."""
64
+ self.name = name
65
+ self.time_start = time_start
66
+ self.time_end = time_end
67
+ self.coeff_a = coeff_a
68
+ self.coeff_b = coeff_b
69
+ self.coeff_c = coeff_c
70
+ self.noise_level = noise_level
71
+ self.velocity_performance = noisy_velocity(self.time_start,
72
+ self.time_end, self.coeff_a,
73
+ self.coeff_b, self.coeff_c,
74
+ self.noise_level)
75
+
76
+
77
+ class Car(Transport):
78
+ """DEMO"""
79
+
80
+ def __init__(self, name: str, time_start: float, time_end: float,
81
+ coeff_a: float, coeff_b: float, coeff_c: float,
82
+ noise_level: float):
83
+ super().__init__(name, time_start, time_end, coeff_a, coeff_b, coeff_c,
84
+ noise_level)
85
+
86
+ def gnuplot(self, show_name: bool = False) -> GnuplotSnippets:
87
+ """Gnuplot snippet to plot this class to a pdf file or the screen.
88
+ THIS CONTAINS ALL THE GNUPLOT COMMANDS TO RELEVANT TO PLOTTING A 'CAR'.
89
+ YOU CAN USE THIS AS A TEMPLATE.
90
+
91
+ The code below demonstrates the wide variety of ways to share the workflow
92
+ and workload between Python and gnuplot.
93
+
94
+ :param show_name: If True show the name in the key.
95
+ """
96
+ window_title = "Car Performance"
97
+ pdf_filename = f'zJUNK-DEMOFILE-{self.name}.pdf'
98
+
99
+ gs = GnuplotSnippets()
100
+
101
+ # Snippet for pdfcairo plotfile-specific settings.
102
+ gs.output_to_file(
103
+ 'set terminal pdfcairo enhanced size 5.0,5.0*0.7 lw 2.0',
104
+ 'set title', # clear title
105
+ 'set xlabel "Time {/:Italic t} [s]"; set format x "%h"', # plotfile values
106
+ 'set ylabel "Velocity {/:Italic v} [m/s]"; set format y "%0.1f"',
107
+ 'set y2label "Acceleration {/Symbol a} [m/s^2]"; set format y2 "%h"',
108
+ filename=pdf_filename,
109
+ )
110
+
111
+ # Snippet for screen-specific settings that undo plotfile settings above:
112
+ gs.output_to_screen(
113
+ f'set terminal qt title "{window_title}"',
114
+ # f'set terminal windows title "{window_title}"', # UNCOMMENT FOR WINDOWS
115
+ f'set title "Preview of {escape_str(pdf_filename)}"',
116
+ 'set xlabel "Time [s]"; set format x',
117
+ 'set ylabel "Velocity [m/s]"; set format y "%0.1f"',
118
+ 'set y2label "Acceleration [m/s^2]"; set format y2',
119
+ )
120
+
121
+ # Adds a datablock to preplot snippet:
122
+ # Here python generates the curve. So we use a gnuplot datablock for display.
123
+ # Create a nicely formatted datablock and put it in the preplot snippet:
124
+ datablock_name = f'$DataBlock_CarData{next_datablock_counter()}' # unique datablock name
125
+ df = pd.DataFrame(
126
+ self.velocity_performance,
127
+ columns=("Time_s", "Velocity_mps",
128
+ "SmoothedAcceleration_mpsps")) # type: ignore
129
+ column_formats: dict[str, str] = {
130
+ "Time_s": "9.2f",
131
+ "Velocity_mps": "12.3f",
132
+ "SmoothedAcceleration_mpsps": "26.5g"
133
+ } # human-readable formatting for datablock without compromising plot precision
134
+ # OR if we want to treat all columns the same and they are all floats just do: df = df.map("{:15.3f}".format)
135
+ gs.preplot_add_datablock(df,
136
+ datablock_name=datablock_name,
137
+ column_formats=column_formats)
138
+
139
+ # Append more to the preplot snippet.
140
+ # Other settings [using the option of one long string for several gnuplot set commands]:
141
+ # Note: Every call to preplot() must appends more commands to the preplot snippet.
142
+ # This applies to all the snippet methods.
143
+ # To see the preplot snippet: print gs.preplot()
144
+ gs.preplot("""
145
+ # Setting up gnuplot:
146
+ set grid
147
+ set xrange[0:100]
148
+ set yrange[0:*]; set y2range[0:*]
149
+ set ytics nomirror; set y2tics
150
+ set key left top
151
+ """)
152
+
153
+ # Append more to the preplot snippet.
154
+ # Define some variables and functions [this time using separate args for the commands]:
155
+ name = self.name + " " if show_name else ""
156
+ gs.preplot(
157
+ # It's usually not a great idea to use gnuplot variables because they might get overwritten by a later snippet!..
158
+ f'gnuplot_coeff_a = {self.coeff_a}',
159
+ f'# print( sprintf("Gnuplot print(): Demo: {self.name}: gnuplot_coeff_a = %.6g", gnuplot_coeff_a) )', # get gnuplot to report coeff_a value
160
+ f'# fAcceleration(t) = 3.*{self.coeff_a}*t**2 + 2.*{self.coeff_b}*t + {self.coeff_c}', # you can do this..
161
+ 'fVelocity(t,coeff_a,coeff_b,coeff_c) = coeff_a*t**3 + coeff_b*t**2 + coeff_c*t', # but this is probably safer
162
+ 'fAcceleration(t,coeff_a,coeff_b,coeff_c) = 3.*coeff_a*t**2 + 2.*coeff_b*t + coeff_c',
163
+ )
164
+
165
+ # Append more to the preplot snippet.
166
+ # Add a gnuplot label to the plot:
167
+ gs.preplot(
168
+ f'eval sprintf("set label \\"{name}Label: coeff_a = {self.coeff_a:.3g}\\" at 2,%f", '
169
+ f'fVelocity(80,{self.coeff_a},{self.coeff_b},{self.coeff_c}))', )
170
+
171
+ # Append more to the preplot snippet.
172
+ # Set title:
173
+ gs.preplot(f'set title "Performance Characteristics for {self.name}."')
174
+
175
+ # Add plot elements mixing gnuplot datablocks and gnuplot user functions:
176
+ # If python generates the curves, use datablocks. If you are OK with gnuplot creating the
177
+ # curve use gnuplot functions.
178
+ gs.plot_elements(
179
+ f'{datablock_name} using 1:2 axis x1y1 smooth mcs title "{name}Velocity Spline" with lines',
180
+ f'{datablock_name} using 1:2 axis x1y1 title "{name}Velocity Pts" with points',
181
+ f'{datablock_name} using 1:3 axis x1y2 title "{name}Smooth Acceleration Pts" with points ps 1.3',
182
+ f'fVelocity(x,{self.coeff_a},{self.coeff_b},{self.coeff_c}) axis x1y1 title "{name}Smoothed Velocity" with lines',
183
+ f'fAcceleration(x,{self.coeff_a},{self.coeff_b},{self.coeff_c}) axis x1y2 title "{name}Smooth Acceleration" with lines',
184
+ )
185
+ # Note when plotting we can use Python's array slicing capabilities to just plot some of the above:
186
+ # e.g. gc.plot(gs.plot_elements()[:3])
187
+
188
+ # Set/append to the postplot snippet:
189
+ gs.postplot('unset label') # cleanup commands
190
+ return gs # gs contains everything to print self.
191
+
192
+
193
+ def main() -> None:
194
+ print("Running gnuplot_snippets demo...")
195
+
196
+ # ##############################################################
197
+ # EXAMPLE USAGE
198
+ print(
199
+ """Note: During the demo print messages from Python and gnuplot are interlaced
200
+ and the order may not be predictable. This can't be avoided and is not usually a problem.
201
+ It's helpful to preceed print statements from each with a tag to indicate
202
+ if it came from your python code or gnuplot script, e.g. "Demo:" or "Gnuplot:"
203
+ so you know the source.
204
+ """)
205
+
206
+ # ==============================================================
207
+ # NOTE: The demo does many plots building a single gnuplot scriptfile as
208
+ # it goes. In this case the snippets were contructed so we don't
209
+ # need a gnuplot 'reset' between plots.
210
+
211
+ demo_script_filename = "zDEMO-GNUPLOT-SCRIPTFILE.gp" # You must choose a safe name for a file here!
212
+
213
+ gc = GnuplotController(debug=False, script_filename=demo_script_filename)
214
+
215
+ # ==============================================================
216
+ # DEMO 1: USING SNIPPETS
217
+ # --------------------------------------------------------------
218
+ # car1 = Car("Car1", 0, 100, 0.0001, 0.00001, 0.01, 3.0)
219
+ # car2 = Car("Car2", 0, 120, 0.00015, 0.00002, 0.02, 2.0)
220
+ car1 = Car("Car1", 0, 100, 0.00005, 0.000005, 0.005, 1.5)
221
+ car2 = Car("Car2", 0, 120, 0.00007, 0.000001, 0.01, 1.0)
222
+ # Get all snippets for each Car:
223
+ gs_car1 = car1.gnuplot()
224
+ gs_car2 = car2.gnuplot()
225
+ #
226
+ print("==============================================================")
227
+ print("Demo: Plot Car1 to screen:")
228
+ # We send all the relevant preplot info to the controller in the correct sequence:
229
+ gc.preplot(gs_car1.preplot(), gs_car1.output_to_screen(), show_source=True)
230
+ # Plot all the plot elements of Car1:
231
+ gc.plot(gs_car1.plot_elements(), pause=3) # waits 3s
232
+ # Cleanup
233
+ gc.postplot(gs_car1.postplot())
234
+ #
235
+ print("Demo: Publishing Car1 to file:")
236
+ # Before plotting now send output to file preplot command(s):
237
+ gc.preplot(gs_car1.output_to_file(), show_source=True)
238
+ # Plot to file:
239
+ gc.plot(gs_car1.plot_elements(), show_output=True, pause=0) # no pause
240
+ # Cleanup:
241
+ gc.postplot(gs_car1.postplot(), 'set output') # play safe
242
+
243
+ print("==============================================================")
244
+ print("Demo: Plot Car2 to screen:")
245
+ gc.preplot(gs_car2.preplot(), gs_car2.output_to_screen(), show_source=True)
246
+ gc.plot(gs_car2.plot_elements(), pause=4) # waits 4s
247
+ gc.postplot(gs_car2.postplot())
248
+
249
+ print("==============================================================")
250
+ print("Demo: Plot both cars to screen:")
251
+ # Plot both Cars on the one graph:
252
+ gs_car1 = car1.gnuplot(show_name=True)
253
+ gs_car2 = car2.gnuplot(show_name=True)
254
+
255
+ # Send preplot info for each car and tweak title etc for two cars instead:
256
+ # Note: the command order is the order sent to gnuplot.
257
+ # Thus, as in a normal gnuplot scripts, recent set commands overwrite older ones.
258
+ gc.preplot(gs_car1.preplot(),
259
+ gs_car2.preplot(),
260
+ 'set title "Two Cars"',
261
+ 'set key left top',
262
+ show_source=True)
263
+ # Plot both cars:
264
+ gc.plot(gs_car1.plot_elements(), gs_car2.plot_elements(),
265
+ pause=-1) # -1 is wait for keypress
266
+ # Cleanup both cars ready for next demo:
267
+ gc.postplot(gs_car1.postplot(), gs_car2.postplot())
268
+
269
+ # ==============================================================
270
+ # DEMO 2: MULTIPLOT:
271
+ # --------------------------------------------------------------
272
+ print("==============================================================")
273
+ print("Demo: Multiplot example:")
274
+ # Multiplot is a more complex case and needs a special methods
275
+ # gc.premultiplot_to_screen() OR gc.premultiplot_to_file() and gc.postmultiplot():
276
+ # Note: Once premultiplot() is called, all 'set terminal' commands in snippets are blocked until an
277
+ # 'unset multiplot' is sent by calling postmultiplot().
278
+ gc.premultiplot_to_screen(
279
+ 'set terminal qt size 800,500 title "Multiplot"',
280
+ '# set terminal windows size 800,500 title "Multiplot"', # uncomment for Windows
281
+ 'set multiplot layout 1,2',
282
+ show_source=True)
283
+ # Note: Any 'set terminal ' commands in these snippets are blocked for now.
284
+ gc.preplot(gs_car1.preplot(),
285
+ gs_car1.output_to_screen(),
286
+ 'set y2range[0:50]',
287
+ 'set title "Car 1"',
288
+ show_source=True)
289
+ gc.plot(gs_car1.plot_elements(), pause=0) # don't pause
290
+ gc.postplot(gs_car1.postplot())
291
+ #
292
+ gc.preplot(gs_car2.preplot(),
293
+ gs_car2.output_to_screen(),
294
+ 'set y2range[0:50]',
295
+ 'set title "Car 2"',
296
+ show_source=True)
297
+ gc.plot(gs_car2.plot_elements(), pause=-1) # stop on last plot
298
+ gc.postplot(gs_car2.postplot())
299
+ #
300
+ gc.postmultiplot() # turn off multiplotting.
301
+
302
+ # ==============================================================
303
+ # DEMO 3: python array slicing to see some curves from plot_elements but not all:
304
+ # --------------------------------------------------------------
305
+ print("==============================================================")
306
+ print("Demo: Plot Car1 - some curves only:")
307
+ title = "Some curves of Car 1\\nPress \\\"m\\\" to try the mouse\\\\_measure functionality."
308
+ gc.preplot(
309
+ gs_car1.preplot(),
310
+ gs_car1.output_to_screen(),
311
+ f'set title "{title}"', # put this last to override any other titles
312
+ show_source=True)
313
+ # Plot some elements of available plot_elements() list:
314
+ gc.plot(gs_car1.plot_elements()[0],
315
+ gs_car1.plot_elements()[-2:],
316
+ pause="mouse_measure")
317
+ gc.postplot(gs_car1.postplot())
318
+
319
+ # ==============================================================
320
+ # DEMO 4 - NO SNIPPETS
321
+ # Note: In this example we skip using GnuplotSnippet and send commands directly with GnuplotController:
322
+ print("==============================================================")
323
+ print("Demo: Demo of raw interface to GnuplotController:")
324
+ title = "Plot without snippets using GnuplotController only."
325
+
326
+ # Note: Generally args can be one long gnuplot script string OR one line per arg OR a mix:
327
+ gc.preplot('reset')
328
+ gc.preplot( # each call to preplot() sends more commands
329
+ """
330
+ set angle degrees
331
+ fSin(x,a) = a*x + sin(x)
332
+ fCos(x,a) = a*x + cos(x)
333
+ set xrange[-30:360*3]
334
+ set xlabel "x [deg]"
335
+ set ylabel "y [-]"
336
+ set label "Hello!" at graph 0.1, graph 0.7
337
+ set key left top
338
+ """,
339
+ f'set title "{title}"',
340
+ show_source=True)
341
+ # One gnuplot <plot-element> per arg:
342
+ gc.plot('fSin(x, 5./1440.)',
343
+ 'fCos(x, 4./1440.)',
344
+ 'sin(x) with lines lw 2.0 dt 2',
345
+ pause=-1)
346
+ gc.postplot("unset label")
347
+
348
+ # ==============================================================
349
+ # DONE!
350
+ gc.close()
351
+
352
+ print("\n==============================================================")
353
+ print(
354
+ f'The preceding code has generated one long gnuplot script file "{demo_script_filename}"\n'
355
+ 'The file contains useful links back to the python source code.\n\n'
356
+ f'Try running the demo script file directly using "gnuplot {demo_script_filename}"\n'
357
+ "This is very useful for debugging gnuplot commands and replaying the session.\n"
358
+ )
359
+
360
+
361
+ if __name__ == "__main__":
362
+ main()
@@ -0,0 +1,13 @@
1
+ # Copyright (c) 2025-2026 Neil Temperley
2
+ # SPDX-License-Identifier: MIT
3
+ # See the LICENSE file in the project root for full license text.
4
+ # https://github.com/neiltemperley/gnuplot-snippets
5
+ """Flexible unrestricted tools for Gnuplot integration with Python."""
6
+
7
+
8
+ class GnuplotError(Exception):
9
+ """Base class for exceptions in the gnuplot plotting library."""
10
+
11
+
12
+ class GnuplotNotFoundError(GnuplotError, RuntimeError):
13
+ """Raised when the gnuplot executable cannot be found."""