File: observers.py

package info (click to toggle)
python-pyvista 0.46.5-6
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 178,808 kB
  • sloc: python: 94,599; sh: 216; makefile: 70
file content (406 lines) | stat: -rw-r--r-- 13,487 bytes parent folder | download | duplicates (4)
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
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
371
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
"""Core error utilities."""

from __future__ import annotations

import importlib.util
import logging
from pathlib import Path
import re
import signal
import sys
import threading
import traceback
from typing import TYPE_CHECKING
from typing import NamedTuple

import pyvista
from pyvista._deprecate_positional_args import _deprecate_positional_args
from pyvista._warn_external import warn_external
from pyvista.core import _vtk_core as _vtk
from pyvista.core.errors import VTKExecutionError
from pyvista.core.errors import VTKExecutionWarning
from pyvista.core.utilities.misc import _NoNewAttrMixin

if TYPE_CHECKING:
    from typing_extensions import Self


def set_error_output_file(filename):
    """Set a file to write out the VTK errors.

    Parameters
    ----------
    filename : str, Path
        Path to the file to write VTK errors to.

    Returns
    -------
    :vtk:`vtkFileOutputWindow`
        VTK file output window.
    :vtk:`vtkOutputWindow`
        VTK output window.

    """
    filename = Path(filename).expanduser().resolve()
    fileOutputWindow = _vtk.vtkFileOutputWindow()
    if pyvista.vtk_version_info < (9, 2, 2):  # pragma no cover
        fileOutputWindow.SetFileName(str(filename))
    else:
        fileOutputWindow.SetFileName(filename)
    outputWindow = _vtk.vtkOutputWindow()
    outputWindow.SetInstance(fileOutputWindow)
    return fileOutputWindow, outputWindow


class VtkErrorCatcher:
    """Context manager to temporarily catch VTK errors.

    Parameters
    ----------
    raise_errors : bool, default: False
        Raise a ``pyvista.VTKExecutionError`` (a runtime error) when a VTK error
        is observed.

        .. versionchanged:: 0.47

            A ``pyvista.VTKExecutionError`` is now raised instead of a generic
            ``RuntimeError``.

    send_to_logging : bool, default: True
        Determine whether VTK errors raised within the context should
        also be sent to logging.

    emit_warnings : bool, default: False
        Emit a ``pyvista.VTKExecutionWarning`` (a runtime warning) when a VTK warning
        is observed.

        .. versionadded:: 0.47

    Examples
    --------
    Catch VTK errors using the context manager. This only sends to
    logging by default.

    >>> import pyvista as pv
    >>> with pv.VtkErrorCatcher() as error_catcher:
    ...     sphere = pv.Sphere()

    Raise VTK errors as Python errors and emit VTK warnings as Python warnings.

    >>> with pv.VtkErrorCatcher(
    ...     raise_errors=True, emit_warnings=True
    ... ) as error_catcher:
    ...     sphere = pv.Sphere()

    """

    @_deprecate_positional_args
    def __init__(
        self,
        raise_errors: bool = False,  # noqa: FBT001, FBT002
        send_to_logging: bool = True,  # noqa: FBT001, FBT002
        emit_warnings: bool = False,  # noqa: FBT001, FBT002
    ) -> None:
        """Initialize context manager."""
        self.raise_errors = raise_errors
        self.send_to_logging = send_to_logging
        self.emit_warnings = emit_warnings

    def __enter__(self: Self) -> Self:
        """Observe VTK string output window for errors."""
        self._start_observing()
        return self

    def _start_observing(self):
        output_window = _vtk.vtkStringOutputWindow()
        error_win = _vtk.vtkOutputWindow()
        self._error_output_orig = error_win.GetInstance()
        error_win.SetInstance(output_window)

        obs = Observer(event_type='ErrorEvent', log=self.send_to_logging, store_history=True)
        obs.observe(output_window)
        self._error_observer = obs

        obs = Observer(event_type='WarningEvent', log=self.send_to_logging, store_history=True)
        obs.observe(output_window)
        self._warning_observer = obs

    def __exit__(self, *args):
        """Stop observing VTK string output window."""
        self._stop_observing()
        self._emit_warnings_and_raise_errors()

    def _stop_observing(self):
        error_win = _vtk.vtkOutputWindow()
        error_win.SetInstance(self._error_output_orig)

    def _emit_warnings_and_raise_errors(self):
        if self.emit_warnings and self.warning_events:
            self._emit_warning(self._runtime_warning_message)
        if self.raise_errors and self.error_events:
            self._raise_error(self._runtime_error_message)

    @property
    def events(self) -> list[VtkEvent]:  # numpydoc ignore=RT01
        """List of all VTK warning and error events observed.

        .. versionadded:: 0.47

        """
        return [*self._warning_observer.event_history, *self._error_observer.event_history]

    @property
    def error_events(self) -> list[VtkEvent]:  # numpydoc ignore=RT01
        """List of VTK error events observed.

        .. versionadded:: 0.47

        """
        return self._error_observer.event_history

    @property
    def warning_events(self) -> list[VtkEvent]:  # numpydoc ignore=RT01
        """List of VTK error events observed.

        .. versionadded:: 0.47

        """
        return self._warning_observer.event_history

    @property
    def _runtime_error_message(self) -> str:  # numpydoc ignore=RT01
        """List of VTK error events formatted as runtime errors."""
        return '\n'.join([str(e) for e in self.error_events])

    @property
    def _runtime_warning_message(self) -> str:  # numpydoc ignore=RT01
        """List of VTK error events formatted as runtime errors."""
        return '\n'.join([str(e) for e in self.warning_events])

    def _raise_error(self, message: str):
        raise VTKExecutionError(message)

    def _emit_warning(self, message: str):
        warn_external(message, VTKExecutionWarning)


