Debian Codegraph @

pyvista/core/utilities/observers.py

raw
1 """Core error utilities."""
2
3 from __future__ import annotations
4
5 import importlib.util
6 import logging
7 from pathlib import Path
8 import re
9 import signal
10 import sys
11 import threading
12 import traceback
13 from typing import TYPE_CHECKING
14 from typing import NamedTuple
15
16 from pyvista import _vtk
17 from pyvista._deprecate_positional_args import _deprecate_positional_args
18 from pyvista._warn_external import warn_external
19 from pyvista.core.errors import VTKExecutionError
20 from pyvista.core.errors import VTKExecutionWarning
21 from pyvista.core.utilities.misc import _NoNewAttrMixin
22
23 log = logging.getLogger(__name__)
24
25 if TYPE_CHECKING:
26 from typing_extensions import Self
27
28
29 def set_error_output_file(filename):
30 """Set a file to write out the VTK errors.
31
32 Parameters
33 ----------
34 filename : str, Path
35 Path to the file to write VTK errors to.
36
37 Returns
38 -------
39 :vtk:`vtkFileOutputWindow`
40 VTK file output window.
41 :vtk:`vtkOutputWindow`
42 VTK output window.
43
44 """
45 filename = Path(filename).expanduser().resolve()
46 fileOutputWindow = _vtk.vtkFileOutputWindow()
47 fileOutputWindow.SetFileName(filename)
48 outputWindow = _vtk.vtkOutputWindow()
49 outputWindow.SetInstance(fileOutputWindow)
50 return fileOutputWindow, outputWindow
51
52
53 class VtkErrorCatcher:
54 """Context manager to temporarily catch VTK errors.
55
56 Parameters
57 ----------
58 raise_errors : bool, default: False
59 Raise a ``pyvista.VTKExecutionError`` (a runtime error) when a VTK error
60 is observed.
61
62 .. versionchanged:: 0.47
63
64 A ``pyvista.VTKExecutionError`` is now raised instead of a generic
65 ``RuntimeError``.
66
67 send_to_logging : bool, default: True
68 Determine whether VTK errors raised within the context should
69 also be sent to logging.
70
71 emit_warnings : bool, default: False
72 Emit a ``pyvista.VTKExecutionWarning`` (a runtime warning) when a VTK warning
73 is observed.
74
75 .. versionadded:: 0.47
76
77 Examples
78 --------
79 Catch VTK errors using the context manager. This only sends to
80 logging by default.
81
82 >>> import pyvista as pv
83 >>> with pv.VtkErrorCatcher() as error_catcher:
84 ... sphere = pv.Sphere()
85
86 Raise VTK errors as Python errors and emit VTK warnings as Python warnings.
87
88 >>> with pv.VtkErrorCatcher(
89 ... raise_errors=True, emit_warnings=True
90 ... ) as error_catcher:
91 ... sphere = pv.Sphere()
92
93 """
94
95 @_deprecate_positional_args
96 def __init__(
97 self,
98 raise_errors: bool = False, # noqa: FBT001, FBT002
99 send_to_logging: bool = True, # noqa: FBT001, FBT002
100 emit_warnings: bool = False, # noqa: FBT001, FBT002
101 ) -> None:
102 """Initialize context manager."""
103 self.raise_errors = raise_errors
104 self.send_to_logging = send_to_logging
105 self.emit_warnings = emit_warnings
106
107 def __enter__(self: Self) -> Self:
108 """Observe VTK string output window for errors."""
109 self._start_observing()
110 return self
111
112 def _start_observing(self):
113 output_window = _vtk.vtkStringOutputWindow()
114 error_win = _vtk.vtkOutputWindow()
115 self._error_output_orig = error_win.GetInstance()
116 error_win.SetInstance(output_window)
117
118 obs = Observer(event_type='ErrorEvent', log=self.send_to_logging, store_history=True)
119 obs.observe(output_window)
120 self._error_observer = obs
121
122 obs = Observer(event_type='WarningEvent', log=self.send_to_logging, store_history=True)
123 obs.observe(output_window)
124 self._warning_observer = obs
125
126 def __exit__(self, *args):
127 """Stop observing VTK string output window."""
128 self._stop_observing()
129 self._emit_warnings_and_raise_errors()
130
131 def _stop_observing(self):
132 error_win = _vtk.vtkOutputWindow()
133 error_win.SetInstance(self._error_output_orig)
134
135 def _emit_warnings_and_raise_errors(self):
136 if self.emit_warnings and self.warning_events:
137 self._emit_warning(self._runtime_warning_message)
138 if self.raise_errors and self.error_events:
139 self._raise_error(self._runtime_error_message)
140
141 @property
142 def events(self) -> list[VtkEvent]: # numpydoc ignore=RT01
143 """List of all VTK warning and error events observed.
144
145 .. versionadded:: 0.47
146
147 """
148 return [*self._warning_observer.event_history, *self._error_observer.event_history]
149
150 @property
151 def error_events(self) -> list[VtkEvent]: # numpydoc ignore=RT01
152 """List of VTK error events observed.
153
154 .. versionadded:: 0.47
155
156 """
157 return self._error_observer.event_history
158
159 @property
160 def warning_events(self) -> list[VtkEvent]: # numpydoc ignore=RT01
161 """List of VTK error events observed.
162
163 .. versionadded:: 0.47
164
165 """
166 return self._warning_observer.event_history
167
168 @property
169 def _runtime_error_message(self) -> str: # numpydoc ignore=RT01
170 """List of VTK error events formatted as runtime errors."""
171 return '\n'.join([str(e) for e in self.error_events])
172
173 @property
174 def _runtime_warning_message(self) -> str: # numpydoc ignore=RT01
175 """List of VTK error events formatted as runtime errors."""
176 return '\n'.join([str(e) for e in self.warning_events])
177
178 def _raise_error(self, message: str):
179 raise VTKExecutionError(message)
180
181 def _emit_warning(self, message: str):
182 warn_external(message, VTKExecutionWarning)
183
184
185 class VtkEvent(NamedTuple):
186 """Named tuple to store VTK event information."""
187
188 kind: str
189 path: str
190 address: str
191 alert: str
192 line: str
193 name: str
194
195 def __str__(self):
196 if all(self):
197 return (
198 f'{self.kind}: In {self.path}, line {self.line}\n'
199 f'{self.name} ({self.address}): {self.alert}'
200 ).strip()
201 return self.alert
202
203
204 class Observer(_NoNewAttrMixin):
205 """A standard class for observing VTK objects."""
206
207 @_deprecate_positional_args(allowed=['event_type'])
208 def __init__(
209 self,
210 event_type='ErrorEvent',
211 log: bool = True, # noqa: FBT001, FBT002
212 store_history: bool = False, # noqa: FBT001, FBT002
213 ) -> None:
214 """Initialize observer."""
215 self.__event_occurred: bool = False
216 self.__message: str | None = None
217 self.__message_etc: str | None = None
218 self.CallDataType = 'string0'
219 self.__observing: bool = False
220 self.event_type = event_type
221 self.__log = log
222
223 self.store_history = store_history
224 self.event_history: list[VtkEvent] = []
225 self._event_history_etc: list[str] = []
226
227 @staticmethod
228 def parse_message(message) -> VtkEvent: # numpydoc ignore=RT01
229 """Parse the given message."""
230 regex = re.compile(
231 r'(?P<kind>[a-zA-Z]+):\sIn\s(?P<path>.+?),\sline\s(?P<line>\d+)\r?\n'
232 r'(?P<name>\w+) \((?P<address>0x[0-9a-fA-F]+)\):\s(?P<alert>.+)',
233 re.DOTALL,
234 )
235
236 match = regex.match(message)
237 if match:
238 d = match.groupdict()
239 kind = d.get('kind', '')
240 path = d.get('path', '')
241 line = d.get('line', '')
242 name = d.get('name', '')
243 address = d.get('address', '')
244 alert = d.get('alert', '').strip()
245 return VtkEvent(
246 kind=kind, path=path, line=line, name=name, address=address, alert=alert
247 )
248 return VtkEvent(kind='', path='', line='', name='', address='', alert=message.strip())
249
250 def log_message(self, kind, alert) -> None:
251 """Parse different event types and passes them to logging."""
252 if kind == 'ERROR':
253 logging.error(alert) # noqa: LOG015
254 else:
255 logging.warning(alert) # noqa: LOG015
256
257 def __call__(self, _obj, _event, message) -> None:
258 """Declare standard call function for the observer.
259
260 On an event occurrence, this function executes.
261
262 """
263 try:
264 self.__event_occurred = True
265 self.__message_etc = message
266 event = self.parse_message(message)
267 self.__message = event.alert
268 if self.store_history:
269 self.event_history.append(event)
270 self._event_history_etc.append(message)
271 if self.__log:
272 self.log_message(event.kind, event.alert)
273 except Exception: # noqa: BLE001 # pragma: no cover
274 try:
275 if len(message) > 120:
276 message = f'{message[:100]!r} ... ({len(message)} characters)'
277 else:
278 message = repr(message)
279 print(
280 f'PyVista error in handling VTK error message:\n{message}',
281 file=sys.__stdout__,
282 )
283 traceback.print_tb(sys.last_traceback, file=sys.__stderr__)
284 except Exception as e: # noqa: BLE001
285 log.debug('Failed to print VTK error message: %s', e)
286
287 def has_event_occurred(self): # numpydoc ignore=RT01
288 """Ask self if an error has occurred since last queried.
289
290 This resets the observer's status.
291
292 """
293 occ = self.__event_occurred
294 self.__event_occurred = False
295 return occ
296
297 @_deprecate_positional_args
298 def get_message(self, etc: bool = False): # noqa: FBT001, FBT002
299 """Get the last set error message.
300
301 Returns
302 -------
303 str
304 The last set error message.
305
306 """
307 if etc:
308 return self.__message_etc
309 return self.__message
310
311 def observe(self, algorithm):
312 """Make this an observer of an algorithm."""
313 if self.__observing:
314 msg = 'This error observer is already observing an algorithm.'
315 raise RuntimeError(msg)
316 if hasattr(algorithm, 'GetExecutive') and algorithm.GetExecutive() is not None:
317 algorithm.GetExecutive().AddObserver(self.event_type, self)
318 algorithm.AddObserver(self.event_type, self)
319 self.__observing = True
320
321
322 def send_errors_to_logging(): # numpydoc ignore=RT01
323 """Send all VTK error/warning messages to Python's logging module."""
324 error_output = _vtk.vtkStringOutputWindow()
325 error_win = _vtk.vtkOutputWindow()
326 error_win.SetInstance(error_output)
327 obs = Observer()
328 return obs.observe(error_output)
329
330
331 class ProgressMonitor(_NoNewAttrMixin):
332 """A standard class for monitoring the progress of a VTK algorithm.
333
334 This must be use in a ``with`` context and it will block keyboard
335 interrupts from happening until the exit event as interrupts will crash
336 the kernel if the VTK algorithm is still executing.
337
338 Parameters
339 ----------
340 algorithm
341 VTK algorithm or filter.
342
343 message : str, default: ""
344 Message to display in the progress bar.
345
346 """
347
348 def __init__(self, algorithm, message=''):
349 """Initialize observer."""
350 if not importlib.util.find_spec('tqdm'):
351 msg = 'Please install `tqdm` to monitor algorithms.'
352 raise ImportError(msg)
353 self.event_type = _vtk.vtkCommand.ProgressEvent
354 self.progress = 0.0
355 self._last_progress = self.progress
356 self.algorithm = algorithm
357 self.message = message
358 self._interrupt_signal_received = False
359 self._old_progress = 0
360 self._old_handler = None
361 self._progress_bar = None
362
363 def handler(self, sig, frame) -> None:
364 """Pass signal to custom interrupt handler."""
365 self._interrupt_signal_received = (sig, frame) # type: ignore[assignment]
366 logging.debug('SIGINT received. Delaying KeyboardInterrupt until VTK algorithm finishes.') # noqa: LOG015
367
368 def __call__(self, obj, *args) -> None: # noqa: ARG002
369 """Call progress update callback.
370
371 On an event occurrence, this function executes.
372 """
373 if self._interrupt_signal_received:
374 obj.AbortExecuteOn()
375 else:
376 progress = obj.GetProgress()
377 step = progress - self._old_progress
378 self._progress_bar.update(step) # type: ignore[union-attr]
379 self._old_progress = progress
380
381 def __enter__(self):
382 """Enter event for ``with`` context."""
383 from tqdm import tqdm # noqa: PLC0415
384
385 # check if in main thread
386 if threading.current_thread().__class__.__name__ == '_MainThread':
387 self._old_handler = signal.signal(signal.SIGINT, self.handler)
388 self._progress_bar = tqdm(
389 total=1,
390 leave=True,
391 bar_format='{l_bar}{bar}[{elapsed}<{remaining}]',
392 )
393 self._progress_bar.set_description(self.message)
394 self.algorithm.AddObserver(self.event_type, self)
395 return self._progress_bar
396
397 def __exit__(self, *args) -> None:
398 """Exit event for ``with`` context."""
399 self._progress_bar.total = 1 # type: ignore[union-attr]
400 self._progress_bar.refresh() # type: ignore[union-attr]
401 self._progress_bar.close() # type: ignore[union-attr]
402 self.algorithm.RemoveObservers(self.event_type)
403 if threading.current_thread().__class__.__name__ == '_MainThread':
404 signal.signal(signal.SIGINT, self._old_handler)