capytaine 2.3__cp312-cp312-win_amd64.whl → 3.0.0a1__cp312-cp312-win_amd64.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.
Files changed (88) hide show
  1. capytaine/__about__.py +7 -2
  2. capytaine/__init__.py +11 -15
  3. capytaine/bem/engines.py +234 -354
  4. capytaine/bem/problems_and_results.py +30 -21
  5. capytaine/bem/solver.py +205 -81
  6. capytaine/bodies/bodies.py +279 -862
  7. capytaine/bodies/dofs.py +136 -9
  8. capytaine/bodies/hydrostatics.py +540 -0
  9. capytaine/bodies/multibodies.py +216 -0
  10. capytaine/green_functions/{libs/Delhommeau_float32.cp312-win_amd64.dll.a → Delhommeau_float32.cp312-win_amd64.dll.a} +0 -0
  11. capytaine/green_functions/Delhommeau_float32.cp312-win_amd64.pyd +0 -0
  12. capytaine/green_functions/{libs/Delhommeau_float64.cp312-win_amd64.dll.a → Delhommeau_float64.cp312-win_amd64.dll.a} +0 -0
  13. capytaine/green_functions/Delhommeau_float64.cp312-win_amd64.pyd +0 -0
  14. capytaine/green_functions/abstract_green_function.py +2 -2
  15. capytaine/green_functions/delhommeau.py +50 -31
  16. capytaine/green_functions/hams.py +19 -13
  17. capytaine/io/legacy.py +3 -103
  18. capytaine/io/xarray.py +15 -10
  19. capytaine/meshes/__init__.py +2 -6
  20. capytaine/meshes/abstract_meshes.py +375 -0
  21. capytaine/meshes/clean.py +302 -0
  22. capytaine/meshes/clip.py +347 -0
  23. capytaine/meshes/export.py +89 -0
  24. capytaine/meshes/geometry.py +244 -394
  25. capytaine/meshes/io.py +433 -0
  26. capytaine/meshes/meshes.py +621 -676
  27. capytaine/meshes/predefined/cylinders.py +22 -56
  28. capytaine/meshes/predefined/rectangles.py +26 -85
  29. capytaine/meshes/predefined/spheres.py +4 -11
  30. capytaine/meshes/quality.py +118 -407
  31. capytaine/meshes/surface_integrals.py +48 -29
  32. capytaine/meshes/symmetric_meshes.py +641 -0
  33. capytaine/meshes/visualization.py +353 -0
  34. capytaine/post_pro/free_surfaces.py +1 -4
  35. capytaine/post_pro/kochin.py +10 -10
  36. capytaine/tools/block_circulant_matrices.py +275 -0
  37. capytaine/tools/lists_of_points.py +2 -2
  38. capytaine/tools/memory_monitor.py +45 -0
  39. capytaine/tools/symbolic_multiplication.py +31 -5
  40. capytaine/tools/timer.py +68 -42
  41. capytaine-3.0.0a1.dist-info/DELVEWHEEL +2 -0
  42. {capytaine-2.3.dist-info → capytaine-3.0.0a1.dist-info}/METADATA +8 -14
  43. capytaine-3.0.0a1.dist-info/RECORD +70 -0
  44. capytaine/bodies/predefined/__init__.py +0 -6
  45. capytaine/bodies/predefined/cylinders.py +0 -151
  46. capytaine/bodies/predefined/rectangles.py +0 -111
  47. capytaine/bodies/predefined/spheres.py +0 -70
  48. capytaine/green_functions/FinGreen3D/.gitignore +0 -1
  49. capytaine/green_functions/FinGreen3D/FinGreen3D.f90 +0 -3589
  50. capytaine/green_functions/FinGreen3D/LICENSE +0 -165
  51. capytaine/green_functions/FinGreen3D/Makefile +0 -16
  52. capytaine/green_functions/FinGreen3D/README.md +0 -24
  53. capytaine/green_functions/FinGreen3D/test_program.f90 +0 -39
  54. capytaine/green_functions/LiangWuNoblesse/.gitignore +0 -1
  55. capytaine/green_functions/LiangWuNoblesse/LICENSE +0 -504
  56. capytaine/green_functions/LiangWuNoblesse/LiangWuNoblesseWaveTerm.f90 +0 -751
  57. capytaine/green_functions/LiangWuNoblesse/Makefile +0 -18
  58. capytaine/green_functions/LiangWuNoblesse/README.md +0 -2
  59. capytaine/green_functions/LiangWuNoblesse/test_program.f90 +0 -28
  60. capytaine/green_functions/libs/Delhommeau_float32.cp312-win_amd64.pyd +0 -0
  61. capytaine/green_functions/libs/Delhommeau_float64.cp312-win_amd64.pyd +0 -0
  62. capytaine/green_functions/libs/__init__.py +0 -0
  63. capytaine/io/mesh_loaders.py +0 -1086
  64. capytaine/io/mesh_writers.py +0 -692
  65. capytaine/io/meshio.py +0 -38
  66. capytaine/matrices/__init__.py +0 -16
  67. capytaine/matrices/block.py +0 -592
  68. capytaine/matrices/block_toeplitz.py +0 -325
  69. capytaine/matrices/builders.py +0 -89
  70. capytaine/matrices/linear_solvers.py +0 -232
  71. capytaine/matrices/low_rank.py +0 -395
  72. capytaine/meshes/clipper.py +0 -465
  73. capytaine/meshes/collections.py +0 -334
  74. capytaine/meshes/mesh_like_protocol.py +0 -37
  75. capytaine/meshes/properties.py +0 -276
  76. capytaine/meshes/quadratures.py +0 -80
  77. capytaine/meshes/symmetric.py +0 -392
  78. capytaine/tools/lru_cache.py +0 -49
  79. capytaine/ui/vtk/__init__.py +0 -3
  80. capytaine/ui/vtk/animation.py +0 -329
  81. capytaine/ui/vtk/body_viewer.py +0 -28
  82. capytaine/ui/vtk/helpers.py +0 -82
  83. capytaine/ui/vtk/mesh_viewer.py +0 -461
  84. capytaine-2.3.dist-info/DELVEWHEEL +0 -2
  85. capytaine-2.3.dist-info/RECORD +0 -97
  86. {capytaine-2.3.dist-info → capytaine-3.0.0a1.dist-info}/LICENSE +0 -0
  87. {capytaine-2.3.dist-info → capytaine-3.0.0a1.dist-info}/WHEEL +0 -0
  88. {capytaine-2.3.dist-info → capytaine-3.0.0a1.dist-info}/entry_points.txt +0 -0
