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