capytaine 2.2.1__cp310-cp310-macosx_14_0_arm64.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 (76) hide show
  1. capytaine/.dylibs/libgcc_s.1.1.dylib +0 -0
  2. capytaine/.dylibs/libgfortran.5.dylib +0 -0
  3. capytaine/.dylibs/libquadmath.0.dylib +0 -0
  4. capytaine/__about__.py +16 -0
  5. capytaine/__init__.py +35 -0
  6. capytaine/bem/__init__.py +0 -0
  7. capytaine/bem/airy_waves.py +106 -0
  8. capytaine/bem/engines.py +441 -0
  9. capytaine/bem/problems_and_results.py +548 -0
  10. capytaine/bem/solver.py +506 -0
  11. capytaine/bodies/__init__.py +4 -0
  12. capytaine/bodies/bodies.py +1193 -0
  13. capytaine/bodies/dofs.py +19 -0
  14. capytaine/bodies/predefined/__init__.py +6 -0
  15. capytaine/bodies/predefined/cylinders.py +151 -0
  16. capytaine/bodies/predefined/rectangles.py +109 -0
  17. capytaine/bodies/predefined/spheres.py +70 -0
  18. capytaine/green_functions/__init__.py +2 -0
  19. capytaine/green_functions/abstract_green_function.py +12 -0
  20. capytaine/green_functions/delhommeau.py +432 -0
  21. capytaine/green_functions/libs/Delhommeau_float32.cpython-310-darwin.so +0 -0
  22. capytaine/green_functions/libs/Delhommeau_float64.cpython-310-darwin.so +0 -0
  23. capytaine/green_functions/libs/__init__.py +0 -0
  24. capytaine/io/__init__.py +0 -0
  25. capytaine/io/bemio.py +141 -0
  26. capytaine/io/legacy.py +328 -0
  27. capytaine/io/mesh_loaders.py +1086 -0
  28. capytaine/io/mesh_writers.py +692 -0
  29. capytaine/io/meshio.py +38 -0
  30. capytaine/io/xarray.py +524 -0
  31. capytaine/matrices/__init__.py +16 -0
  32. capytaine/matrices/block.py +592 -0
  33. capytaine/matrices/block_toeplitz.py +325 -0
  34. capytaine/matrices/builders.py +89 -0
  35. capytaine/matrices/linear_solvers.py +232 -0
  36. capytaine/matrices/low_rank.py +395 -0
  37. capytaine/meshes/__init__.py +6 -0
  38. capytaine/meshes/clipper.py +464 -0
  39. capytaine/meshes/collections.py +324 -0
  40. capytaine/meshes/geometry.py +409 -0
  41. capytaine/meshes/meshes.py +870 -0
  42. capytaine/meshes/predefined/__init__.py +6 -0
  43. capytaine/meshes/predefined/cylinders.py +314 -0
  44. capytaine/meshes/predefined/rectangles.py +261 -0
  45. capytaine/meshes/predefined/spheres.py +62 -0
  46. capytaine/meshes/properties.py +276 -0
  47. capytaine/meshes/quadratures.py +80 -0
  48. capytaine/meshes/quality.py +448 -0
  49. capytaine/meshes/surface_integrals.py +63 -0
  50. capytaine/meshes/symmetric.py +383 -0
  51. capytaine/post_pro/__init__.py +6 -0
  52. capytaine/post_pro/free_surfaces.py +88 -0
  53. capytaine/post_pro/impedance.py +92 -0
  54. capytaine/post_pro/kochin.py +54 -0
  55. capytaine/post_pro/rao.py +60 -0
  56. capytaine/tools/__init__.py +0 -0
  57. capytaine/tools/cache_on_disk.py +26 -0
  58. capytaine/tools/deprecation_handling.py +18 -0
  59. capytaine/tools/lists_of_points.py +52 -0
  60. capytaine/tools/lru_cache.py +49 -0
  61. capytaine/tools/optional_imports.py +27 -0
  62. capytaine/tools/prony_decomposition.py +94 -0
  63. capytaine/tools/symbolic_multiplication.py +123 -0
  64. capytaine/ui/__init__.py +0 -0
  65. capytaine/ui/cli.py +28 -0
  66. capytaine/ui/rich.py +5 -0
  67. capytaine/ui/vtk/__init__.py +3 -0
  68. capytaine/ui/vtk/animation.py +329 -0
  69. capytaine/ui/vtk/body_viewer.py +28 -0
  70. capytaine/ui/vtk/helpers.py +82 -0
  71. capytaine/ui/vtk/mesh_viewer.py +461 -0
  72. capytaine-2.2.1.dist-info/LICENSE +674 -0
  73. capytaine-2.2.1.dist-info/METADATA +754 -0
  74. capytaine-2.2.1.dist-info/RECORD +76 -0
  75. capytaine-2.2.1.dist-info/WHEEL +4 -0
  76. capytaine-2.2.1.dist-info/entry_points.txt +3 -0
