|
| 1 | +# Copyright (C) 2023 - 2025 ANSYS, Inc. and/or its affiliates. |
| 2 | +# SPDX-License-Identifier: MIT |
| 3 | +# |
| 4 | +# |
| 5 | +# Permission is hereby granted, free of charge, to any person obtaining a copy |
| 6 | +# of this software and associated documentation files (the "Software"), to deal |
| 7 | +# in the Software without restriction, including without limitation the rights |
| 8 | +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 9 | +# copies of the Software, and to permit persons to whom the Software is |
| 10 | +# furnished to do so, subject to the following conditions: |
| 11 | +# |
| 12 | +# The above copyright notice and this permission notice shall be included in all |
| 13 | +# copies or substantial portions of the Software. |
| 14 | +# |
| 15 | +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 16 | +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 17 | +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 18 | +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 19 | +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 20 | +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE |
| 21 | +# SOFTWARE. |
| 22 | +"""Provides for creating and managing a nurbs sketch curve.""" |
| 23 | + |
| 24 | +from typing import TYPE_CHECKING |
| 25 | + |
| 26 | +from beartype import beartype as check_input_types |
| 27 | +import numpy as np |
| 28 | + |
| 29 | +from ansys.geometry.core.math.point import Point2D |
| 30 | +from ansys.geometry.core.misc.checks import graphics_required |
| 31 | +from ansys.geometry.core.sketch.edge import SketchEdge |
| 32 | +from ansys.geometry.core.typing import Real |
| 33 | + |
| 34 | +if TYPE_CHECKING: # pragma: no cover |
| 35 | + import geomdl.NURBS as geomdl_nurbs # noqa: N811 |
| 36 | + import pyvista as pv |
| 37 | + |
| 38 | + |
| 39 | +class SketchNurbs(SketchEdge): |
| 40 | + """Represents a NURBS sketch curve. |
| 41 | +
|
| 42 | + Warnings |
| 43 | + -------- |
| 44 | + NURBS sketching is only supported in 26R1 and later versions of Ansys. |
| 45 | +
|
| 46 | + Notes |
| 47 | + ----- |
| 48 | + This class is a wrapper around the NURBS curve class from the `geomdl` library. |
| 49 | + By leveraging the `geomdl` library, this class provides a high-level interface |
| 50 | + to create and manipulate NURBS curves. The `geomdl` library is a powerful |
| 51 | + library for working with NURBS curves and surfaces. For more information, see |
| 52 | + https://pypi.org/project/geomdl/. |
| 53 | + """ |
| 54 | + |
| 55 | + def __init__(self): |
| 56 | + """Initialize the NURBS sketch curve.""" |
| 57 | + super().__init__() |
| 58 | + try: |
| 59 | + import geomdl.NURBS as geomdl_nurbs # noqa: N811 |
| 60 | + except ImportError as e: # pragma: no cover |
| 61 | + raise ImportError( |
| 62 | + "The `geomdl` library is required to use the NURBSCurve class. " |
| 63 | + "Please install it using `pip install geomdl`." |
| 64 | + ) from e |
| 65 | + |
| 66 | + self._nurbs_curve = geomdl_nurbs.Curve() |
| 67 | + |
| 68 | + @property |
| 69 | + def geomdl_nurbs_curve(self) -> "geomdl_nurbs.Curve": |
| 70 | + """Get the underlying NURBS curve. |
| 71 | +
|
| 72 | + Notes |
| 73 | + ----- |
| 74 | + This property gives access to the full functionality of the NURBS curve |
| 75 | + coming from the `geomdl` library. Use with caution. |
| 76 | + """ |
| 77 | + return self._nurbs_curve |
| 78 | + |
| 79 | + @property |
| 80 | + def control_points(self) -> list[Point2D]: |
| 81 | + """Get the control points of the curve.""" |
| 82 | + return [Point2D(point) for point in self._nurbs_curve.ctrlpts] |
| 83 | + |
| 84 | + @property |
| 85 | + def degree(self) -> int: |
| 86 | + """Get the degree of the curve.""" |
| 87 | + return self._nurbs_curve.degree |
| 88 | + |
| 89 | + @property |
| 90 | + def knots(self) -> list[Real]: |
| 91 | + """Get the knot vector of the curve.""" |
| 92 | + return self._nurbs_curve.knotvector |
| 93 | + |
| 94 | + @property |
| 95 | + def weights(self) -> list[Real]: |
| 96 | + """Get the weights of the control points.""" |
| 97 | + return self._nurbs_curve.weights |
| 98 | + |
| 99 | + @property |
| 100 | + def start(self) -> Point2D: |
| 101 | + """Get the start point of the curve.""" |
| 102 | + return Point2D(self._nurbs_curve.evaluate_single(0.0)) |
| 103 | + |
| 104 | + @property |
| 105 | + def end(self) -> Point2D: |
| 106 | + """Get the end point of the curve.""" |
| 107 | + return Point2D(self._nurbs_curve.evaluate_single(1.0)) |
| 108 | + |
| 109 | + @property |
| 110 | + @graphics_required |
| 111 | + def visualization_polydata(self) -> "pv.PolyData": |
| 112 | + """Get the VTK polydata representation for PyVista visualization. |
| 113 | +
|
| 114 | + Returns |
| 115 | + ------- |
| 116 | + pyvista.PolyData |
| 117 | + VTK pyvista.Polydata configuration. |
| 118 | +
|
| 119 | + Notes |
| 120 | + ----- |
| 121 | + The representation lies in the X/Y plane within |
| 122 | + the standard global Cartesian coordinate system. |
| 123 | + """ |
| 124 | + import pyvista as pv |
| 125 | + |
| 126 | + # Sample points along the curve |
| 127 | + params = np.linspace(0, 1, 100) |
| 128 | + points = [self._nurbs_curve.evaluate_single(u) for u in params] # For 2D: [x, y] |
| 129 | + |
| 130 | + # Add a zero z-coordinate for PyVista (only supports 3D points) |
| 131 | + points = [(*pt, 0.0) for pt in points] |
| 132 | + |
| 133 | + # Create PolyData and add the line |
| 134 | + polydata = pv.PolyData(points) |
| 135 | + polydata.lines = [len(points)] + list(range(len(points))) |
| 136 | + |
| 137 | + return polydata |
| 138 | + |
| 139 | + def contains_point(self, point: Point2D, tolerance: Real = 1e-6) -> bool: |
| 140 | + """Check if the curve contains a given point within a specified tolerance. |
| 141 | +
|
| 142 | + Parameters |
| 143 | + ---------- |
| 144 | + point : Point2D |
| 145 | + The point to check. |
| 146 | + tolerance : Real, optional |
| 147 | + The tolerance for the containment check, by default 1e-6. |
| 148 | +
|
| 149 | + Returns |
| 150 | + ------- |
| 151 | + bool |
| 152 | + True if the curve contains the point within the tolerance, False otherwise. |
| 153 | + """ |
| 154 | + # Sample points along the curve |
| 155 | + params = np.linspace(0, 1, 200) |
| 156 | + sampled = [self._nurbs_curve.evaluate_single(u) for u in params] |
| 157 | + |
| 158 | + # Check if any sampled point is close to the target point |
| 159 | + return any(np.linalg.norm(np.array(pt) - np.array(point)) < tolerance for pt in sampled) |
| 160 | + |
| 161 | + @classmethod |
| 162 | + @check_input_types |
| 163 | + def fit_curve_from_points( |
| 164 | + cls, |
| 165 | + points: list[Point2D], |
| 166 | + degree: int = 3, |
| 167 | + ) -> "SketchNurbs": |
| 168 | + """Fit a NURBS curve to a set of points. |
| 169 | +
|
| 170 | + Parameters |
| 171 | + ---------- |
| 172 | + points : list[Point2D] |
| 173 | + The points to fit the curve to. |
| 174 | + degree : int, optional |
| 175 | + The degree of the NURBS curve, by default 3. |
| 176 | +
|
| 177 | + Returns |
| 178 | + ------- |
| 179 | + SketchNurbs |
| 180 | + A new instance of SketchNurbs fitted to the given points. |
| 181 | + """ |
| 182 | + from geomdl import fitting |
| 183 | + |
| 184 | + # Check degree compared to number of points provided |
| 185 | + if degree < 1: |
| 186 | + raise ValueError("Degree must be at least 1.") |
| 187 | + if len(points) == 2: |
| 188 | + degree = 1 # Force linear interpolation for two points |
| 189 | + if len(points) == 3: |
| 190 | + degree = 2 # Force quadratic interpolation for three points |
| 191 | + if degree >= len(points): |
| 192 | + raise ValueError( |
| 193 | + f"Degree {degree} is too high for the number of points provided: {len(points)}." |
| 194 | + ) |
| 195 | + |
| 196 | + curve = fitting.interpolate_curve( |
| 197 | + [[*pt] for pt in points], # Convert Point2D to list of coordinates |
| 198 | + degree=degree, |
| 199 | + ) |
| 200 | + |
| 201 | + # Construct the NURBSCurve object |
| 202 | + nurbs_curve = cls() |
| 203 | + nurbs_curve._nurbs_curve.degree = curve.degree |
| 204 | + nurbs_curve._nurbs_curve.ctrlpts = [Point2D(entry) for entry in curve.ctrlpts] |
| 205 | + nurbs_curve._nurbs_curve.knotvector = curve.knotvector |
| 206 | + nurbs_curve._nurbs_curve.weights = curve.weights |
| 207 | + |
| 208 | + # Verify the curve is valid |
| 209 | + try: |
| 210 | + nurbs_curve._nurbs_curve._check_variables() |
| 211 | + except ValueError as e: |
| 212 | + raise ValueError(f"Invalid NURBS curve: {e}") |
| 213 | + |
| 214 | + return nurbs_curve |
0 commit comments