class VtkEvent(NamedTuple):
    """Named tuple to store VTK event information."""

    kind: str
    path: str
    address: str
    alert: str
    line: str
    name: str

    def __str__(self):
        if all(self):
            return (
                f'{self.kind}: In {self.path}, line {self.line}\n'
                f'{self.name} ({self.address}): {self.alert}'
            ).strip()
        return self.alert


class Observer(_NoNewAttrMixin):
    """A standard class for observing VTK objects."""

    @_deprecate_positional_args(allowed=['event_type'])
    def __init__(
        self,
        event_type='ErrorEvent',
        log: bool = True,  # noqa: FBT001, FBT002
        store_history: bool = False,  # noqa: FBT001, FBT002
    ) -> None:
        """Initialize observer."""
        self.__event_occurred: bool = False
        self.__message: str | None = None
        self.__message_etc: str | None = None
        self.CallDataType = 'string0'
        self.__observing: bool = False
        self.event_type = event_type
        self.__log = log

        self.store_history = store_history
        self.event_history: list[VtkEvent] = []
        self._event_history_etc: list[str] = []

    @staticmethod
    def parse_message(message) -> VtkEvent:  # numpydoc ignore=RT01
        """Parse the given message."""
        regex = re.compile(
            r'(?P<kind>[a-zA-Z]+):\sIn\s(?P<path>.+?),\sline\s(?P<line>\d+)\r?\n'
            r'(?P<name>\w+) \((?P<address>0x[0-9a-fA-F]+)\):\s(?P<alert>.+)',
            re.DOTALL,
        )

        match = regex.match(message)
        if match:
            d = match.groupdict()
            kind = d.get('kind', '')
            path = d.get('path', '')
            line = d.get('line', '')
            name = d.get('name', '')
            address = d.get('address', '')
            alert = d.get('alert', '').strip()
            return VtkEvent(
                kind=kind, path=path, line=line, name=name, address=address, alert=alert
            )
        return VtkEvent(kind='', path='', line='', name='', address='', alert=message.strip())

    def log_message(self, kind, alert) -> None:
        """Parse different event types and passes them to logging."""
        if kind == 'ERROR':
            logging.error(alert)  # noqa: LOG015
        else:
            logging.warning(alert)  # noqa: LOG015

    def __call__(self, _obj, _event, message) -> None:
        """Declare standard call function for the observer.

        On an event occurrence, this function executes.

        """
        try:
            self.__event_occurred = True
            self.__message_etc = message
            event = self.parse_message(message)
            self.__message = event.alert
            if self.store_history:
                self.event_history.append(event)
                self._event_history_etc.append(message)
            if self.__log:
                self.log_message(event.kind, event.alert)
        except Exception:  # noqa: BLE001  # pragma: no cover
            try:
                if len(message) > 120:
                    message = f'{message[:100]!r} ... ({len(message)} characters)'
                else:
                    message = repr(message)
                print(
                    f'PyVista error in handling VTK error message:\n{message}',
                    file=sys.__stdout__,
                )
                traceback.print_tb(sys.last_traceback, file=sys.__stderr__)
            except Exception:  # noqa: BLE001
                pass

    def has_event_occurred(self):  # numpydoc ignore=RT01
        """Ask self if an error has occurred since last queried.

        This resets the observer's status.

        """
        occ = self.__event_occurred
        self.__event_occurred = False
        return occ

    @_deprecate_positional_args
    def get_message(self, etc: bool = False):  # noqa: FBT001, FBT002
        """Get the last set error message.

        Returns
        -------
        str
            The last set error message.

        """
        if etc:
            return self.__message_etc
        return self.__message

    def observe(self, algorithm):
        """Make this an observer of an algorithm."""
        if self.__observing:
            msg = 'This error observer is already observing an algorithm.'
            raise RuntimeError(msg)
        if hasattr(algorithm, 'GetExecutive') and algorithm.GetExecutive() is not None:
            algorithm.GetExecutive().AddObserver(self.event_type, self)
        algorithm.AddObserver(self.event_type, self)
        self.__observing = True