capytaine/io/xarray.py CHANGED
@@ -11,6 +11,7 @@ from datetime import datetime
11
11
  from itertools import product
12
12
  from collections import Counter
13
13
  from typing import Sequence, List, Union
14
+ from pathlib import Path
14
15
 
15
16
  import numpy as np
16
17
  import pandas as pd
@@ -18,6 +19,7 @@ import xarray as xr
18
19
 
19
20
  from capytaine import __version__
20
21
  from capytaine.bodies.bodies import FloatingBody
22
+ from capytaine.bodies.multibodies import Multibody
21
23
  from capytaine.bem.problems_and_results import (
22
24
  LinearPotentialFlowProblem, DiffractionProblem, RadiationProblem,
23
25
  LinearPotentialFlowResult, _default_parameters)
@@ -43,7 +45,7 @@ def _unsqueeze_dimensions(data_array, dimensions=None):
43
45
 
44
46
 
45
47
  def problems_from_dataset(dataset: xr.Dataset,
46
- bodies: Union[FloatingBody, Sequence[FloatingBody]],
48
+ bodies: Union[FloatingBody, Sequence[FloatingBody], Multibody, Sequence[Multibody]],
47
49
  ) -> List[LinearPotentialFlowProblem]:
48
50
  """Generate a list of problems from a test matrix.
49
51
 
@@ -64,7 +66,7 @@ def problems_from_dataset(dataset: xr.Dataset,
64
66
  ValueError
65
67
  if required fields are missing in the dataset
66
68
  """
67
- if isinstance(bodies, FloatingBody):
69
+ if isinstance(bodies, (FloatingBody, Multibody)):
68
70
  bodies = [bodies]
69
71
 
70
72
  # Should be done before looking for `frequency_keys`, otherwise
@@ -257,7 +259,7 @@ def hydrostatics_dataset(bodies: Sequence[FloatingBody]) -> xr.Dataset:
257
259
  if len(bodies_properties) > 0:
