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,21 @@
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
+ """Composable gnuplot snippets for Python.
6
+
7
+ Typical use::
8
+ from gnuplot_snippets import GnuplotController, GnuplotSnippet, escape_str, format_dataframe, next_datablock_counter
9
+ """
10
+ from .snippets import GnuplotSnippets, escape_str, format_dataframe, next_datablock_counter
11
+ from .controller import GnuplotController
12
+
13
+ # __all__ defines the public API for "from gnuplot_snippets import *"
14
+ # and signals the public names to IDEs and static tools.
15
+ __all__ = [
16
+ "GnuplotController",
17
+ "GnuplotSnippets",
18
+ "escape_str",
19
+ "format_dataframe",
20
+ "next_datablock_counter",
21
+ ]
@@ -0,0 +1,157 @@
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
+ import sys
7
+ import logging
8
+ import re
9
+ from collections.abc import Iterable, Iterator
10
+
11
+ logger = logging.getLogger("gnuplot_snippets")
12
+
13
+ _TERMINAL_RE = re.compile(r"^\s*set\s+term[inal]*\b", re.IGNORECASE)
14
+
15
+
16
+ def _split_top_level(line: str) -> list[str]:
17
+ """Split one Gnuplot line on ';' outside quotes, braces and comments.
18
+ """
19
+ segments: list[str] = []
20
+ start, depth, quote, i = 0, 0, "", 0
21
+ while i < len(line):
22
+ ch = line[i]
23
+ if quote:
24
+ if ch == "\\" and quote == '"':
25
+ i += 1 # skip escaped character
26
+ elif ch == quote:
27
+ quote = ""
28
+ elif ch in "\"'":
29
+ quote = ch
30
+ elif ch == "#":
31
+ break # rest of the line is a comment
32
+ elif ch == "{":
33
+ depth += 1
34
+ elif ch == "}":
35
+ depth = max(0, depth - 1)
36
+ elif ch == ";" and depth == 0:
37
+ segments.append(line[start:i])
38
+ start = i + 1
39
+ i += 1
40
+ segments.append(line[start:])
41
+ return segments
42
+
43
+
44
+ def _extract_set_terminal_cmd(*set_cmds: str) -> tuple[str | None, list[str]]:
45
+ """Find 'set terminal ...' command(s) if it exists in command(s).
46
+
47
+ Commands may be separated by newlines or by semicolons (outside quotes and
48
+ braces). The terminal command is removed from the remaining commands.
49
+ :param set_cmds: Gnuplot commands
50
+ :returns: tuple of set terminal command, list of remaining command lines.
51
+ """
52
+ lines: list[str] = []
53
+ terms: list[str] = []
54
+ for cmd in set_cmds:
55
+ for line in cmd.splitlines():
56
+ if not line.strip():
57
+ continue
58
+ kept: list[str] = []
59
+ for seg in _split_top_level(line):
60
+ if _TERMINAL_RE.match(seg):
61
+ terms.append(seg.strip())
62
+ elif seg.strip():
63
+ kept.append(seg.strip())
64
+ if kept:
65
+ lines.append("; ".join(kept))
66
+ if len(terms) > 1:
67
+ raise ValueError(
68
+ f"More than one 'set terminal' command given: {terms}.")
69
+ return (terms[0] if terms else None), lines
70
+
71
+
72
+ def _source(note: str = "", is_snippet: bool = True, depth: int = 2) -> str:
73
+ """Create a comment string identifying the source of a gnuplot command.
74
+
75
+ Reports the location ``depth`` frames above this function. The default of 2
76
+ is the caller of the function that called ``_source``, i.e. the user's code
77
+ when called from a public GnuplotSnippets or GnuplotController method.
78
+
79
+ Note: No newline at end.
80
+ :param note: optional note to append. Newlines are converted to comment lines.
81
+ :param is_snippet: True if called from a GnuplotSnippets method, else GnuplotController.
82
+ :param depth: number of frames to walk up from this function.
83
+ :returns: Source string to write to the gnuplot script file.
84
+ """
85
+ source_type = "GnuplotSnippets" if is_snippet else "GnuplotController"
86
+ note = note.replace("\n", "\n# ")
87
+ try:
88
+ frame = sys._getframe(depth)
89
+ except (ValueError, AttributeError): # stack too shallow / non-CPython
90
+ return f"{source_type} Source unknown. {note}"
91
+ filename = frame.f_code.co_filename
92
+ return f"{source_type} Source: {filename}: {frame.f_lineno}: {frame.f_code.co_name}()... {note}"
93
+
94
+
95
+ def _flatten_to_tuple_of_strings(*args) -> tuple[str, ...]:
96
+ """Flatten strings and arbitrarily nested iterables of strings.
97
+
98
+ Accepts str, or any iterable (tuple, list, generator, ...) of those, nested to any depth.
99
+ Empty strings are dropped, since plot elements cannot be empty.
100
+
101
+ :raises TypeError: if any item is neither a str nor an iterable.
102
+ :returns: tuple of strings
103
+ """
104
+
105
+ # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
106
+ def _flatten(item) -> Iterator[str]:
107
+ if isinstance(item, str):
108
+ yield item
109
+ elif isinstance(item, (bytes, dict)):
110
+ raise TypeError(
111
+ f"plot elements cannot contain {type(item).__name__}")
112
+ elif isinstance(item, Iterable):
113
+ for sub in item:
114
+ yield from _flatten(sub)
115
+ else:
116
+ raise TypeError(
117
+ f"plot elements must be str or iterable of str, got {type(item).__name__}: {item!r}!"
118
+ )
119
+
120
+ # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
121
+
122
+ return tuple(s for s in _flatten(args) if s.strip())
123
+
124
+
125
+ def _check_cmd(cmd):
126
+ """Check cmd is a string."""
127
+ if not isinstance(cmd, str):
128
+ if type(cmd).__name__ == "GnuplotSnippets":
129
+ raise TypeError(
130
+ f"Expected string, got {type(cmd).__name__}: {cmd!r}.\n"
131
+ "Perhaps you sent a snippets object to preplot()? To add a snippet use the snippets' append() method."
132
+ )
133
+ else:
134
+ raise TypeError(
135
+ f"Expected a string; got {type(cmd).__name__}: {cmd!r}.")
136
+ return
137
+
138
+
139
+ def _clean_cmds(*set_cmds) -> str:
140
+ """Clean and add one or more lines to the gnuplot command string.
141
+
142
+ Attempts to comment out any "pause XXX" gnuplot commands of user because
143
+ the GnuplotController will handle the pause workflow.
144
+ :raises TypeError: if any argument is not a string
145
+ :returns: cleaned up command string always ending with a newline unless empty.
146
+ """
147
+ lines: list[str] = []
148
+ for cmd in set_cmds:
149
+ _check_cmd(cmd)
150
+ for line in cmd.splitlines():
151
+ # logger.debug("line \t= \"{}\"".format(line))
152
+ # Replace 'pause -1', 'pause mouse' with '# pause 0' etc.
153
+ new_line = re.sub(r'\bpause\s+(-?\d+|mouse)([^;\n]*)[;]*',
154
+ r'# pause \1\2\n', line)
155
+ # logger.debug("new_line \t= \"{}\"".format(new_line))
156
+ lines.append(new_line.rstrip())
157
+ return "\n".join(lines) + "\n" if len(lines) > 0 else ""
@@ -0,0 +1,484 @@
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 controller for unrestricted gnuplot integration with Python."""
6
+ import logging
7
+ import math
8
+ import shutil
9
+ import subprocess
10
+ import sys
11
+ import time
12
+ from datetime import datetime
13
+ from types import TracebackType
14
+ from typing import Literal
15
+
16
+ from ._utils import (_clean_cmds, _extract_set_terminal_cmd,
17
+ _flatten_to_tuple_of_strings, _source)
18
+ from .errors import GnuplotError, GnuplotNotFoundError
19
+
20
+ logger = logging.getLogger("gnuplot_snippets")
21
+
22
+
23
+ def _gp_quote(text: str) -> str:
24
+ """Return ``text`` as a gnuplot single-quoted string (quotes doubled)."""
25
+ return "'" + text.replace("'", "''") + "'"
26
+
27
+
28
+ class GnuplotController:
29
+ """Control creation and display of gnuplot plots.
30
+
31
+ Best used as a context manager so gnuplot is always shut down and the
32
+ debug script is written, even when an exception occurs::
33
+
34
+ with GnuplotController(script_filename="debug.gp") as gc:
35
+ gc.preplot('set title "sine curve"', 'set angle degrees', 'set xrange [-360:360]')
36
+ gc.plot("sin(x)", pause=-1)
37
+
38
+ Note: GnuplotController() can be used standalone but works best with GnuplotSnippets().
39
+ Note: commands are passed to gnuplot unchanged (including ``system``),
40
+ so never pass untrusted input.
41
+ """
42
+
43
+ def __init__(self,
44
+ debug: bool = False,
45
+ script_filename: str = "",
46
+ gnuplot_executable: str = "gnuplot") -> None:
47
+ """Open gnuplot as a subprocess.
48
+
49
+ Example without GnuplotSnippets::
50
+
51
+ gc = GnuplotController()
52
+ gc.preplot('set title "Some curves"', 'set angle degrees')
53
+ gc.plot("sin(x)", "cos(x)", pause=4)
54
+ gc.plot("sin(x)", "tan(x)", pause=5)
55
+ gc.close()
56
+
57
+ :param debug: If True, print the recorded gnuplot script on close.
58
+ :param script_filename: If set, write the recorded script here on close. Useful
59
+ for debugging gnupot errors by "gnuplot ``script_filename``".
60
+ :param gnuplot_executable: Name or path of the gnuplot executable.
61
+ """
62
+ # Plain attributes first so close() is always safe to call:
63
+ self.is_debug: bool = debug
64
+ self.script_filename = script_filename
65
+ self.pause_override: int | float | None = None # overrides pause if set
66
+ self._closed = False
67
+ timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
68
+ self.script = (
69
+ "# Gnuplot script particularly useful for debugging gnuplot errors by running \"gnuplot script_filename\" in a terminal.\n"
70
+ f"# Created on {timestamp}\n\n")
71
+
72
+ self.gnuplot_path = self._find_gnuplot(gnuplot_executable)
73
+ self.gnuplot = subprocess.Popen(
74
+ [self.gnuplot_path], # don't want -persistent switch!
75
+ stdin=subprocess.PIPE,
76
+ text=True,
77
+ # universal_newlines=True,
78
+ encoding="utf-8")
79
+
80
+ def __enter__(self) -> "GnuplotController":
81
+ """Context manager support."""
82
+ return self
83
+
84
+ def __exit__(self, exc_type: type[BaseException] | None,
85
+ exc: BaseException | None,
86
+ tb: TracebackType | None) -> Literal[False]:
87
+ """Context manager support."""
88
+ self.close()
89
+ return False # never swallow exceptions
90
+
91
+ def _find_gnuplot(self, executable: str = "gnuplot") -> str:
92
+ """Return the full path to gnuplot, or raise a clear error.
93
+
94
+ :param executable: gnuplot executable
95
+ """
96
+ path = shutil.which(executable)
97
+ if path is None:
98
+ raise GnuplotNotFoundError(
99
+ f"Could not find '{executable}'. "
100
+ "Install gnuplot (e.g. on Linux 'sudo apt install gnuplot') "
101
+ "and check you can run it from the terminal command prompt.")
102
+ return path
103
+
104
+ def cmd(self,
105
+ gnuplot_str: str,
106
+ show_source: bool = False,
107
+ script_str: str | None = None) -> None:
108
+ """Send a command str to gnuplot ensuring a newline termination.
109
+
110
+ :param gnuplot_str: Raw gnuplot command(s).
111
+ :param show_source: If True, record the calling file and line in the script.
112
+ :param script_str: If given, recorded in the script instead of ``gnuplot_str``
113
+ (e.g. to add prompts that only make sense when run standalone).
114
+ """
115
+ cmd_source: str = f'# {_source(is_snippet=False)}\n' if show_source else ""
116
+ gnuplot_str = gnuplot_str.rstrip() + "\n"
117
+ stdin = self.gnuplot.stdin
118
+ if stdin is None:
119
+ raise GnuplotError("gnuplot stdin is not available!")
120
+ try:
121
+ stdin.write(gnuplot_str)
122
+ stdin.flush()
123
+ except (BrokenPipeError, ValueError, OSError) as e:
124
+ raise GnuplotError("gnuplot process has exited!") from e
125
+ logged = gnuplot_str if script_str is None else script_str.rstrip(
126
+ ) + "\n"
127
+ self.script += cmd_source + logged
128
+
129
+ def preplot(self, *cmds: str, show_source: bool = False) -> None:
130
+ """Send setup commands.
131
+
132
+ :param cmds: gnuplot commands.
133
+ :param show_source: If True, record the calling file and line in the script.
134
+ """
135
+ cmd_source = f'# {_source(is_snippet=False)}\n' if show_source else ""
136
+ self.cmd(_clean_cmds(cmd_source, *cmds))
137
+
138
+ def postplot(self, *cmds: str, show_source: bool = False) -> None:
139
+ """Send tidy up commands.
140
+
141
+ This is an alias for preplot() to improve usability.
142
+
143
+ :param cmds: gnuplot commands.
144
+ :param show_source: If True, record the calling file and line in the script.
145
+ """
146
+ cmd_source = f'# {_source(is_snippet=False)}\n' if show_source else ""
147
+ self.cmd(_clean_cmds(cmd_source, *cmds))
148
+
149
+ def premultiplot_to_file(self,
150
+ *set_cmds: str,
151
+ filename: str | None = None,
152
+ show_source: bool = True) -> None:
153
+ """Begin a multiplot that is written to a file.
154
+
155
+ Sends, in order: ``unset multiplot``, the ``set terminal`` command,
156
+ ``set output '<filename>'``, then the remaining commands (e.g.
157
+ ``set multiplot layout 1,2``). The output must be set after the
158
+ terminal and before the multiplot starts.
159
+
160
+ Note: Once this is called, any 'set terminal' commands in snippets are
161
+ helpfully blocked until an 'unset multiplot' is sent by postmultiplot().
162
+
163
+ Example::
164
+
165
+ gc.premultiplot_to_file('set terminal pngcairo size 1000,1000',
166
+ 'set multiplot layout 1,2',
167
+ filename='file.png')
168
+ # then gc.preplot(...), gc.plot(...) and gc.postplot(...) for each plot...
169
+ gc.postmultiplot()
170
+
171
+ :param set_cmds: A 'set terminal ...' command plus 'set multiplot ...' plus any others.
172
+ :param filename: Output file. Note: Provide both a 'set terminal' command and
173
+ a filename, or neither.
174
+ :param show_source: If True, record the calling file and line in the script.
175
+ """
176
+ cmd_source = f'# {_source(is_snippet=False)}\n' if show_source else ""
177
+ set_terminal_cmd, remaining = _extract_set_terminal_cmd(*set_cmds)
178
+ if (set_terminal_cmd is None) != (filename is None):
179
+ raise ValueError(
180
+ "Provide both a 'set terminal ...' command and 'filename', or neither."
181
+ )
182
+ if set_terminal_cmd is None or filename is None:
183
+ # Neither given: leave terminal/output as already configured.
184
+ self.cmd(_clean_cmds(cmd_source, 'unset multiplot', *set_cmds))
185
+ return
186
+ self.cmd(
187
+ _clean_cmds(cmd_source, 'unset multiplot', set_terminal_cmd,
188
+ f"set output {_gp_quote(filename)}", *remaining))
189
+
190
+ def premultiplot_to_screen(self,
191
+ *set_cmds: str,
192
+ show_source: bool = True) -> None:
193
+ """Begin a multiplot shown on screen.
194
+
195
+ Note: Once this is called, any 'set terminal' commands in snippets are
196
+ helpfully blocked until an 'unset multiplot' is sent by postmultiplot().
197
+
198
+ Example::
199
+
200
+ gc.premultiplot_to_screen('set terminal qt 1000,1000 title "Multiplot"',
201
+ 'set multiplot layout 1,2')
202
+ # then gc.preplot(...), gc.plot(...) and gc.postplot(...) for each plot...
203
+ gc.postmultiplot()
204
+
205
+ :param set_cmds: A screen 'set terminal ...' command plus 'set multiplot ...' plus any others.
206
+ :param show_source: If True, record the calling file and line in the script.
207
+ """
208
+ cmd_source = f'# {_source(is_snippet=False)}\n' if show_source else ""
209
+ set_terminal_cmd, _ = _extract_set_terminal_cmd(*set_cmds)
210
+ if set_terminal_cmd is None:
211
+ raise ValueError(
212
+ "Must have a screen 'set terminal ' command, e.g. 'set terminal qt'."
213
+ )
214
+ self.cmd(
215
+ _clean_cmds(cmd_source, 'set output', 'unset multiplot',
216
+ *set_cmds))
217
+
218
+ def postmultiplot(self, *cmds: str, show_source: bool = False) -> None:
219
+ """Send 'unset multiplot' plus other cmds to cleanup after a multiplot.
220
+
221
+ Note: Once premultiplot_to_xxxx() is called, any 'set terminal' commands in
222
+ snippets are blocked until an 'unset multiplot' is sent.
223
+
224
+ Example::
225
+
226
+ gc.premultiplot_to_screen('set terminal qt 1000,1000 title "Multiplot"',
227
+ 'set multiplot layout 1,2')
228
+ # then gc.preplot(...), gc.plot(...) and gc.postplot(...) for each plot...
229
+ gc.postmultiplot()
230
+
231
+
232
+ :param cmds: Extra gnuplot commands to send after 'unset multiplot'.
233
+ :param show_source: If True, record the calling file and line in the script.
234
+ """
235
+ cmd_source = f'# {_source(is_snippet=False)}\n' if show_source else ""
236
+ self.cmd(_clean_cmds(cmd_source, 'unset multiplot', *cmds))
237
+
238
+ def plot(self,
239
+ *plot_elements: str | tuple[str, ...],
240
+ pause: int | float | Literal["mouse_measure"] = 0,
241
+ plot_and_ranges: str = "plot",
242
+ show_output: bool = True,
243
+ show_source: bool = False) -> None:
244
+ """Build a gnuplot plot command and send it, followed by a pause.
245
+
246
+ Note: A gnuplot plot command has the form:
247
+ plot {<ranges>} <plot-element> {, <plot-element>, ...}
248
+
249
+ When a pause is used, Python waits until it completes, keeping the
250
+ gnuplot window and the Python terminal in sync during interaction.
251
+
252
+ Example::
253
+
254
+ gc = GnuplotController()
255
+ gc.preplot('set title "Some curves"', 'set angle degrees')
256
+ # gc.plot(gs1.plot_elements(), gs2.plot_elements(), pause=-1) # e.g. with GnuplotSnippets gs1 and gs2
257
+ gc.plot("sin(x)", "cos(x)", pause=4) # without GnuplotSnippets
258
+ gc.plot("sin(x)", "tan(x)", plot_and_ranges="plot [-70:70]", pause=5) # without GnuplotSnippets
259
+ gc.preplot("unset angle")
260
+ # ..other GnuplotController commands
261
+ gc.close()
262
+
263
+ :param plot_elements: gnuplot plot elements, e.g. "sin(x)" or "'data.csv' using 1:2".
264
+ :param pause: How to pause after plotting. -1 waits for user input,
265
+ 0 does not pause, N > 0 pauses N seconds, and "mouse_measure"
266
+ prompts and waits for user interaction with plot, e.g. measure a gradient.
267
+ When pause is -1, the user may respond at the prompt:
268
+ q, quit close gnuplot and exit Python
269
+ Enter, c, continue continue to next plot
270
+ f, fastforward, a, all stop pausing for all remaining plots
271
+ <number> set the pause (secs) for all remaining plots
272
+ :param plot_and_ranges: The leading "plot {<ranges>}" portion of the
273
+ gnuplot plot command, e.g. "plot", "plot [0:10]", or "splot".
274
+ :param show_output: If True, instruct gnuplot to print the output filename
275
+ when plotting to a file.
276
+ :param show_source: If True, add a comment in the generated gnuplot
277
+ script giving the file and line of this call. This is incredibly useful for
278
+ debugging a faulty script!
279
+ """
280
+ if len(plot_elements) == 0:
281
+ raise GnuplotError("Plot elements cannot be empty!")
282
+ if self.pause_override is not None and pause != 0:
283
+ pause = self.pause_override
284
+ elements = _flatten_to_tuple_of_strings(plot_elements)
285
+
286
+ # Build the gnuplot plot string:
287
+ continue_str = ", \\\n" # extra spaces make nicer gnuplot error messages
288
+ plot_cmd = _clean_cmds(plot_and_ranges + " \\\n" +
289
+ continue_str.join(e.strip()
290
+ for e in elements) + "\n")
291
+ if show_source:
292
+ plot_cmd = f"# {_source(is_snippet=False)}\n" + plot_cmd
293
+ if show_output:
294
+ # Printed before the pause so the filename is visible while pausing.
295
+ plot_cmd += """
296
+ if (strlen(GPVAL_OUTPUT) > 0) {
297
+ print(sprintf("Gnuplot: Created plot file: \\"%s\\"", GPVAL_OUTPUT))
298
+ }
299
+ """
300
+ send_cmd = script_cmd = plot_cmd
301
+ if isinstance(pause, (int, float)):
302
+ base = plot_cmd.rstrip()
303
+ send_cmd = base + f"\npause {pause}\n"
304
+ # Write user-friendly versions to script file:
305
+ if pause < 0:
306
+ script_cmd = base + f'\npause {pause} "Gnuplot: Press Enter to continue..."\n'
307
+ elif pause == 0:
308
+ script_cmd = base + f'\npause {pause} \n' # no message
309
+ else:
310
+ script_cmd = base + f'\npause {pause} "Gnuplot: Pausing for {pause} seconds..."\n'
311
+ self.cmd(send_cmd, script_str=script_cmd) # send it
312
+
313
+ # --------------------------------------------------------------
314
+ # Optionally override original scripted plot workflow:
315
+ user_input = self._wait_for_user(pause).strip().lower()
316
+ if user_input in {"q", "quit"}:
317
+ print("Python: Quitting gnuplot and Python!")
318
+ self.close()
319
+ sys.exit()
320
+ elif user_input in {"", "c", "continue"}:
321
+ pass # no change
322
+ elif user_input in {"f", "fastforward", "a", "all"}:
323
+ print(
324
+ "Python: Fast forwarding through all plots without further pausing!"
325
+ )
326
+ self.pause_override = 0
327
+ else:
328
+ try:
329
+ new_pause = float(user_input)
330
+ if not (math.isfinite(new_pause) and new_pause >= 0):
331
+ raise ValueError(user_input)
332
+ self.pause_override = new_pause
333
+ print(
334
+ f"Python: Sleep for following plots is set to = {self.pause_override}."
335
+ )
336
+ except ValueError:
337
+ print("Python: Unrecognised response. Continuing...")
338
+
339
+ def _wait_for_user(
340
+ self, pause_option: int | float | Literal["mouse_measure"]) -> str:
341
+ """Mimic gnuplot's pause functionality in Python based on ``pause_option``.
342
+
343
+ Note:
344
+ - gnuplot can't see keypresses so gnuplot's "pause key" can't be used.
345
+ - python can't see gnuplot mouse clicks so "pause mouse" also won't work.
346
+ - These work: "pause -1", "pause 0" etc.
347
+
348
+ :param pause_option: "mouse_measure" OR gnuplot pause values -1, 0, 1.5, 3, etc.
349
+ :return: Whatever the user typed at the prompt ("" if none).
350
+ """
351
+ user_input = ""
352
+ try:
353
+ if pause_option == "mouse_measure":
354
+ self.cmd(self._mouse_measurement_cmds())
355
+ user_input = input(
356
+ "Python: Mouse Measurements! Next keypress must be in gnuplot window!\n"
357
+ )
358
+ elif isinstance(pause_option, (int, float)):
359
+ if pause_option < 0:
360
+ user_input = input(
361
+ "Python: Press Enter to continue (or 'q' to quit, 'f' for fast forward, 'N' for N sec delays):...\n"
362
+ )
363
+ try:
364
+ if self.gnuplot.stdin is not None:
365
+ self.gnuplot.stdin.write(
366
+ "\n") # gnuplot needs a char!
367
+ self.gnuplot.stdin.flush()
368
+ except (BrokenPipeError, ValueError, OSError) as e:
369
+ raise GnuplotError(
370
+ "gnuplot process has exited!") from e
371
+ elif pause_option != 0:
372
+ print(f"Python: Pausing for {pause_option} seconds...")
373
+ time.sleep(pause_option)
374
+ else:
375
+ print(
376
+ f"Python: Invalid pause option = \"{pause_option}\". Try pause=\"mouse_measure\" or standard gnuplot numerical pause values: -1, 0, 3, etc. "
377
+ )
378
+ except EOFError:
379
+ # Non-interactive stdin (CI, pipes): carry on without waiting.
380
+ return ""
381
+ return user_input
382
+
383
+ def close(self) -> None:
384
+ """Close the gnuplot window and end the session.
385
+
386
+ Safe to call more than once. The debug script is written first, so it
387
+ survives even if shutting gnuplot down fails.
388
+ """
389
+ if self._closed:
390
+ return
391
+ self._closed = True
392
+ try:
393
+ # Note: gnuplot exits on error!
394
+ if self.is_debug:
395
+ print("# GNUPLOT LOG SCRIPT FOR DEBUGGING:")
396
+ print(self.script)
397
+ if self.script_filename:
398
+ print(f"Python: Writing script to \"{self.script_filename}\".")
399
+ with open(self.script_filename, "w", encoding="utf-8") as f:
400
+ f.write(self.script)
401
+ finally:
402
+ self._shutdown()
403
+
404
+ def _shutdown(self) -> None:
405
+ """Ask gnuplot to exit, escalating to terminate then kill if it hangs."""
406
+ if self.gnuplot.poll() is None:
407
+ try:
408
+ if self.gnuplot.stdin is not None:
409
+ self.gnuplot.stdin.write(
410
+ "exit\n") # End gnuplot gracefully
411
+ self.gnuplot.stdin.close()
412
+ except (OSError, ValueError) as e:
413
+ print(f"Python: Error closing gnuplot: {e}")
414
+ try:
415
+ self.gnuplot.wait(timeout=3)
416
+ except subprocess.TimeoutExpired:
417
+ self.gnuplot.terminate()
418
+ try:
419
+ self.gnuplot.wait(timeout=2)
420
+ except subprocess.TimeoutExpired:
421
+ self.gnuplot.kill()
422
+ self.gnuplot.wait()
423
+ # Check if gnuplot returned an error:
424
+ if self.gnuplot.returncode: # non-zero (and not None)
425
+ print(
426
+ f"\nPython: gnuplot reported an error! To find the exact line, run:\n"
427
+ f" gnuplot \"{self.script_filename}\"\n"
428
+ f"Then open \"{self.script_filename}\" and look for the comments \n"
429
+ "near that line that point back to the Python source.\n")
430
+
431
+ def _mouse_measurement_cmds(self) -> str:
432
+ """Gnuplot code that adds the ability to measure deltas and gradients using
433
+ the mouse on an interactive plot. Very cool!
434
+
435
+ When in use press 'm' or 'M' in plot window to get started or Esc or Return to quit.
436
+ The measurement labels are removed again on exit.
437
+ """
438
+ return r"""
439
+ # gnuplot script to do measurements with the mouse. Neil Temperley 2025-04-29
440
+ # Esc or Enter to exit loop
441
+ l901 = 0; l902 = 0
442
+ pause mouse keypress "\nGnuplot: Click in gnuplot window, then press 'm' key to change mouse buttons to measure deltas and gradients,\n otherwise click in gnuplot window then press Esc or Enter to quit measurement..."
443
+ while (1) {
444
+ if (MOUSE_KEY == 27 || MOUSE_KEY == 10 || MOUSE_KEY == 13) { # 27 = Esc or Enter to exit
445
+ print "\nGnuplot: Now press Enter here (in terminal window) to continue..."
446
+ break
447
+ }
448
+ if (MOUSE_KEY == 109 || MOUSE_KEY == 77) { # 109='m' or 77='M' key to measure gradient
449
+ pause mouse "\nGnuplot: First point for gradient.."
450
+ if (exists("MOUSE_BUTTON")) {
451
+ mx11 = MOUSE_X; my11 = MOUSE_Y; my21 = MOUSE_Y2;
452
+ print sprintf("\nGnuplot: Mouse button %d at x1, y1, y2 = %.8g, %.8g, %.8g", MOUSE_BUTTON, MOUSE_X, MOUSE_Y, MOUSE_Y2)
453
+ set label 901 sprintf(" Point 1!")
454
+ set label 901 at MOUSE_X, MOUSE_Y
455
+ set label 901 point pt 6 ps 3
456
+ l901 = 1
457
+ replot
458
+ } else {
459
+ print "Gnuplot: No mouse click?"
460
+ }
461
+ pause mouse "Gnuplot: Second point for gradient.."
462
+ if (exists("MOUSE_BUTTON")) {
463
+ mx12 = MOUSE_X; my12 = MOUSE_Y; my22 = MOUSE_Y2;
464
+ print sprintf("\nGnuplot: Mouse button %d at x1, y1, y2 = %.8g, %.8g, %.8g", MOUSE_BUTTON, MOUSE_X, MOUSE_Y, MOUSE_Y2)
465
+ set label 902 sprintf(" Point 2!")
466
+ set label 902 at MOUSE_X, MOUSE_Y
467
+ set label 902 point pt 6 ps 3
468
+ l902 = 1
469
+ replot
470
+ } else {
471
+ print "Gnuplot: No mouse click?"
472
+ }
473
+ print sprintf("## Gnuplot: Deltas: deltax = %9.6g; deltay = %9.6g; deltay2 = %9.6g;", (mx12-mx11), (my12-my11), (my22-my21))
474
+ if ((mx12-mx11) != 0.) {
475
+ print sprintf("## Gnuplot: Gradients: dy1/dx1 = %9.6g; dy2/dx1 = %9.6g;", (my12-my11)/(mx12-mx11), (my22-my21)/(mx12-mx11))
476
+ }
477
+ print "Gnuplot: Mouse reset to normal!.."
478
+ }
479
+ pause mouse keypress "\nGnuplot: Click in gnuplot window, then press 'm' key to change mouse buttons to measure deltas and gradients,\n otherwise click in gnuplot window, then press Esc or Enter to quit measurement..."
480
+ }
481
+ # Tidy up so the labels don't leak into later plots:
482
+ if (l901) { unset label 901 }
483
+ if (l902) { unset label 902 }
484
+ """