def send_errors_to_logging():  # numpydoc ignore=RT01
    """Send all VTK error/warning messages to Python's logging module."""
    error_output = _vtk.vtkStringOutputWindow()
    error_win = _vtk.vtkOutputWindow()
    error_win.SetInstance(error_output)
    obs = Observer()
    return obs.observe(error_output)


class ProgressMonitor(_NoNewAttrMixin):
    """A standard class for monitoring the progress of a VTK algorithm.

    This must be use in a ``with`` context and it will block keyboard
    interrupts from happening until the exit event as interrupts will crash
    the kernel if the VTK algorithm is still executing.

    Parameters
    ----------
    algorithm
        VTK algorithm or filter.

    message : str, default: ""
        Message to display in the progress bar.

    """

    def __init__(self, algorithm, message=''):
        """Initialize observer."""
        if not importlib.util.find_spec('tqdm'):
            msg = 'Please install `tqdm` to monitor algorithms.'
            raise ImportError(msg)
        self.event_type = _vtk.vtkCommand.ProgressEvent
        self.progress = 0.0
        self._last_progress = self.progress
        self.algorithm = algorithm
        self.message = message
        self._interrupt_signal_received = False
        self._old_progress = 0
        self._old_handler = None
        self._progress_bar = None

    def handler(self, sig, frame) -> None:
        """Pass signal to custom interrupt handler."""
        self._interrupt_signal_received = (sig, frame)  # type: ignore[assignment]
        logging.debug('SIGINT received. Delaying KeyboardInterrupt until VTK algorithm finishes.')  # noqa: LOG015

    def __call__(self, obj, *args) -> None:  # noqa: ARG002
        """Call progress update callback.

        On an event occurrence, this function executes.
        """
        if self._interrupt_signal_received:
            obj.AbortExecuteOn()
        else:
            progress = obj.GetProgress()
            step = progress - self._old_progress
            self._progress_bar.update(step)  # type: ignore[union-attr]
            self._old_progress = progress

    def __enter__(self):
        """Enter event for ``with`` context."""
        from tqdm import tqdm  # noqa: PLC0415

        # check if in main thread
        if threading.current_thread().__class__.__name__ == '_MainThread':
            self._old_handler = signal.signal(signal.SIGINT, self.handler)
        self._progress_bar = tqdm(
            total=1,
            leave=True,
            bar_format='{l_bar}{bar}[{elapsed}<{remaining}]',
        )
        self._progress_bar.set_description(self.message)
        self.algorithm.AddObserver(self.event_type, self)
        return self._progress_bar

    def __exit__(self, *args) -> None:
        """Exit event for ``with`` context."""
        self._progress_bar.total = 1  # type: ignore[union-attr]
        self._progress_bar.refresh()  # type: ignore[union-attr]
        self._progress_bar.close()  # type: ignore[union-attr]
        self.algorithm.RemoveObservers(self.event_type)
        if threading.current_thread().__class__.__name__ == '_MainThread':
            signal.signal(signal.SIGINT, self._old_handler)