@@ -0,0 +1,1193 @@
1
+ """Floating bodies to be used in radiation-diffraction problems."""
2
+ # Copyright (C) 2017-2024 Matthieu Ancellin
3
+ # See LICENSE file at <https://github.com/capytaine/capytaine>
4
+
5
+ import logging
6
+ import copy
7
+ from itertools import chain, accumulate, zip_longest
8
+ from functools import cached_property, lru_cache
9
+
10
+ import numpy as np
11
+ import xarray as xr
12
+
13
+ from capytaine.meshes.collections import CollectionOfMeshes
14
+ from capytaine.meshes.geometry import Abstract3DObject, ClippableMixin, Plane, inplace_transformation
15
+ from capytaine.meshes.properties import connected_components, connected_components_of_waterline
16
+ from capytaine.meshes.meshes import Mesh
17
+ from capytaine.meshes.symmetric import build_regular_array_of_meshes
18
+ from capytaine.bodies.dofs import RigidBodyDofsPlaceholder
19
+
20
+ from capytaine.tools.optional_imports import silently_import_optional_dependency
21
+ meshio = silently_import_optional_dependency("meshio")
22
+
23
+ LOG = logging.getLogger(__name__)
24
+
25
+ TRANSLATION_DOFS_DIRECTIONS = {"surge": (1, 0, 0), "sway": (0, 1, 0), "heave": (0, 0, 1)}
26
+ ROTATION_DOFS_AXIS = {"roll": (1, 0, 0), "pitch": (0, 1, 0), "yaw": (0, 0, 1)}
27
+
28
+
29
+ class FloatingBody(ClippableMixin, Abstract3DObject):
30
+ """A floating body described as a mesh and some degrees of freedom.
31
+
32
+ The mesh structure is stored as a Mesh from capytaine.mesh.mesh or a
33
+ CollectionOfMeshes from capytaine.mesh.meshes_collection.
34
+
35
+ The degrees of freedom (dofs) are stored as a dict associating a name to
36
+ a complex-valued array of shape (nb_faces, 3). To each face of the body
37
+ (as indexed in the mesh) corresponds a complex-valued 3d vector, which
38
+ defines the displacement of the center of the face in frequency domain.
39
+
40
+ Parameters
41
+ ----------
42
+ mesh : Mesh or CollectionOfMeshes, optional
43
+ the mesh describing the geometry of the hull of the floating body.
44
+ If none is given, a empty one is created.
45
+ lid_mesh : Mesh or CollectionOfMeshes or None, optional
46
+ a mesh of an internal lid for irregular frequencies removal.
47
+ Unlike the mesh of the hull, no dof is defined on the lid_mesh.
48
+ If none is given, none is used when solving the Boundary Integral Equation.
49
+ dofs : dict, optional
50
+ the degrees of freedom of the body.
51
+ If none is given, a empty dictionary is initialized.
52
+ mass : float or None, optional
53
+ the mass of the body in kilograms.
54
+ Required only for some hydrostatics computation.
55
+ If None, the mass is implicitly assumed to be the mass of displaced water.
56
+ center_of_mass: 3-element array, optional
57
+ the position of the center of mass.
58
+ Required only for some hydrostatics computation.
59
+ name : str, optional
60
+ a name for the body.
61
+ If none is given, the one of the mesh is used.
62
+ """
63
+
64
+ def __init__(self, mesh=None, dofs=None, mass=None, center_of_mass=None, name=None, *, lid_mesh=None):
65
+ if mesh is None:
66
+ self.mesh = Mesh(name="dummy_mesh")
67
+
68
+ elif meshio is not None and isinstance(mesh, meshio._mesh.Mesh):
69
+ from capytaine.io.meshio import load_from_meshio
70
+ self.mesh = load_from_meshio(mesh)
71
+
72
+ elif isinstance(mesh, Mesh) or isinstance(mesh, CollectionOfMeshes):
73
+ self.mesh = mesh
74
+
75
+ else:
76
+ raise TypeError("Unrecognized `mesh` object passed to the FloatingBody constructor.")
77
+
78
+ if lid_mesh is not None:
79
+ if lid_mesh.nb_faces == 0:
80
+ LOG.warning("Lid mesh %s provided for body initialization is empty. The lid mesh is ignored.", lid_mesh)
81
+ self.lid_mesh = None
82
+ else:
83
+ self.lid_mesh = lid_mesh.with_normal_vector_going_down(inplace=False)
84
+ else:
85
+ self.lid_mesh = None
86
+
87
+ if name is None and mesh is None:
88
+ self.name = "dummy_body"
89
+ elif name is None:
90
+ self.name = self.mesh.name
91
+ else:
92
+ self.name = name
93
+
94
+ self.mass = mass
95
+ if center_of_mass is not None:
96
+ self.center_of_mass = np.asarray(center_of_mass, dtype=float)
97
+ else:
98
+ self.center_of_mass = None
99
+
100
+ if self.mesh.nb_vertices > 0 and self.mesh.nb_faces > 0:
101
+ self.mesh.heal_mesh()
102
+
103
+ if dofs is None:
104
+ self.dofs = {}
105
+ elif isinstance(dofs, RigidBodyDofsPlaceholder):
106
+ if dofs.rotation_center is not None:
107
+ self.rotation_center = np.asarray(dofs.rotation_center, dtype=float)
108
+ self.dofs = {}
109
+ self.add_all_rigid_body_dofs()
110
+ else:
111
+ self.dofs = dofs
112
+
113
+ LOG.info(f"New floating body: {self.__str__()}.")
114
+
115
+ @staticmethod
116
+ def from_meshio(mesh, name=None) -> 'FloatingBody':
117
+ """Create a FloatingBody from a meshio mesh object.
118
+ Kinda deprecated, use cpt.load_mesh instead."""
119
+ from capytaine.io.meshio import load_from_meshio
120
+ return FloatingBody(mesh=load_from_meshio(mesh, name), name=name)
121
+
122
+ @staticmethod
123
+ def from_file(filename: str, file_format=None, name=None) -> 'FloatingBody':
124
+ """Create a FloatingBody from a mesh file using meshmagick.
125
+ Kinda deprecated, use cpt.load_mesh instead."""
126
+ from capytaine.io.mesh_loaders import load_mesh
127
+ if name is None: name = filename
128
+ mesh = load_mesh(filename, file_format, name=f"{name}_mesh")
129
+ return FloatingBody(mesh, name=name)
130
+
131
+ def __lt__(self, other: 'FloatingBody') -> bool:
132
+ """Arbitrary order. The point is to sort together the problems involving the same body."""
133
+ return self.name < other.name
134
+
135
+ @cached_property
136
+ def mesh_including_lid(self):
137
+ if self.lid_mesh is not None:
138
+ return CollectionOfMeshes([self.mesh, self.lid_mesh])
139
+ else:
140
+ return self.mesh
141
+
142
+ ##########
143
+ # Dofs #
144
+ ##########
145
+
146
+ @property
147
+ def nb_dofs(self) -> int:
148
+ """Number of degrees of freedom."""
149
+ return len(self.dofs)
150
+
151
+ def add_translation_dof(self, direction=None, name=None, amplitude=1.0) -> None:
152
+ """Add a new translation dof (in place).
153
+ If no direction is given, the code tries to infer it from the name.
154
+
155
+ Parameters
156
+ ----------
157
+ direction : array of shape (3,), optional
158
+ the direction of the translation
159
+ name : str, optional
160
+ a name for the degree of freedom
161
+ amplitude : float, optional
162
+ amplitude of the dof (default: 1.0 m/s)
163
+ """
164
+ if direction is None:
165
+ if name is not None and name.lower() in TRANSLATION_DOFS_DIRECTIONS:
166
+ direction = TRANSLATION_DOFS_DIRECTIONS[name.lower()]
167
+ else:
168
+ raise ValueError("A direction needs to be specified for the dof.")
169
+
170
+ if name is None:
171
+ name = f"dof_{self.nb_dofs}_translation"
172
+
173
+ direction = np.asarray(direction)
174
+ assert direction.shape == (3,)
175
+
176
+ motion = np.empty((self.mesh.nb_faces, 3))
177
+ motion[:, :] = direction
178
+ self.dofs[name] = amplitude * motion
179
+
180
+ def add_rotation_dof(self, axis=None, name=None, amplitude=1.0) -> None:
181
+ """Add a new rotation dof (in place).
182
+ If no axis is given, the code tries to infer it from the name.
183
+
184
+ Parameters
185
+ ----------
186
+ axis: Axis, optional
187
+ the axis of the rotation
188
+ name : str, optional
189
+ a name for the degree of freedom
190
+ amplitude : float, optional
191
+ amplitude of the dof (default: 1.0)
192
+ """
193
+ if axis is None:
194
+ if name is not None and name.lower() in ROTATION_DOFS_AXIS:
195
+ axis_direction = ROTATION_DOFS_AXIS[name.lower()]
196
+ for point_attr in ('rotation_center', 'center_of_mass', 'geometric_center'):
197
+ if hasattr(self, point_attr) and getattr(self, point_attr) is not None:
198
+ axis_point = getattr(self, point_attr)
199
+ LOG.info(f"The rotation dof {name} has been initialized around the point: "
200
+ f"{self.__short_str__()}.{point_attr} = {getattr(self, point_attr)}")
201
+ break
202
+ else:
203
+ axis_point = np.array([0, 0, 0])
204
+ LOG.warning(f"The rotation dof {name} has been initialized "
205
+ f"around the origin of the domain (0, 0, 0).")
206
+ else:
207
+ raise ValueError("A direction needs to be specified for the dof.")
208
+ else:
209
+ axis_point = axis.point
210
+ axis_direction = axis.vector
211
+
212
+ if name is None:
213
+ name = f"dof_{self.nb_dofs}_rotation"
214
+
215
+ if self.mesh.nb_faces == 0:
216
+ self.dofs[name] = np.empty((self.mesh.nb_faces, 3))
217
+ else:
218
+ motion = np.cross(axis_point - self.mesh.faces_centers, axis_direction)
219
+ self.dofs[name] = amplitude * motion
220
+
221
+ def add_all_rigid_body_dofs(self) -> None:
222
+ """Add the six degrees of freedom of rigid bodies (in place)."""
223
+ self.add_translation_dof(name="Surge")
224
+ self.add_translation_dof(name="Sway")
225
+ self.add_translation_dof(name="Heave")
226
+ self.add_rotation_dof(name="Roll")
227
+ self.add_rotation_dof(name="Pitch")
228
+ self.add_rotation_dof(name="Yaw")
229
+
230
+ def integrate_pressure(self, pressure):
231
+ forces = {}
232
+ for dof_name in self.dofs:
233
+ # Scalar product on each face:
234
+ normal_dof_amplitude_on_face = - np.sum(self.dofs[dof_name] * self.mesh.faces_normals, axis=1)
235
+ # The minus sign in the above line is because we want the force of the fluid on the body and not the force of the body on the fluid.
236
+ # Sum over all faces:
237
+ forces[dof_name] = np.sum(pressure * normal_dof_amplitude_on_face * self.mesh.faces_areas)
238
+ return forces
239
+
240
+ @inplace_transformation
241
+ def keep_only_dofs(self, dofs):
242
+ for dof in list(self.dofs.keys()):
243
+ if dof not in dofs:
244
+ del self.dofs[dof]
245
+
246
+ if hasattr(self, 'inertia_matrix'):
247
+ self.inertia_matrix = self.inertia_matrix.sel(radiating_dof=dofs, influenced_dof=dofs)
248
+ if hasattr(self, 'hydrostatic_stiffness'):
249
+ self.hydrostatic_stiffness = self.hydrostatic_stiffness.sel(radiating_dof=dofs, influenced_dof=dofs)
250
+
251
+ return self
252
+
253
+ def add_dofs_labels_to_vector(self, vector):
254
+ """Helper function turning a bare vector into a vector labelled by the name of the dofs of the body,
255
+ to be used for instance for the computation of RAO."""
256
+ return xr.DataArray(data=np.asarray(vector), dims=['influenced_dof'],
257
+ coords={'influenced_dof': list(self.dofs)},
258
+ )
259
+
260
+ def add_dofs_labels_to_matrix(self, matrix):
261
+ """Helper function turning a bare matrix into a matrix labelled by the name of the dofs of the body,
262
+ to be used for instance for the computation of RAO."""
263
+ return xr.DataArray(data=np.asarray(matrix), dims=['influenced_dof', 'radiating_dof'],
264
+ coords={'influenced_dof': list(self.dofs), 'radiating_dof': list(self.dofs)},
265
+ )
266
+
267
+ ###################
268
+ # Hydrostatics #
269
+ ###################
270
+
271
+ def surface_integral(self, data, **kwargs):
272
+ """Returns integral of given data along wet surface area."""
273
+ return self.mesh.surface_integral(data, **kwargs)
274
+
275
+ def waterplane_integral(self, data, **kwargs):
276
+ """Returns integral of given data along water plane area."""
277
+ return self.mesh.waterplane_integral(data, **kwargs)
278
+
279
+ @property
280
+ def wet_surface_area(self):
281
+ """Returns wet surface area."""
282
+ return self.mesh.wet_surface_area
283
+
284
+ @property
285
+ def volumes(self):
286
+ """Returns volumes using x, y, z components of the FloatingBody."""
287
+ return self.mesh.volumes
288
+
289
+ @property
290
+ def volume(self):
291
+ """Returns volume of the FloatingBody."""
292
+ return self.mesh.volume
293
+
294
+ def disp_mass(self, *, rho=1000.0):
295
+ return self.mesh.disp_mass(rho=rho)
296
+
297
+ @property
298
+ def center_of_buoyancy(self):
299
+ """Returns center of buoyancy of the FloatingBody."""
300
+ return self.mesh.center_of_buoyancy
301
+
302
+ @property
303
+ def waterplane_area(self):
304
+ """Returns water plane area of the FloatingBody."""
305
+ return self.mesh.waterplane_area
306
+
307
+ @property
308
+ def waterplane_center(self):
309
+ """Returns water plane center of the FloatingBody.
310
+
311
+ Note: Returns None if the FloatingBody is full submerged.
312
+ """
313
+ return self.mesh.waterplane_center
314
+
315
+ @property
316
+ def transversal_metacentric_radius(self):
317
+ """Returns transversal metacentric radius of the mesh."""
318
+ inertia_moment = -self.waterplane_integral(self.mesh.faces_centers[:,1]**2)
319
+ return inertia_moment / self.volume
320
+
321
+ @property
322
+ def longitudinal_metacentric_radius(self):
323
+ """Returns longitudinal metacentric radius of the mesh."""
324
+ inertia_moment = -self.waterplane_integral(self.mesh.faces_centers[:,0]**2)
325
+ return inertia_moment / self.volume
326
+
327
+ @property
328
+ def transversal_metacentric_height(self):
329
+ """Returns transversal metacentric height of the mesh."""
330
+ gb = self.center_of_mass - self.center_of_buoyancy
331
+ return self.transversal_metacentric_radius - gb[2]
332
+
333
+ @property
334
+ def longitudinal_metacentric_height(self):
335
+ """Returns longitudinal metacentric height of the mesh."""
336
+ gb = self.center_of_mass - self.center_of_buoyancy
337
+ return self.longitudinal_metacentric_radius - gb[2]
338
+
339
+ def dof_normals(self, dof):
340
+ """Returns dot product of the surface face normals and DOF"""
341
+ return np.sum(self.mesh.faces_normals * dof, axis=1)
342
+
343
+ def _infer_rotation_center(self):
344
+ """Hacky way to infer the point around which the rotation dofs are defined.
345
+ (Assuming all three rotation dofs are defined around the same point).
346
+ In the future, should be replaced by something more robust.
347
+ """
348
+ if hasattr(self, "rotation_center"):
349
+ return np.asarray(self.rotation_center)
350
+
351
+ else:
352
+ try:
353
+ xc1 = self.dofs["Pitch"][:, 2] + self.mesh.faces_centers[:, 0]
354
+ xc2 = -self.dofs["Yaw"][:, 1] + self.mesh.faces_centers[:, 0]
355
+ yc1 = self.dofs["Yaw"][:, 0] + self.mesh.faces_centers[:, 1]
356
+ yc2 = -self.dofs["Roll"][:, 2] + self.mesh.faces_centers[:, 1]
357
+ zc1 = -self.dofs["Pitch"][:, 0] + self.mesh.faces_centers[:, 2]
358
+ zc2 = self.dofs["Roll"][:, 1] + self.mesh.faces_centers[:, 2]
359
+
360
+ # All items should be identical in a given vector
361
+ assert np.isclose(xc1, xc1[0]).all()
362
+ assert np.isclose(yc1, yc1[0]).all()
363
+ assert np.isclose(zc1, zc1[0]).all()
364
+
365
+ # Both vector should be identical
366
+ assert np.allclose(xc1, xc2)
367
+ assert np.allclose(yc1, yc2)
368
+ assert np.allclose(zc1, zc2)
369
+
370
+ return np.array([xc1[0], yc1[0], zc1[0]])
371
+
372
+ except Exception as e:
373
+ raise ValueError(
374
+ f"Failed to infer the rotation center of {self.name} to compute rigid body hydrostatics.\n"
375
+ f"Possible fix: add a `rotation_center` attribute to {self.name}.\n"
376
+ "Note that rigid body hydrostatic methods currently assume that the three rotation dofs have the same rotation center."
377
+ ) from e
378
+
379
+ def each_hydrostatic_stiffness(self, influenced_dof_name, radiating_dof_name, *,
380
+ influenced_dof_div=0.0, rho=1000.0, g=9.81):
381
+ r"""
382
+ Return the hydrostatic stiffness for a pair of DOFs.
383
+
384
+ :math:`C_{ij} = \rho g\iint_S (\hat{n} \cdot V_j) (w_i + z D_i) dS`
385
+
386
+ where :math:`\hat{n}` is surface normal,
387
+
388
+ :math:`V_i = u_i \hat{n}_x + v_i \hat{n}_y + w_i \hat{n}_z` is DOF vector and
389
+
390
+ :math:`D_i = \nabla \cdot V_i` is the divergence of the DOF.
391
+
392
+ Parameters
393
+ ----------
394
+ influenced_dof_name : str
395
+ Name of influenced DOF vector of the FloatingBody
396
+ radiating_dof_name: str
397
+ Name of radiating DOF vector of the FloatingBody
398
+ influenced_dof_div: np.ndarray (Face_count), optional
399
+ Influenced DOF divergence of the FloatingBody, by default 0.0.
400
+ rho: float, optional
401
+ water density, by default 1000.0
402
+ g: float, optional
403
+ Gravity acceleration, by default 9.81
404
+
405
+ Returns
406
+ -------
407
+ hs_ij: xarray.variable
408
+ hydrostatic_stiffness of ith DOF and jth DOF.
409
+
410
+ Note
411
+ ----
412
+ This function computes the hydrostatic stiffness assuming :math:`D_{i} = 0`.
413
+ If :math:`D_i \neq 0`, input the divergence interpolated to face centers.
414
+
415
+ General integral equations are used for the rigid body modes and
416
+ Neumann (1994) method is used for flexible modes.
417
+
418
+ References
419
+ ----------
420
+ Newman, John Nicholas. "Wave effects on deformable bodies."Applied ocean
421
+ research" 16.1 (1994): 47-59.
422
+ http://resolver.tudelft.nl/uuid:0adff84c-43c7-43aa-8cd8-d4c44240bed8
423
+
424
+ """
425
+ # Newman (1994) formula is not 'complete' as recovering the rigid body
426
+ # terms is not possible. https://doi.org/10.1115/1.3058702.
427
+
428
+ # Alternative is to use the general equation of hydrostatic and
429
+ # restoring coefficient for rigid modes and use Newman equation for elastic
430
+ # modes.
431
+
432
+ rigid_dof_names = ("Surge", "Sway", "Heave", "Roll", "Pitch", "Yaw")
433
+ dof_pair = (influenced_dof_name, radiating_dof_name)
434
+
435
+ if set(dof_pair).issubset(set(rigid_dof_names)):
436
+ if self.center_of_mass is None:
437
+ raise ValueError(f"Trying to compute rigid-body hydrostatic stiffness for {self.name}, but no center of mass has been defined.\n"
438
+ f"Suggested solution: define a `center_of_mass` attribute for the FloatingBody {self.name}.")
439
+ mass = self.disp_mass(rho=rho) if self.mass is None else self.mass
440
+ xc, yc, zc = self._infer_rotation_center()
441
+
442
+ if dof_pair == ("Heave", "Heave"):
443
+ norm_hs_stiff = self.waterplane_area
444
+ elif dof_pair in [("Heave", "Roll"), ("Roll", "Heave")]:
445
+ norm_hs_stiff = -self.waterplane_integral(self.mesh.faces_centers[:,1] - yc)
446
+ elif dof_pair in [("Heave", "Pitch"), ("Pitch", "Heave")]:
447
+ norm_hs_stiff = self.waterplane_integral(self.mesh.faces_centers[:,0] - xc)
448
+ elif dof_pair == ("Roll", "Roll"):
449
+ norm_hs_stiff = (
450
+ -self.waterplane_integral((self.mesh.faces_centers[:,1] - yc)**2)
451
+ + self.volume*(self.center_of_buoyancy[2] - zc) - mass/rho*(self.center_of_mass[2] - zc)
452
+ )
453
+ elif dof_pair in [("Roll", "Pitch"), ("Pitch", "Roll")]:
454
+ norm_hs_stiff = self.waterplane_integral((self.mesh.faces_centers[:,0] - xc)
455
+ * (self.mesh.faces_centers[:,1] - yc))
456
+ elif dof_pair == ("Roll", "Yaw"):
457
+ norm_hs_stiff = - self.volume*(self.center_of_buoyancy[0] - xc) + mass/rho*(self.center_of_mass[0] - xc)
458
+ elif dof_pair == ("Pitch", "Pitch"):
459
+ norm_hs_stiff = (
460
+ -self.waterplane_integral((self.mesh.faces_centers[:,0] - xc)**2)
461
+ + self.volume*(self.center_of_buoyancy[2] - zc) - mass/rho*(self.center_of_mass[2] - zc)
462
+ )
463
+ elif dof_pair == ("Pitch", "Yaw"):
464
+ norm_hs_stiff = - self.volume*(self.center_of_buoyancy[1] - yc) + mass/rho*(self.center_of_mass[1] - yc)
465
+ else:
466
+ norm_hs_stiff = 0.0
467
+ else:
468
+ if self.mass is not None and not np.isclose(self.mass, self.disp_mass(rho=rho), rtol=1e-4):
469
+ raise NotImplementedError(
470
+ f"Trying to compute the hydrostatic stiffness for dofs {radiating_dof_name} and {influenced_dof_name}"
471
+ f"of body {self.name}, which is not neutrally buoyant (mass={self.mass}, disp_mass={self.disp_mass(rho=rho)}).\n"
472
+ f"This case has not been implemented in Capytaine. You need either a single rigid body or a neutrally buoyant body."
473
+ )
474
+
475
+ # Newman (1994) formula for flexible DOFs
476
+ influenced_dof = np.array(self.dofs[influenced_dof_name])
477
+ radiating_dof = np.array(self.dofs[radiating_dof_name])
478
+ influenced_dof_div_array = np.array(influenced_dof_div)
479
+
480
+ radiating_dof_normal = self.dof_normals(radiating_dof)
481
+ z_influenced_dof_div = influenced_dof[:,2] + self.mesh.faces_centers[:,2] * influenced_dof_div_array
482
+ norm_hs_stiff = self.surface_integral( -radiating_dof_normal * z_influenced_dof_div)
483
+
484
+ hs_stiff = rho * g * norm_hs_stiff
485
+
486
+ return xr.DataArray([[hs_stiff]],
487
+ dims=['influenced_dof', 'radiating_dof'],
488
+ coords={'influenced_dof': [influenced_dof_name],
489
+ 'radiating_dof': [radiating_dof_name]},
490
+ name="hydrostatic_stiffness"
491
+ )
492
+
493
+ def compute_hydrostatic_stiffness(self, *, divergence=None, rho=1000.0, g=9.81):
494
+ r"""
495
+ Compute hydrostatic stiffness matrix for all DOFs of the body.
496
+
497
+ :math:`C_{ij} = \rho g\iint_S (\hat{n} \cdot V_j) (w_i + z D_i) dS`
498
+
499
+ where :math:`\hat{n}` is surface normal,
500
+
501
+ :math:`V_i = u_i \hat{n}_x + v_i \hat{n}_y + w_i \hat{n}_z` is DOF vector and
502
+
503
+ :math:`D_i = \nabla \cdot V_i` is the divergence of the DOF.
504
+
505
+ Parameters
506
+ ----------
507
+ divergence : dict mapping a dof name to an array of shape (nb_faces) or
508
+ xarray.DataArray of shape (nb_dofs × nb_faces), optional
509
+ Divergence of the DOFs, by default None
510
+ rho : float, optional
511
+ Water density, by default 1000.0
512
+ g: float, optional
513
+ Gravity acceleration, by default 9.81
514
+
515
+ Returns
516
+ -------
517
+ xr.DataArray
518
+ Matrix of hydrostatic stiffness
519
+
520
+ Note
521
+ ----
522
+ This function computes the hydrostatic stiffness assuming :math:`D_{i} = 0`.
523
+ If :math:`D_i \neq 0`, input the divergence interpolated to face centers.
524
+
525
+ General integral equations are used for the rigid body modes and
526
+ Neumann (1994) method is used for flexible modes.
527
+
528
+ References
529
+ ----------
530
+ Newman, John Nicholas. "Wave effects on deformable bodies."Applied ocean
531
+ research" 16.1 (1994): 47-59.
532
+ http://resolver.tudelft.nl/uuid:0adff84c-43c7-43aa-8cd8-d4c44240bed8
533
+
534
+ """
535
+ if len(self.dofs) == 0:
536
+ raise AttributeError("Cannot compute hydrostatics stiffness on {} since no dof has been defined.".format(self.name))
537
+
538
+ def divergence_dof(influenced_dof):
539
+ if influenced_dof.lower() in [*TRANSLATION_DOFS_DIRECTIONS, *ROTATION_DOFS_AXIS]:
540
+ return 0.0 # Dummy value that is not actually used afterwards.
541
+ elif divergence is None:
542
+ return 0.0
543
+ elif isinstance(divergence, dict) and influenced_dof in divergence.keys():
544
+ return divergence[influenced_dof]
545
+ elif isinstance(divergence, xr.DataArray) and influenced_dof in divergence.coords["influenced_dof"]:
546
+ return divergence.sel(influenced_dof=influenced_dof).values
547
+ else:
548
+ LOG.warning("Computing hydrostatic stiffness without the divergence of {}".format(influenced_dof))
549
+ return 0.0
550
+
551
+ hs_set = xr.merge([
552
+ self.each_hydrostatic_stiffness(
553
+ influenced_dof_name, radiating_dof_name,
554
+ influenced_dof_div = divergence_dof(influenced_dof_name),
555
+ rho=rho, g=g
556
+ )
557
+ for radiating_dof_name in self.dofs
558
+ for influenced_dof_name in self.dofs
559
+ ])
560
+
561
+ # Reorder dofs
562
+ K = hs_set.hydrostatic_stiffness.sel(influenced_dof=list(self.dofs.keys()), radiating_dof=list(self.dofs.keys()))
563
+ return K
564
+
565
+ def compute_rigid_body_inertia(self, *, rho=1000.0, output_type="body_dofs"):
566
+ """
567
+ Inertia Mass matrix of the body for 6 rigid DOFs.
568
+
569
+ Parameters
570
+ ----------
571
+ rho : float, optional
572
+ Density of water, by default 1000.0
573
+ output_type : {"body_dofs", "rigid_dofs", "all_dofs"}
574
+ Type of DOFs for mass mat output, by default "body_dofs".
575
+
576
+ Returns
577
+ -------
578
+ xarray.DataArray
579
+ Inertia matrix
580
+
581
+ Raises
582
+ ------
583
+ ValueError
584
+ If output_type is not in {"body_dofs", "rigid_dofs", "all_dofs"}.
585
+ """
586
+ if self.center_of_mass is None:
587
+ raise ValueError(f"Trying to compute rigid-body inertia matrix for {self.name}, but no center of mass has been defined.\n"
588
+ f"Suggested solution: define a `center_of_mass` attribute for the FloatingBody {self.name}.")
589
+
590
+ rc = self._infer_rotation_center()
591
+ fcs = (self.mesh.faces_centers - rc).T
592
+ combinations = np.array([fcs[0]**2, fcs[1]**2, fcs[2]**2, fcs[0]*fcs[1],
593
+ fcs[1]*fcs[2], fcs[2]*fcs[0]])
594
+ integrals = np.array([
595
+ [np.sum(normal_i * fcs[axis] * combination * self.mesh.faces_areas)
596
+ for combination in combinations]
597
+ for axis, normal_i in enumerate(self.mesh.faces_normals.T)])
598
+
599
+
600
+ inertias = np.array([
601
+ (integrals[0,1] + integrals[0,2] + integrals[1,1]/3
602
+ + integrals[1,2] + integrals[2,1] + integrals[2,2]/3)/3,
603
+ (integrals[0,0]/3 + integrals[0,2] + integrals[1,0]
604
+ + integrals[1,2] + integrals[2,0] + integrals[2,2]/3)/3,
605
+ (integrals[0,0]/3 + integrals[0,1] + integrals[1,0]
606
+ + integrals[1,1]/3 + integrals[2,0] + integrals[2,1] )/3,
607
+ integrals[2,3],
608
+ integrals[0,4],
609
+ integrals[1,5]
610
+ ])
611
+
612
+ cog = self.center_of_mass - rc
613
+ volume = self.volume
614
+ volumic_inertia_matrix = np.array([
615
+ [ volume , 0 , 0 ,
616
+ 0 , volume*cog[2] , -volume*cog[1] ],
617
+ [ 0 , volume , 0 ,
618
+ -volume*cog[2] , 0 , volume*cog[0] ],
619
+ [ 0 , 0 , volume ,
620
+ volume*cog[1] , -volume*cog[0] , 0 ] ,
621
+ [ 0 , -volume*cog[2] , volume*cog[1] ,
622
+ inertias[0] , -inertias[3] , -inertias[5] ],
623
+ [ volume*cog[2] , 0 , -volume*cog[0] ,
624
+ -inertias[3] , inertias[1] , -inertias[4] ],
625
+ [-volume*cog[1] , volume*cog[0] , 0 ,
626
+ -inertias[5] , -inertias[4] , inertias[2] ],
627
+ ])
628
+
629
+ density = rho if self.mass is None else self.mass/volume
630
+ inertia_matrix = density * volumic_inertia_matrix
631
+
632
+ # Rigid DOFs
633
+ rigid_dof_names = ["Surge", "Sway", "Heave", "Roll", "Pitch", "Yaw"]
634
+ rigid_inertia_matrix_xr = xr.DataArray(data=np.asarray(inertia_matrix),
635
+ dims=['influenced_dof', 'radiating_dof'],
636
+ coords={'influenced_dof': rigid_dof_names,
637
+ 'radiating_dof': rigid_dof_names},
638
+ name="inertia_matrix")
639
+
640
+ # Body DOFs (Default as np.nan)
641
+ body_dof_names = list(self.dofs)
642
+ body_dof_count = len(body_dof_names)
643
+ other_dofs_inertia_matrix_xr = xr.DataArray(np.nan * np.zeros([body_dof_count, body_dof_count]),
644
+ dims=['influenced_dof', 'radiating_dof'],
645
+ coords={'influenced_dof': body_dof_names,
646
+ 'radiating_dof': body_dof_names},
647
+ name="inertia_matrix")
648
+
649
+ total_mass_xr = xr.merge([rigid_inertia_matrix_xr, other_dofs_inertia_matrix_xr], compat="override").inertia_matrix
650
+
651
+ non_rigid_dofs = set(body_dof_names) - set(rigid_dof_names)
652
+
653
+ if output_type == "body_dofs":
654
+ if len(non_rigid_dofs) > 0:
655
+ LOG.warning(f"Non-rigid dofs {non_rigid_dofs} detected: their \
656
+ inertia coefficients are assigned as NaN.")
657
+
658
+ inertia_matrix_xr = total_mass_xr.sel(influenced_dof=body_dof_names,
659
+ radiating_dof=body_dof_names)
660
+ elif output_type == "rigid_dofs":
661
+ inertia_matrix_xr = total_mass_xr.sel(influenced_dof=rigid_dof_names,
662
+ radiating_dof=rigid_dof_names)
663
+ elif output_type == "all_dofs":
664
+ if len(non_rigid_dofs) > 0:
665
+ LOG.warning("Non-rigid dofs: {non_rigid_dofs} are detected and \
666
+ respective inertia coefficients are assigned as NaN.")
667
+
668
+ inertia_matrix_xr = total_mass_xr
669
+ else:
670
+ raise ValueError(f"output_type should be either 'body_dofs', \
671
+ 'all_dofs' or 'rigid_dofs'. Given output_type = '{output_type}'.")
672
+
673
+ return inertia_matrix_xr
674
+
675
+
676
+ def compute_hydrostatics(self, *, rho=1000.0, g=9.81, divergence=None):
677
+ """Compute hydrostatics of the FloatingBody.
678
+
679
+ Parameters
680
+ ----------
681
+ rho : float, optional
682
+ Density of Water. The default is 1000.
683
+ g: float, optional
684
+ Gravity acceleration. The default is 9.81.
685
+ divergence : np.ndarray, optional
686
+ Divergence of the DOFs.
687
+
688
+ Returns
689
+ -------
690
+ hydrostatics : dict
691
+ All hydrostatics values of the FloatingBody.
692
+ """
693
+ if self.center_of_mass is None:
694
+ raise ValueError(f"Trying to compute hydrostatics for {self.name}, but no center of mass has been defined.\n"
695
+ f"Suggested solution: define a `center_of_mass` attribute for the FloatingBody {self.name}.")
696
+
697
+ immersed_self = self.immersed_part()
698
+
699
+ full_mesh_vertices = self.mesh.vertices
700
+ coord_max = full_mesh_vertices.max(axis=0)
701
+ coord_min = full_mesh_vertices.min(axis=0)
702
+ full_length, full_breadth, depth = full_mesh_vertices.max(axis=0) - full_mesh_vertices.min(axis=0)
703
+
704
+ vertices = immersed_self.mesh.vertices
705
+ sub_length, sub_breadth, _ = vertices.max(axis=0) - vertices.min(axis=0)
706
+
707
+ if abs(immersed_self.waterplane_area) > 1e-10:
708
+ water_plane_idx = np.isclose(vertices[:,2], 0.0)
709
+ water_plane = vertices[water_plane_idx][:,:-1]
710
+ wl_length, wl_breadth = water_plane.max(axis=0) - water_plane.min(axis=0)
711
+ else:
712
+ wl_length, wl_breadth = 0.0, 0.0
713
+
714
+ hydrostatics = {}
715
+ hydrostatics["g"] = g
716
+ hydrostatics["rho"] = rho
717
+ hydrostatics["center_of_mass"] = self.center_of_mass
718
+
719
+ hydrostatics["wet_surface_area"] = immersed_self.wet_surface_area
720
+ hydrostatics["disp_volumes"] = immersed_self.volumes
721
+ hydrostatics["disp_volume"] = immersed_self.volume
722
+ hydrostatics["disp_mass"] = immersed_self.disp_mass(rho=rho)
723
+ hydrostatics["center_of_buoyancy"] = immersed_self.center_of_buoyancy
724
+ hydrostatics["waterplane_center"] = np.append(immersed_self.waterplane_center, 0.0)
725
+ hydrostatics["waterplane_area"] = immersed_self.waterplane_area
726
+ hydrostatics["transversal_metacentric_radius"] = immersed_self.transversal_metacentric_radius
727
+ hydrostatics["longitudinal_metacentric_radius"] = immersed_self.longitudinal_metacentric_radius
728
+ hydrostatics["transversal_metacentric_height"] = immersed_self.transversal_metacentric_height
729
+ hydrostatics["longitudinal_metacentric_height"] = immersed_self.longitudinal_metacentric_height
730
+ self.hydrostatic_stiffness = hydrostatics["hydrostatic_stiffness"] = immersed_self.compute_hydrostatic_stiffness(
731
+ divergence=divergence, rho=rho, g=g)
732
+
733
+ hydrostatics["length_overall"] = full_length
734
+ hydrostatics["breadth_overall"] = full_breadth
735
+ hydrostatics["depth"] = depth
736
+ hydrostatics["draught"] = np.abs(coord_min[2])
737
+ hydrostatics["length_at_waterline"] = wl_length
738
+ hydrostatics["breadth_at_waterline"] = wl_breadth
739
+ hydrostatics["length_overall_submerged"] = sub_length
740
+ hydrostatics["breadth_overall_submerged"] = sub_breadth
741
+ if any(dof.lower() in {"surge", "sway", "heave", "roll", "pitch", "yaw"}
742
+ for dof in self.dofs) > 0: # If there is at least one rigid body dof:
743
+ self.inertia_matrix = hydrostatics["inertia_matrix"] = self.compute_rigid_body_inertia(rho=rho)
744
+
745
+ return hydrostatics
746
+
747
+
748
+ ###################
749
+ # Transformations #
750
+ ###################
751
+
752
+ def __add__(self, body_to_add: 'FloatingBody') -> 'FloatingBody':
753
+ return self.join_bodies(body_to_add)
754
+
755
+ def join_bodies(*bodies, name=None) -> 'FloatingBody':
756
+ if name is None:
757
+ name = "+".join(body.name for body in bodies)
758
+ meshes = CollectionOfMeshes(
759
+ [body.mesh for body in bodies],
760
+ name=f"{name}_mesh"
761
+ )
762
+ if all(body.lid_mesh is None for body in bodies):
763
+ lid_meshes = None
764
+ else:
765
+ lid_meshes = CollectionOfMeshes(
766
+ [body.lid_mesh for body in bodies if body.lid_mesh is not None],
767
+ name=f"{name}_lid_mesh"
768
+ )
769
+ dofs = FloatingBody.combine_dofs(bodies)
770
+
771
+ if all(body.mass is not None for body in bodies):
772
+ new_mass = sum(body.mass for body in bodies)
773
+ else:
774
+ new_mass = None
775
+
776
+ if (all(body.mass is not None for body in bodies)
777
+ and all(body.center_of_mass is not None for body in bodies)):
778
+ new_cog = sum(body.mass*np.asarray(body.center_of_mass) for body in bodies)/new_mass
779
+ else:
780
+ new_cog = None
781
+
782
+ joined_bodies = FloatingBody(
783
+ mesh=meshes, lid_mesh=lid_meshes, dofs=dofs,
784
+ mass=new_mass, center_of_mass=new_cog, name=name
785
+ )
786
+
787
+ for matrix_name in ["inertia_matrix", "hydrostatic_stiffness"]:
788
+ if all(hasattr(body, matrix_name) for body in bodies):
789
+ from scipy.linalg import block_diag
790
+ setattr(joined_bodies, matrix_name, joined_bodies.add_dofs_labels_to_matrix(
791
+ block_diag(*[getattr(body, matrix_name) for body in bodies])
792
+ ))
793
+
794
+ return joined_bodies
795
+
796
+ @staticmethod
797
+ def combine_dofs(bodies) -> dict:
798
+ """Combine the degrees of freedom of several bodies."""
799
+ dofs = {}
800
+ cum_nb_faces = accumulate(chain([0], (body.mesh.nb_faces for body in bodies)))
801
+ total_nb_faces = sum(body.mesh.nb_faces for body in bodies)
802
+ for body, nbf in zip(bodies, cum_nb_faces):
803
+ # nbf is the cumulative number of faces of the previous subbodies,
804
+ # that is the offset of the indices of the faces of the current body.
805
+ for name, dof in body.dofs.items():
806
+ new_dof = np.zeros((total_nb_faces, 3))
807
+ new_dof[nbf:nbf+len(dof), :] = dof
808
+ if '__' not in name:
809
+ new_dof_name = '__'.join([body.name, name])
810
+ else:
811
+ # The body is probably a combination of bodies already.
812
+ # So for the associativity of the + operation,
813
+ # it is better to keep the same name.
814
+ new_dof_name = name
815
+ dofs[new_dof_name] = new_dof
816
+ return dofs
817
+
818
+ def copy(self, name=None) -> 'FloatingBody':
819
+ """Return a deep copy of the body.
820
+
821
+ Parameters
822
+ ----------
823
+ name : str, optional
824
+ a name for the new copy
825
+ """
826
+ new_body = copy.deepcopy(self)
827
+ if name is None:
828
+ new_body.name = f"copy_of_{self.name}"
829
+ LOG.debug(f"Copy {self.name}.")
830
+ else:
831
+ new_body.name = name
832
+ LOG.debug(f"Copy {self.name} under the name {name}.")
833
+ return new_body
834
+
835
+ def assemble_regular_array(self, distance, nb_bodies):
836
+ """Create an regular array of identical bodies.
837
+
838
+ Parameters
839
+ ----------
840
+ distance : float
841
+ Center-to-center distance between objects in the array
842
+ nb_bodies : couple of ints
843
+ Number of objects in the x and y directions.
844
+
845
+ Returns
846
+ -------
847
+ FloatingBody
848
+ """
849
+ bodies = (self.translated((i*distance, j*distance, 0), name=f"{i}_{j}") for j in range(nb_bodies[1]) for i in range(nb_bodies[0]))
850
+ array = FloatingBody.join_bodies(*bodies)
851
+ array.mesh = build_regular_array_of_meshes(self.mesh, distance, nb_bodies)
852
+ array.name = f"array_of_{self.name}"
853
+ return array
854
+
855
+ def assemble_arbitrary_array(self, locations:np.ndarray):
856
+
857
+ if not isinstance(locations, np.ndarray):
858
+ raise TypeError('locations must be of type np.ndarray')
859
+ assert locations.shape[1] == 2, 'locations must be of shape nx2, received {:}'.format(locations.shape)
860
+
861
+ fb_list = []
862
+ for idx, li in enumerate(locations):
863
+ fb1 = self.copy()
864
+ fb1.translate(np.append(li,0))
865
+ fb1.name = 'arbitrary_array_body{:02d}'.format(idx)
866
+ fb_list.append(fb1)
867
+
868
+ arbitrary_array = fb_list[0].join_bodies(*fb_list[1:])
869
+
870
+ return arbitrary_array
871
+
872
+ def extract_faces(self, id_faces_to_extract, return_index=False):
873
+ """Create a new FloatingBody by extracting some faces from the mesh.
874
+ The dofs evolve accordingly.
875
+ The lid_mesh, center_of_mass, mass and hydrostatics data are discarded.
876
+ """
877
+ if isinstance(self.mesh, CollectionOfMeshes):
878
+ raise NotImplementedError # TODO
879
+
880
+ if return_index:
881
+ new_mesh, id_v = Mesh.extract_faces(self.mesh, id_faces_to_extract, return_index)
882
+ else:
883
+ new_mesh = Mesh.extract_faces(self.mesh, id_faces_to_extract, return_index)
884
+ new_body = FloatingBody(new_mesh)
885
+ LOG.info(f"Extract floating body from {self.name}.")
886
+
887
+ new_body.dofs = {}
888
+ for name, dof in self.dofs.items():
889
+ new_body.dofs[name] = dof[id_faces_to_extract, :]
890
+
891
+ if return_index:
892
+ return new_body, id_v
893
+ else:
894
+ return new_body
895
+
896
+ def sliced_by_plane(self, plane):
897
+ """Return the same body, but replace the mesh by a set of two meshes
898
+ corresponding to each sides of the plane."""
899
+ return FloatingBody(mesh=self.mesh.sliced_by_plane(plane),
900
+ lid_mesh=self.lid_mesh.sliced_by_plane(plane)
901
+ if self.lid_mesh is not None else None,
902
+ dofs=self.dofs, name=self.name)
903
+
904
+ def minced(self, nb_slices=(8, 8, 4)):
905
+ """Experimental method decomposing the mesh as a hierarchical structure.
906
+
907
+ Parameters
908
+ ----------
909
+ nb_slices: Tuple[int, int, int]
910
+ The number of slices in each of the x, y and z directions.
911
+ Only powers of 2 are supported at the moment.
912
+
913
+ Returns
914
+ -------
915
+ FloatingBody
916
+ """
917
+ minced_body = self.copy()
918
+
919
+ # Extreme points of the mesh in each directions.
920
+ x_min, x_max, y_min, y_max, z_min, z_max = self.mesh.axis_aligned_bbox
921
+ sizes = [(x_min, x_max), (y_min, y_max), (z_min, z_max)]
922
+
923
+ directions = [np.array(d) for d in [(1, 0, 0), (0, 1, 0), (0, 0, 1)]]
924
+
925
+ def _slice_positions_at_depth(i):
926
+ """Helper function.
927
+
928
+ Returns a list of floats as follows:
929
+ i=1 -> [1/2]
930
+ i=2 -> [1/4, 3/4]
931
+ i=3 -> [1/8, 3/8, 5/8, 7/8]
932
+ ...
933
+ """
934
+ denominator = 2**i
935
+ return [numerator/denominator for numerator in range(1, denominator, 2)]
936
+
937
+ # GENERATE ALL THE PLANES THAT WILL BE USED TO MINCE THE MESH
938
+ planes = []
939
+ for direction, nb_slices_in_dir, (min_coord, max_coord) in zip(directions, nb_slices, sizes):
940
+ planes_in_dir = []
941
+
942
+ depth_of_treelike_structure = int(np.log2(nb_slices_in_dir))
943
+ for i_depth in range(1, depth_of_treelike_structure+1):
944
+ planes_in_dir_at_depth = []
945
+ for relative_position in _slice_positions_at_depth(i_depth):
946
+ slice_position = (min_coord + relative_position*(max_coord-min_coord))*direction
947
+ plane = Plane(normal=direction, point=slice_position)
948
+ planes_in_dir_at_depth.append(plane)
949
+ planes_in_dir.append(planes_in_dir_at_depth)
950
+ planes.append(planes_in_dir)
951
+
952
+ # SLICE THE MESH
953
+ intermingled_x_y_z = chain.from_iterable(zip_longest(*planes))
954
+ for planes in intermingled_x_y_z:
955
+ if planes is not None:
956
+ for plane in planes:
957
+ minced_body = minced_body.sliced_by_plane(plane)
958
+ return minced_body
959
+
960
+ @inplace_transformation
961
+ def mirror(self, plane):
962
+ self.mesh.mirror(plane)
963
+ if self.lid_mesh is not None:
964
+ self.lid_mesh.mirror(plane)
965
+ for dof in self.dofs:
966
+ self.dofs[dof] -= 2 * np.outer(np.dot(self.dofs[dof], plane.normal), plane.normal)
967
+ for point_attr in ('geometric_center', 'rotation_center', 'center_of_mass'):
968
+ if point_attr in self.__dict__ and self.__dict__[point_attr] is not None:
969
+ point = np.array(self.__dict__[point_attr])
970
+ shift = - 2 * (np.dot(point, plane.normal) - plane.c) * plane.normal
971
+ self.__dict__[point_attr] = point + shift
972
+ return self
973
+
974
+ @inplace_transformation
975
+ def translate(self, vector, *args, **kwargs):
976
+ self.mesh.translate(vector, *args, **kwargs)
977
+ if self.lid_mesh is not None:
978
+ self.lid_mesh.translate(vector, *args, **kwargs)
979
+ for point_attr in ('geometric_center', 'rotation_center', 'center_of_mass'):
980
+ if point_attr in self.__dict__ and self.__dict__[point_attr] is not None:
981
+ self.__dict__[point_attr] = np.array(self.__dict__[point_attr]) + vector
982
+ return self
983
+
984
+ @inplace_transformation
985
+ def rotate(self, axis, angle):
986
+ self.mesh.rotate(axis, angle)
987
+ if self.lid_mesh is not None:
988
+ self.lid_mesh.rotate(axis, angle)
989
+ for point_attr in ('geometric_center', 'rotation_center', 'center_of_mass'):
990
+ if point_attr in self.__dict__ and self.__dict__[point_attr] is not None:
991
+ self.__dict__[point_attr] = axis.rotate_points([self.__dict__[point_attr]], angle)[0, :]
992
+ for dof in self.dofs:
993
+ self.dofs[dof] = axis.rotate_vectors(self.dofs[dof], angle)
994
+ return self
995
+
996
+ @inplace_transformation
997
+ def clip(self, plane):
998
+ # Clip mesh
999
+ LOG.info(f"Clipping {self.name} with respect to {plane}")
1000
+ self.mesh.clip(plane)
1001
+ if self.lid_mesh is not None:
1002
+ self.lid_mesh.clip(plane)
1003
+ if self.lid_mesh.nb_faces == 0:
1004
+ LOG.warning("Lid mesh %s is empty after clipping. The lid mesh is removed.", self.lid_mesh)
1005
+ self.lid_mesh = None
1006
+
1007
+ # Clip dofs
1008
+ ids = self.mesh._clipping_data['faces_ids']
1009
+ for dof in self.dofs:
1010
+ if len(ids) > 0:
1011
+ self.dofs[dof] = np.array(self.dofs[dof])[ids]
1012
+ else:
1013
+ self.dofs[dof] = np.empty((0, 3))
1014
+ return self
1015
+
1016
+
1017
+ #############
1018
+ # Display #
1019
+ #############
1020
+
1021
+ def __short_str__(self):
1022
+ return (f"{self.__class__.__name__}(..., name=\"{self.name}\")")
1023
+
1024
+ def _optional_params_str(self):
1025
+ items = []
1026
+ if self.mass is not None: items.append(f"mass={self.mass}, ")
1027
+ if self.center_of_mass is not None: items.append(f"center_of_mass={self.center_of_mass}, ")
1028
+ return ''.join(items)
1029
+
1030
+ def __str__(self):
1031
+ short_dofs = '{' + ', '.join('"{}": ...'.format(d) for d in self.dofs) + '}'
1032
+
1033
+ if self.lid_mesh is not None:
1034
+ lid_mesh_str = self.lid_mesh.__short_str__()
1035
+ else:
1036
+ lid_mesh_str = str(None)
1037
+
1038
+ return (f"{self.__class__.__name__}(mesh={self.mesh.__short_str__()}, lid_mesh={lid_mesh_str}, "
1039
+ f"dofs={short_dofs}, {self._optional_params_str()}name=\"{self.name}\")")
1040
+
1041
+ def __repr__(self):
1042
+ short_dofs = '{' + ', '.join('"{}": ...'.format(d) for d in self.dofs) + '}'
1043
+
1044
+ if self.lid_mesh is not None:
1045
+ lid_mesh_str = str(self.lid_mesh)
1046
+ else:
1047
+ lid_mesh_str = str(None)
1048
+
1049
+ return (f"{self.__class__.__name__}(mesh={str(self.mesh)}, lid_mesh={lid_mesh_str}, "
1050
+ f"dofs={short_dofs}, {self._optional_params_str()}name=\"{self.name}\")")
1051
+
1052
+ def _repr_pretty_(self, p, cycle):
1053
+ p.text(self.__str__())
1054
+
1055
+ def __rich_repr__(self):
1056
+ class DofWithShortRepr:
1057
+ def __repr__(self):
1058
+ return '...'
1059
+ yield "mesh", self.mesh
1060
+ yield "lid_mesh", self.lid_mesh
1061
+ yield "dofs", {d: DofWithShortRepr() for d in self.dofs}
1062
+ if self.mass is not None:
1063
+ yield "mass", self.mass, None
1064
+ if self.center_of_mass is not None:
1065
+ yield "center_of_mass", tuple(self.center_of_mass)
1066
+ yield "name", self.name
1067
+
1068
+ def show(self, **kwargs):
1069
+ from capytaine.ui.vtk.body_viewer import FloatingBodyViewer
1070
+ viewer = FloatingBodyViewer()
1071
+ viewer.add_body(self, **kwargs)
1072
+ viewer.show()
1073
+ viewer.finalize()
1074
+
1075
+ def show_matplotlib(self, *args, **kwargs):
1076
+ return self.mesh.show_matplotlib(*args, **kwargs)
1077
+
1078
+ def animate(self, motion, *args, **kwargs):
1079
+ """Display a motion as a 3D animation.
1080
+
1081
+ Parameters
1082
+ ==========
1083
+ motion: dict or pd.Series or str
1084
+ A dict or series mapping the name of the dofs to its amplitude.
1085
+ If a single string is passed, it is assumed to be the name of a dof
1086
+ and this dof with a unit amplitude will be displayed.
1087
+ """
1088
+ from capytaine.ui.vtk.animation import Animation
1089
+ if isinstance(motion, str):
1090
+ motion = {motion: 1.0}
1091
+ elif isinstance(motion, xr.DataArray):
1092
+ motion = {k: motion.sel(radiating_dof=k).data for k in motion.coords["radiating_dof"].data}
1093
+
1094
+ if any(dof not in self.dofs for dof in motion):
1095
+ missing_dofs = set(motion.keys()) - set(self.dofs.keys())
1096
+ raise ValueError(f"Trying to animate the body {self.name} using dof(s) {missing_dofs}, but no dof of this name is defined for {self.name}.")
1097
+
1098
+ animation = Animation(*args, **kwargs)
1099
+ animation._add_actor(self.mesh.merged(), faces_motion=sum(motion[dof_name] * dof for dof_name, dof in self.dofs.items() if dof_name in motion))
1100
+ return animation
1101
+
1102
+ @property
1103
+ def minimal_computable_wavelength(self):
1104
+ """For accuracy of the resolution, wavelength should not be smaller than this value."""
1105
+ if self.lid_mesh is not None:
1106
+ return max(8*self.mesh.faces_radiuses.max(), 8*self.lid_mesh.faces_radiuses.max())
1107
+ else:
1108
+ return 8*self.mesh.faces_radiuses.max()
1109
+
1110
+ @lru_cache
1111
+ def first_irregular_frequency_estimate(self, *, g=9.81):
1112
+ r"""Estimates the angular frequency of the lowest irregular
1113
+ frequency.
1114
+ This is based on the formula for the lowest irregular frequency of a
1115
+ parallelepiped of size :math:`L \times B` and draft :math:`H`:
1116
+
1117
+ .. math::
1118
+ \omega = \sqrt{
1119
+ \frac{\pi g \sqrt{\frac{1}{B^2} + \frac{1}{L^2}}}
1120
+ {\tanh\left(\pi H \sqrt{\frac{1}{B^2} + \frac{1}{L^2}} \right)}
1121
+ }
1122
+
1123
+ The formula is applied to all shapes to get an estimate that is usually
1124
+ conservative.
1125
+ The definition of a lid (supposed to be fully covering and horizontal)
1126
+ is taken into account.
1127
+ """
1128
+ if self.lid_mesh is None:
1129
+ draft = abs(self.mesh.vertices[:, 2].min())
1130
+ else:
1131
+ draft = abs(self.lid_mesh.vertices[:, 2].min())
1132
+ if draft < 1e-6:
1133
+ return np.inf
1134
+
1135
+ # Look for the x and y span of each components (e.g. for multibody) and
1136
+ # keep the one causing the lowest irregular frequency.
1137
+ # The draft is supposed to be same for all components.
1138
+ omega = np.inf
1139
+ for comp in connected_components(self.mesh):
1140
+ for ccomp in connected_components_of_waterline(comp):
1141
+ x_span = ccomp.vertices[:, 0].max() - ccomp.vertices[:, 0].min()
1142
+ y_span = ccomp.vertices[:, 1].max() - ccomp.vertices[:, 1].min()
1143
+ p = np.hypot(1/x_span, 1/y_span)
1144
+ omega_comp = np.sqrt(np.pi*g*p/(np.tanh(np.pi*draft*p)))
1145
+ omega = min(omega, omega_comp)
1146
+ return omega
1147
+
1148
+ def cluster_bodies(*bodies, name=None):
1149
+ """
1150
+ Builds a hierarchical clustering from a group of bodies
1151
+
1152
+ Parameters
1153
+ ----------
1154
+ bodies: list
1155
+ a list of bodies
1156
+ name: str, optional
1157
+ a name for the new body
1158
+
1159
+ Returns
1160
+ -------
1161
+ FloatingBody
1162
+ Array built from the provided bodies
1163
+ """
1164
+ from scipy.cluster.hierarchy import linkage
1165
+ nb_buoys = len(bodies)
1166
+
1167
+ if any(body.center_of_buoyancy is None for body in bodies):
1168
+ raise ValueError("The center of buoyancy of each body needs to be known for clustering")
1169
+ buoys_positions = np.stack([body.center_of_buoyancy for body in bodies])[:,:2]
1170
+
1171
+ ln_matrix = linkage(buoys_positions, method='centroid', metric='euclidean')
1172
+
1173
+ node_list = list(bodies) # list of nodes of the tree: the first nodes are single bodies
1174
+
1175
+ # Join the bodies, with an ordering consistent with the dendrogram.
1176
+ # Done by reading the linkage matrix: its i-th row contains the labels
1177
+ # of the two nodes that are merged to form the (n + i)-th node
1178
+ for ii in range(len(ln_matrix)):
1179
+ node_tag = ii + nb_buoys # the first nb_buoys tags are already taken
1180
+ merge_left = int(ln_matrix[ii,0])
1181
+ merge_right = int(ln_matrix[ii,1])
1182
+ # The new node is the parent of merge_left and merge_right
1183
+ new_node_ls = [node_list[merge_left], node_list[merge_right]]
1184
+ new_node = FloatingBody.join_bodies(*new_node_ls, name='node_{:d}'.format(node_tag))
1185
+ node_list.append(new_node)
1186
+
1187
+ # The last node is the parent of all others
1188
+ all_buoys = new_node
1189
+
1190
+ if name is not None:
1191
+ all_buoys.name = name
1192
+
1193
+ return all_buoys