258
260
  bodies_properties = xr.concat(bodies_properties.values(), pd.Index(bodies_properties.keys(), name='body_name'))
259
261
  bodies_properties = _squeeze_dimensions(bodies_properties, dimensions=['body_name'])
260
- dataset = xr.merge([dataset, {body_property: bodies_properties}])
262
+ dataset = xr.merge([dataset, {body_property: bodies_properties}], compat="no_conflicts", join="outer")
261
263
  return dataset
262
264
 
263
265
 
@@ -279,22 +281,24 @@ def kochin_data_array(results: Sequence[LinearPotentialFlowResult],
279
281
  compute_kochin(result, theta_range, **kwargs))
280
282
  ])
281
283
 
284
+ main_freq_type = Counter((res.provided_freq_type for res in results)).most_common(1)[0][0]
285
+
282
286
  kochin_data = xr.Dataset()
283
287
 
284
288
  if "RadiationResult" in set(records['kind']):
285
289
  radiation = _dataset_from_dataframe(
286
290
  records[records['kind'] == "RadiationResult"],
287
291
  variables=['kochin'],
288
- dimensions=['omega', 'radiating_dof', 'theta'],
292
+ dimensions=[main_freq_type, 'radiating_dof', 'theta'],
289
293
  optional_dims=['g', 'rho', 'body_name', 'water_depth', 'forward_speed', 'wave_direction']
290
294
  )
291
- kochin_data['kochin'] = radiation['kochin']
295
+ kochin_data['kochin_radiation'] = radiation['kochin']
292
296
 
293
297
  if "DiffractionResult" in set(records['kind']):
294
298
  diffraction = _dataset_from_dataframe(
295
299
  records[records['kind'] == "DiffractionResult"],
296
300
  ['kochin'],
297
- dimensions=['omega', 'wave_direction', 'theta'],
301
+ dimensions=[main_freq_type, 'wave_direction', 'theta'],
298
302
  optional_dims=['g', 'rho', 'body_name', 'water_depth', 'forward_speed']
299
303
  )
300
304
  kochin_data['kochin_diffraction'] = diffraction['kochin']
@@ -416,7 +420,7 @@ def assemble_dataset(results,
416
420
  variables=['added_mass', 'radiation_damping'],
417
421
  dimensions=[main_freq_type, 'radiating_dof', 'influenced_dof'],
418
422
  optional_dims=optional_dims + ['wave_direction'])
419
- dataset = xr.merge([dataset, radiation_cases])
423
+ dataset = xr.merge([dataset, radiation_cases], compat="no_conflicts", join="outer")
420
424
 
421
425
  # DIFFRACTION RESULTS
422
426
  if "DiffractionResult" in kinds_of_results:
@@ -425,7 +429,7 @@ def assemble_dataset(results,
425
429
  variables=['diffraction_force', 'Froude_Krylov_force'],
426
430
  dimensions=[main_freq_type, 'wave_direction', 'influenced_dof'],
427
431
  optional_dims=optional_dims)
428
- dataset = xr.merge([dataset, diffraction_cases])
432
+ dataset = xr.merge([dataset, diffraction_cases], compat="no_conflicts", join="outer")
429
433
  dataset['excitation_force'] = dataset['Froude_Krylov_force'] + dataset['diffraction_force']
430
434
 
431
435
  # OTHER FREQUENCIES TYPES
