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