Debian Codegraph @

pyvista/_cli/validate.py

raw
1 """`pyvista report` CLI."""
2
3 from __future__ import annotations
4
5 from typing import TYPE_CHECKING
6 from typing import Annotated
7 from typing import cast
8 from typing import get_args
9
10 from cyclopts import Parameter
11
12 import pyvista as pv
13 from pyvista.core.filters.data_object import _LiteralMeshValidationFields
14 from pyvista.core.filters.data_object import _MeshValidator
15 from pyvista.core.filters.data_object import _ReportBodyOptions
16
17 from .app import app
18 from .utils import HELP_FORMATTER
19 from .utils import _console_error
20 from .utils import _converter_files
21
22 if TYPE_CHECKING:
23 from collections.abc import Sequence
24 from pathlib import Path
25
26 from cyclopts import Token
27
28 from .utils import _MeshAndPath
29
30 fields_help = """
31 Field(s) to validate. Specify individual field(s) or group(s) of fields:
32
33 **Data fields**
34
35 - ``cell_data_wrong_length``: Ensure the length of each cell data array matches _n_cells_.
36 - ``point_data_wrong_length``: Ensure the length of each point data array matches _n_points_.
37
38 **Point fields**
39
40 - ``non_finite_points``: Ensure all points have real values (i.e. no _NaN_ or _Inf_).
41 - ``unused_points``: Ensure all points are referenced by at least one cell.
42
43 **Cell fields**
44
45 - ``coincident_points``: Ensure there are no duplicate coordinates or repeated use of the
46 same connectivity entry.
47 - ``degenerate_faces``: Ensure faces do not collapse to a line or a point through repeated
48 collocated vertices.
49 - ``intersecting_edges``: Ensure two edges of a 2D cell do not intersect.
50 - ``intersecting_faces``: Ensure two faces of a 3D cell do not intersect.
51 - ``invalid_point_references``: Ensure all points referenced by cells are valid point ids
52 that can be indexed by a dataset's _points_.
53 - ``inverted_faces``: Ensure the faces of a cell point in the direction required by its
54 cell type.
55 - ``negative_size``: Ensure 1D, 2D, and 3D cells have positive length, area, and volume,
56 respectively.
57 - ``non_contiguous_edges``: Ensure edges around the perimeter of a 2D cell are contiguous.
58 - ``non_convex``: Ensure all 2D and 3D cells are convex.
59 - ``non_planar_faces``: Ensure vertices for a face all lie in the same plane.
60 - ``wrong_number_of_points``: Ensure each cell has the minimum number of points needed to
61 describe it.
62 - ``zero_size``: Ensure 1D, 2D, and 3D cells have non-zero length, area, and volume,
63 respectively.
64
65 **Field groups**
66
67 - ``data``: Validate all data fields.
68 - ``points``: Validate all point fields.
69 - ``cells``: Validate all cell fields.
70 - ``memory_safe``: Validate all fields that, if invalid, may cause a segmentation
71 fault and crash Python. Includes ``cell_data_wrong_length``,
72 ``point_data_wrong_length``, and ``invalid_point_references``.
73 """
74 exclude_help = """
75 Field(s) to exclude from the validation. This is similar to using FIELDS, but is subtractive
76 instead of additive.
77 """
78 tolerance_help = """
79 Value used for most floating point equality checks throughout the cell checking process, e.g. for
80 checking coincident points or intersecting edges.
81 """
82 planarity_tolerance_help = """
83 Allowed relative distance a planar polyhedral cell face may protrude out of its plane compared to
84 the largest distance between a face center and any of its corner points.
85 """
86 size_tolerance_help = """
87 Value used for evaluating the size of a cell. Cells with an absolute size less than or equal to
88 this value are flagged as having zero size, and cells with a size less than this value are flagged
89 as having negative size.
90 """
91 report_help = """
92 Show report. Control the body of the report with:
93 - ``fields`` to show all validation fields.
94 - ``message`` to show the error message (if any).
95
96 ``message`` is used by default if no tokens are passed.
97 """
98
99
100 def _converter_report(
101 type_: type, # noqa: ARG001
102 tokens: Sequence[Token],
103 ) -> list[_ReportBodyOptions]:
104 values: list[str] = [t.value for t in tokens]
105 n_values = len(values)
106 if n_values > 1:
107 msg = f'Invalid value for {tokens[0].keyword}: accepts 0 or 1 arguments. Got {n_values}.'
108 raise ValueError(msg)
109 value = values[0]
110 allowed = get_args(_ReportBodyOptions)
111 if value in allowed:
112 return cast('list[_ReportBodyOptions]', [value])
113 msg = f'expected one of {str(allowed)[1:-1]} or no value. Got {value!r}.'
114 raise ValueError(msg)
115
116
117 def _insert_mesh_path(string: str, path: Path) -> str:
118 return string.replace('mesh is not valid', f'mesh {path.name!r} is not valid', 1)
119
120
121 @app.command(
122 usage=f'Usage: [bold]{pv.__name__} validate MESH-PATH [FIELDS...] [--exclude FIELDS...]',
123 help_formatter=HELP_FORMATTER,
124 help="Validate a mesh's array data, points, and cells.",
125 )
126 def _validate(
127 mesh_path: Annotated[
128 str,
129 Parameter(
130 help=(
131 'Mesh to validate. Must be readable with ``pyvista.read``. '
132 'Glob patterns (``*``, ``?``, ``[...]``) are expanded; '
133 'every match is validated in turn.'
134 ),
135 converter=_converter_files,
136 ),
137 ],
138 fields: Annotated[
139 list[_LiteralMeshValidationFields] | None,
140 Parameter(
141 name='fields',
142 consume_multiple=True,
143 negative=[],
144 help=fields_help,
145 ),
146 ] = None,
147 *,
148 exclude: Annotated[
149 list[_LiteralMeshValidationFields] | None,
150 Parameter(
151 name=('exclude', '-e'),
152 consume_multiple=True,
153 negative=[],
154 help=exclude_help,
155 ),
156 ] = None,
157 tolerance: Annotated[
158 float | None,
159 Parameter(
160 name='tolerance',
161 show_default=False,
162 help=tolerance_help,
163 ),
164 ] = None,
165 planarity_tolerance: Annotated[
166 float | None,
167 Parameter(
168 name='planarity-tolerance',
169 show_default=False,
170 help=planarity_tolerance_help,
171 ),
172 ] = None,
173 size_tolerance: Annotated[
174 float | None,
175 Parameter(
176 name='size-tolerance',
177 show_default=False,
178 help=size_tolerance_help,
179 ),
180 ] = None,
181 report: Annotated[
182 list[_ReportBodyOptions] | None,
183 Parameter(
184 name='report',
185 consume_multiple=True,
186 converter=_converter_report,
187 show_default=False,
188 negative=[],
189 help=report_help,
190 ),
191 ] = None,
192 ) -> None:
193 # Cyclopts declares ``mesh_path`` as ``str`` for CLI parsing but ``_converter_files``
194 # replaces the string token with the list of read meshes — narrow the type here.
195 items: list[_MeshAndPath] = mesh_path # type: ignore[assignment]
196 report_body = report[0] if report else 'message'
197 for item in items:
198 mesh = item.mesh
199 if not isinstance(mesh, (pv.DataSet, pv.MultiBlock)):
200 msg = (
201 f'Cannot validate {type(mesh).__name__} read from path {str(item.path)!r}: '
202 f'only DataSet and MultiBlock meshes are supported.'
203 )
204 _console_error(app=app, message=msg)
205 _validate_one(
206 mesh,
207 item.path,
208 fields=fields,
209 exclude=exclude,
210 tolerance=tolerance,
211 planarity_tolerance=planarity_tolerance,
212 size_tolerance=size_tolerance,
213 report=report,
214 report_body=report_body,
215 )
216
217
218 def _validate_one(
219 mesh: pv.DataSet | pv.MultiBlock,
220 path: Path,
221 *,
222 fields: list[_LiteralMeshValidationFields] | None,
223 exclude: list[_LiteralMeshValidationFields] | None,
224 tolerance: float | None,
225 planarity_tolerance: float | None,
226 size_tolerance: float | None,
227 report: list[_ReportBodyOptions] | None,
228 report_body: _ReportBodyOptions,
229 ) -> None:
230 """Validate a single mesh and print its result to the console."""
231 class_name = mesh.__class__.__name__
232 try:
233 out = pv.DataObjectFilters.validate_mesh(
234 mesh,
235 validation_fields=fields,
236 exclude_fields=exclude,
237 tolerance=tolerance,
238 planarity_tolerance=planarity_tolerance,
239 size_tolerance=size_tolerance,
240 report_body=report_body,
241 )
242 except Exception as e: # noqa: BLE001
243 msg = f'Failed to validate {class_name} mesh read from path {str(path)!r}\n{e}'
244 _console_error(app=app, message=msg)
245 else:
246 if report is not None:
247 # Print the full report
248 report_string = str(out)
249 if report_body == 'fields':
250 invalid_fields = out.invalid_fields
251 else:
252 invalid_fields = None
253 report_string = _insert_mesh_path(report_string, path)
254 app.console.print(_MeshValidator._colorize_output(report_string, invalid_fields))
255 elif (message := out.message) is not None:
256 # Only print the error message and show the file name
257 message = _insert_mesh_path(message, path)
258 app.console.print(_MeshValidator._colorize_output(message))
259 else:
260 # Mesh is valid
261 app.console.print(f'[green]{class_name} mesh {path.name!r} is valid![/green]')