@@ -519,7 +523,7 @@ def assemble_dataset(results,
519
523
  LOG.warning('Bemio data import being used, hydrostatics=True is ignored.')
520
524
  else:
521
525
  bodies = list({result.body for result in results})
522
- dataset = xr.merge([dataset, hydrostatics_dataset(bodies)])
526
+ dataset = xr.merge([dataset, hydrostatics_dataset(bodies)], compat="no_conflicts", join="outer")
523
527
 
524
528
  for var in set(dataset) | set(dataset.coords):
525
529
  if var in VARIABLES_ATTRIBUTES:
@@ -532,7 +536,7 @@ def assemble_dataset(results,
532
536
 
533
537
  def assemble_matrices(results):
534
538
  """Simplified version of assemble_dataset, returning only bare matrices.
535
- Meant mainly for teaching without introducing Xarray to beginers.
539
+ Meant mainly for teaching without introducing Xarray to beginners.
536
540
 
537
541
  Parameters
538
542
  ----------
@@ -662,6 +666,7 @@ def export_dataset(filename, dataset, format=None, **kwargs):
662
666
  (format is not None and format.lower() == "nemoh")
663
667
  ):
664
668
  from capytaine.io.legacy import write_dataset_as_tecplot_files
669
+ Path(filename).mkdir(exist_ok=True)
665
670
  write_dataset_as_tecplot_files(filename, dataset, **kwargs)
666
671
  else:
667
672
  raise ValueError("`export_dataset` could not infer export format based on filename or `format` argument.\n"
@@ -1,6 +1,2 @@
1
- # Copyright (C) 2017-2019 Matthieu Ancellin, based on the work of François Rongère
2
- # See LICENSE file at <https://github.com/mancellin/capytaine>
3
-
4
- from capytaine.meshes.meshes import Mesh
5
- from capytaine.meshes.collections import CollectionOfMeshes
6
- from capytaine.meshes.symmetric import ReflectionSymmetricMesh, TranslationalSymmetricMesh, AxialSymmetricMesh
1
+ from .meshes import Mesh
2
+ from .symmetric_meshes import ReflectionSymmetricMesh, RotationSymmetricMesh
@@ -0,0 +1,375 @@
1
+ # Copyright 2025 Mews Labs
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from __future__ import annotations
16
+
17
+ import logging
18
+ from abc import ABC, abstractmethod
19
+ from functools import cached_property, lru_cache
20
+ from typing import Literal, Tuple
21
+
22
+ import numpy as np
23
+
24
+ from capytaine.meshes.surface_integrals import SurfaceIntegralsMixin
25
+ from capytaine.tools.deprecation_handling import _get_water_depth
26
+ from capytaine.meshes.geometry import connected_components, connected_components_of_waterline
27
+
28
+ LOG = logging.getLogger(__name__)
29
+
30
+ class AbstractMesh(SurfaceIntegralsMixin, ABC):
31
+ @property
32
+ @abstractmethod
33
+ def nb_vertices(self) -> int:
34
+ ...
35
+
36
+ @property
37
+ @abstractmethod
38
+ def nb_faces(self) -> int:
39
+ ...
40
+
41
+ @property
42
+ @abstractmethod
43
+ def faces_normals(self) -> np.ndarray:
44
+ ...
45
+
46
+ @property
47
+ @abstractmethod
48
+ def faces_areas(self) -> np.ndarray:
49
+ ...
50
+
51
+ @property
52
+ @abstractmethod
53
+ def faces_centers(self) -> np.ndarray:
54
+ ...
55
+
56
+ @property
57
+ @abstractmethod
58
+ def faces_radiuses(self) -> np.ndarray:
59
+ ...
60
+
61
+ @property
62
+ @abstractmethod
63
+ def faces(self) -> np.ndarray:
64
+ ...
65
+
66
+ @property
67
+ @abstractmethod
68
+ def quadrature_points(self) -> np.ndarray:
69
+ ...
70
+
71
+ @cached_property
72
+ def z_span(self) -> Tuple[float, float]:
73
+ return (self.vertices[:, 2].min(), self.vertices[:, 2].max())
74
+
75
+ @abstractmethod
76
+ def __str__(self) -> str:
77
+ ...
78
+
79
+ @abstractmethod
80
+ def __short_str__(self) -> str:
81
+ ...
82
+
83
+ @abstractmethod
84
+ def with_quadrature(self, quadrature_method):
85
+ ...
86
+
87
+ @abstractmethod
88
+ def extract_faces(self, faces_id, *, name=None) -> AbstractMesh:
89
+ ...
90
+
91
+ @abstractmethod
92
+ def translated(self, shift, *, name=None) -> AbstractMesh:
93
+ ...
94
+
95
+ def translated_x(self, dx: float, *, name=None) -> AbstractMesh:
96
+ """Return a new Mesh translated in the x-direction along `dx`."""
97
+ return self.translated([dx, 0.0, 0.0], name=name)
98
+
99
+ def translated_y(self, dy: float, *, name=None) -> AbstractMesh:
100
+ """Return a new Mesh translated in the y-direction along `dy`."""
101
+ return self.translated([0.0, dy, 0.0], name=name)
102
+
103
+ def translated_z(self, dz: float, *, name=None) -> AbstractMesh:
104
+ """Return a new Mesh translated in the z-direction along `dz`."""
105
+ return self.translated([0.0, 0.0, dz], name=name)
106
+
107
+ @abstractmethod
108
+ def rotated_with_matrix(self, R, *, name=None) -> AbstractMesh:
109
+ ...
110
+
111
+ def rotated_x(self, angle: float, *, name=None) -> AbstractMesh:
112
+ """Return a new Mesh rotated around the x-axis using the provided rotation angle in radians"""
113
+ c, s = np.cos(angle), np.sin(angle)
114
+ R = np.array([[1, 0, 0], [0, c, -s], [0, s, c]])
115
+ return self.rotated_with_matrix(R, name=name)
116
+
117
+ def rotated_y(self, angle: float, *, name=None) -> AbstractMesh:
118
+ """Return a new Mesh rotated around the y-axis using the provided rotation angle in radians"""
119
+ c, s = np.cos(angle), np.sin(angle)
120
+ R = np.array([[c, 0, s], [0, 1, 0], [-s, 0, c]])
121
+ return self.rotated_with_matrix(R, name=name)
122
+
123
+ def rotated_z(self, angle: float, *, name=None) -> AbstractMesh:
124
+ """Return a new Mesh rotated around the z-axis using the provided rotation angle in radians"""
125
+ c, s = np.cos(angle), np.sin(angle)
126
+ R = np.array([[c, -s, 0], [s, c, 0], [0, 0, 1]])
127
+ return self.rotated_with_matrix(R, name=name)
128
+
129
+ def rotated_such_that_vectors_are_aligned(self, a, b, *, eps=1e-8, name=None) -> AbstractMesh:
130
+ a = np.asarray(a, dtype=float)
131
+ b = np.asarray(b, dtype=float)
132
+
133
+ # Normalize input vectors
134
+ a_norm = np.linalg.norm(a)
135
+ b_norm = np.linalg.norm(b)
136
+ if a_norm < eps or b_norm < eps:
137
+ raise ValueError("Input vectors must be non-zero")
138
+
139
+ a_hat = a / a_norm
140
+ b_hat = b / b_norm
141
+
142
+ # Cross and dot products
143
+ v = np.cross(a_hat, b_hat)
144
+ c = np.dot(a_hat, b_hat)
145
+ s = np.linalg.norm(v)
146
+
147
+ # Case 1: vectors are already aligned
148
+ if s < eps and c > 0:
149
+ return self.copy(name=name)
150
+
151
+ # Case 2: vectors are opposite
152
+ if s < eps and c < 0:
153
+ # Find an arbitrary orthogonal vector
154
+ # Prefer axis least aligned with a_hat
155
+ axis = np.array([1.0, 0.0, 0.0])
156
+ if abs(a_hat[0]) > abs(a_hat[1]):
157
+ axis = np.array([0.0, 1.0, 0.0])
158
+ axis = axis - a_hat * np.dot(a_hat, axis)
159
+ axis /= np.linalg.norm(axis)
160
+
161
+ # Rotation by pi around axis
162
+ K = np.array([[0, -axis[2], axis[1]],
163
+ [axis[2], 0, -axis[0]],
164
+ [-axis[1], axis[0], 0]])
165
+ return self.rotated_with_matrix(np.eye(3) + 2 * K @ K, name=name)
166
+
167
+ # General case: Rodrigues' rotation formula
168
+ K = np.array([[0, -v[2], v[1]],
169
+ [v[2], 0, -v[0]],
170
+ [-v[1], v[0], 0]])
171
+
172
+ R = np.eye(3) + K + K @ K * ((1 - c) / (s ** 2))
173
+ return self.rotated_with_matrix(R, name=name)
174
+
175
+ def mirrored(self, plane: Literal['xOz', 'yOz'], *, name=None) -> AbstractMesh:
176
+ ...
177
+
178
+ @abstractmethod
179
+ def join_meshes(*meshes, return_masks=False, name=None) -> AbstractMesh:
180
+ ...
181
+
182
+ def _common_metadata_keys(*meshes):
183
+ metadata_keys = [set(m.faces_metadata.keys()) for m in meshes]
184
+ common_metadata_keys = set.intersection(*metadata_keys)
185
+ lost_metadata_keys = set.union(*metadata_keys) - common_metadata_keys
186
+ if len(lost_metadata_keys) > 0:
187
+ LOG.warning(f'The following metadata have been dropped when joining meshes: {lost_metadata_keys}')
188
+ return common_metadata_keys
189
+
190
+ def __add__(self, other: AbstractMesh) -> AbstractMesh:
191
+ """Combine two meshes using the + operator.
192
+
193
+ Parameters
194
+ ----------
195
+ other : Mesh
196
+ Another mesh to combine with this one.
197
+
198
+ Returns
199
+ -------
200
+ Mesh
201
+ New mesh containing vertices and faces from both meshes.
202
+ """
203
+ if self.name is not None or other.name is not None:
204
+ name = f"{self.name}+{other.name}"
205
+ else:
206
+ name = None
207
+ return self.join_meshes(other, name=name)
208
+
209
+ def lowest_lid_position(self, omega_max, *, g=9.81):
210
+ z_lid = 0.0
211
+ for comp in connected_components(self):
212
+ for ccomp in connected_components_of_waterline(comp):
213
+ x_span = ccomp.vertices[:, 0].max() - ccomp.vertices[:, 0].min()
214
+ y_span = ccomp.vertices[:, 1].max() - ccomp.vertices[:, 1].min()
215
+ p = np.hypot(1/x_span, 1/y_span)
216
+ z_lid_comp = -np.arctanh(np.pi*g*p/omega_max**2) / (np.pi * p)
217
+ z_lid = min(z_lid, z_lid_comp)
218
+ return 0.9*z_lid # Add a small safety margin
219
+
220
+ @abstractmethod
221
+ def generate_lid(self, z=0.0, faces_max_radius=None, name=None):
222
+ ...
223
+
224
+ @abstractmethod
225
+ def extract_lid(self, z=0.0):
226
+ ...
227
+
228
+ @abstractmethod
229
+ def with_normal_vector_going_down(self, **kwargs) -> AbstractMesh:
230
+ ...
231
+
232
+ @abstractmethod
233
+ def copy(self) -> AbstractMesh:
234
+ ...
235
+
236
+ def with_metadata(self, **new_metadata) -> AbstractMesh:
237
+ faces_metadata = self.faces_metadata.copy()
238
+ for k, v in new_metadata.items():
239
+ faces_metadata[k] = v
240
+ return self.copy(faces_metadata=faces_metadata)
241
+
242
+ def pop_metadata(self, metadata_name) -> Tuple[AbstractMesh, np.ndarray]:
243
+ faces_metadata = self.faces_metadata.copy()
244
+ data = faces_metadata.pop(metadata_name)
245
+ return self.copy(faces_metadata=faces_metadata), data
246
+
247
+ def without_metadata(self, *metadata_names) -> AbstractMesh:
248
+ faces_metadata = self.faces_metadata.copy()
249
+ for k in metadata_names:
250
+ del faces_metadata[k]
251
+ return self.copy(faces_metadata=faces_metadata)
252
+
253
+ def without_any_metadata(self) -> AbstractMesh:
254
+ return self.copy(faces_metadata={})
255
+
256
+ @abstractmethod
257
+ def merged(self) -> AbstractMesh:
258
+ ...
259
+
260
+ @abstractmethod
261
+ def clipped(self, *, origin, normal, name=None) -> AbstractMesh:
262
+ ...
263
+
264
+ def extract_wedge(self, n: int, axis: str = "z") -> AbstractMesh:
265
+ """Extract a wedge (angular sector) from the mesh for rotational symmetry.
266
+
267
+ Extracts a 1/n sector of the mesh by clipping at angular boundaries.
268
+ This creates proper faces at the wedge boundaries for clean reconstruction.
269
+
270
+ Parameters
271
+ ----------
272
+ n : int
273
+ The rotation order. The wedge will span 360/n degrees.
274
+ axis : str, optional
275
+ Only "z" is currently supported.
276
+
277
+ Returns
278
+ -------
279
+ Mesh
280
+ A new mesh containing the wedge sector with proper boundary faces.
281
+
282
+ Examples
283
+ --------
284
+ Extract 1/3 of a sphere (120-degree wedge):
285
+
286
+ >>> sphere = mesh_sphere(radius=1.0, resolution=(12, 12))
287
+ >>> wedge = sphere.extract_wedge(n=3)
288
+ >>> wedge.nb_faces # Approximately 1/3 of sphere.nb_faces
289
+ """
290
+ if axis != "z":
291
+ raise NotImplementedError(
292
+ f"Only 'z' axis is currently supported, got '{axis}'"
293
+ )
294
+ if n < 2:
295
+ raise ValueError(f"Rotation order must be >= 2, got {n}")
296
+
297
+ # Wedge angle in radians
298
+ wedge_angle = 2 * np.pi / n
299
+
300
+ # First clip: keep the half with y >= 0 (theta in [0, pi])
301
+ # This corresponds to the plane y=0, keeping positive y side
302
+ origin = np.array([0.0, 0.0, 0.0])
303
+ normal_1 = np.array([0.0, -1.0, 0.0]) # Keep y >= 0
304
+ wedge = self.clipped(origin=origin, normal=normal_1)
305
+
306
+ # Second clip: create the wedge boundary at angle = wedge_angle
307
+ # The plane passes through the z-axis and has a normal perpendicular to the boundary
308
+ # For a wedge from theta=0 to theta=wedge_angle, we need to keep theta <= wedge_angle
309
+ # Normal vector points outward from the wedge (to reject the side we don't want)
310
+ # At angle theta, the outward normal is [-sin(theta), cos(theta), 0]
311
+ normal_2 = np.array([-np.sin(wedge_angle), np.cos(wedge_angle), 0.0])
312
+ wedge = wedge.clipped(origin=origin, normal=normal_2, name=f"{self.name}_wedge_n{n}")
313
+
314
+ return wedge
315
+
316
+ @lru_cache
317
+ def immersed_part(self, free_surface=0.0, *, sea_bottom=None, water_depth=None) -> AbstractMesh:
318
+ """
319
+ Clip the mesh to keep only the part below the free surface.
320
+
321
+ Parameters
322
+ ----------
323
+ free_surface: float
324
+ The :math:`z` coordinate of the free surface (default: 0.0)
325
+ water_depth: Optional[float]
326
+ The water depth, as a positive value (default: infinity)
327
+
328
+ Returns
329
+ -------
330
+ Mesh
331
+ A new Mesh instance that has been clipped.
332
+ """
333
+ water_depth = _get_water_depth(free_surface, water_depth, sea_bottom,
334
+ default_water_depth=np.inf)
335
+ if (free_surface - water_depth <= self.z_span[0]
336
+ and self.z_span[1] <= free_surface): # Already clipped
337
+ return self # Shortcut for performance
338
+ clipped = self.clipped(origin=(0, 0, 0), normal=(0, 0, 1))
339
+ if water_depth < np.inf:
340
+ clipped = clipped.clipped(origin=(0, 0, free_surface-water_depth), normal=(0, 0, -1))
341
+ return clipped
342
+
343
+ @abstractmethod
344
+ def show(self, *, backend=None, **kwargs):
345
+ ...
346
+
347
+ def show_pyvista(self, **kwargs):
348
+ """
349
+ Equivalent to show(backend="pyvista").
350
+ See also :func:`~capytaine.meshes.visualization.show_pyvista`
351
+ """
352
+ return self.show(backend="pyvista", **kwargs)
353
+
354
+ def show_matplotlib(self, **kwargs):
355
+ """
356
+ Equivalent to show(backend="matplotlib").
357
+ See also :func:`~capytaine.meshes.visualization.show_matplotlib`
358
+ """
359
+ return self.show(backend="matplotlib", **kwargs)
360
+
361
+ @abstractmethod
362
+ def export(self, format, **kwargs):
363
+ ...
364
+
365
+ def export_to_pyvista(self, **kwargs):
366
+ return self.export(format="pyvista", **kwargs)
367
+
368
+ def export_to_xarray(self, **kwargs):
369
+ return self.export(format="xarray", **kwargs)
370
+
371
+ def export_to_meshio(self, **kwargs):
372
+ return self.export(format="meshio", **kwargs)
373
+
374
+ def export_to_trimesh(self, **kwargs):
375
+ return self.export(format="trimesh", **kwargs)