capytaine 3.0.0a1__cp38-cp38-macosx_15_0_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 (65) 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 +21 -0
  5. capytaine/__init__.py +32 -0
  6. capytaine/bem/__init__.py +0 -0
  7. capytaine/bem/airy_waves.py +111 -0
  8. capytaine/bem/engines.py +321 -0
  9. capytaine/bem/problems_and_results.py +601 -0
  10. capytaine/bem/solver.py +718 -0
  11. capytaine/bodies/__init__.py +4 -0
  12. capytaine/bodies/bodies.py +630 -0
  13. capytaine/bodies/dofs.py +146 -0
  14. capytaine/bodies/hydrostatics.py +540 -0
  15. capytaine/bodies/multibodies.py +216 -0
  16. capytaine/green_functions/Delhommeau_float32.cpython-38-darwin.so +0 -0
  17. capytaine/green_functions/Delhommeau_float64.cpython-38-darwin.so +0 -0
  18. capytaine/green_functions/__init__.py +2 -0
  19. capytaine/green_functions/abstract_green_function.py +64 -0
  20. capytaine/green_functions/delhommeau.py +522 -0
  21. capytaine/green_functions/hams.py +210 -0
  22. capytaine/io/__init__.py +0 -0
  23. capytaine/io/bemio.py +153 -0
  24. capytaine/io/legacy.py +228 -0
  25. capytaine/io/wamit.py +479 -0
  26. capytaine/io/xarray.py +673 -0
  27. capytaine/meshes/__init__.py +2 -0
  28. capytaine/meshes/abstract_meshes.py +375 -0
  29. capytaine/meshes/clean.py +302 -0
  30. capytaine/meshes/clip.py +347 -0
  31. capytaine/meshes/export.py +89 -0
  32. capytaine/meshes/geometry.py +259 -0
  33. capytaine/meshes/io.py +433 -0
  34. capytaine/meshes/meshes.py +826 -0
  35. capytaine/meshes/predefined/__init__.py +6 -0
  36. capytaine/meshes/predefined/cylinders.py +280 -0
  37. capytaine/meshes/predefined/rectangles.py +202 -0
  38. capytaine/meshes/predefined/spheres.py +55 -0
  39. capytaine/meshes/quality.py +159 -0
  40. capytaine/meshes/surface_integrals.py +82 -0
  41. capytaine/meshes/symmetric_meshes.py +641 -0
  42. capytaine/meshes/visualization.py +353 -0
  43. capytaine/post_pro/__init__.py +6 -0
  44. capytaine/post_pro/free_surfaces.py +85 -0
  45. capytaine/post_pro/impedance.py +92 -0
  46. capytaine/post_pro/kochin.py +54 -0
  47. capytaine/post_pro/rao.py +60 -0
  48. capytaine/tools/__init__.py +0 -0
  49. capytaine/tools/block_circulant_matrices.py +275 -0
  50. capytaine/tools/cache_on_disk.py +26 -0
  51. capytaine/tools/deprecation_handling.py +18 -0
  52. capytaine/tools/lists_of_points.py +52 -0
  53. capytaine/tools/memory_monitor.py +45 -0
  54. capytaine/tools/optional_imports.py +27 -0
  55. capytaine/tools/prony_decomposition.py +150 -0
  56. capytaine/tools/symbolic_multiplication.py +161 -0
  57. capytaine/tools/timer.py +90 -0
  58. capytaine/ui/__init__.py +0 -0
  59. capytaine/ui/cli.py +28 -0
  60. capytaine/ui/rich.py +5 -0
  61. capytaine-3.0.0a1.dist-info/LICENSE +674 -0
  62. capytaine-3.0.0a1.dist-info/METADATA +755 -0
  63. capytaine-3.0.0a1.dist-info/RECORD +65 -0
  64. capytaine-3.0.0a1.dist-info/WHEEL +4 -0
  65. capytaine-3.0.0a1.dist-info/entry_points.txt +3 -0
capytaine/io/xarray.py ADDED
@@ -0,0 +1,673 @@
1
+ """Tools to use xarray Datasets as inputs and outputs.
2
+
3
+ .. todo:: This module could be tidied up a bit and some methods merged or
4
+ uniformized.
5
+ """
6
+ # Copyright (C) 2017-2025 Matthieu Ancellin
7
+ # See LICENSE file at <https://github.com/capytaine/capytaine>
8
+
9
+ import logging
10
+ from datetime import datetime
11
+ from itertools import product
12
+ from collections import Counter
13
+ from typing import Sequence, List, Union
14
+ from pathlib import Path
15
+
16
+ import numpy as np
17
+ import pandas as pd
18
+ import xarray as xr
19
+
20
+ from capytaine import __version__
21
+ from capytaine.bodies.bodies import FloatingBody
22
+ from capytaine.bodies.multibodies import Multibody
23
+ from capytaine.bem.problems_and_results import (
24
+ LinearPotentialFlowProblem, DiffractionProblem, RadiationProblem,
25
+ LinearPotentialFlowResult, _default_parameters)
26
+ from capytaine.post_pro.kochin import compute_kochin
27
+ from capytaine.io.bemio import dataframe_from_bemio
28
+
29
+
30
+ LOG = logging.getLogger(__name__)
31
+
32
+
33
+ #########################
34
+ # Reading test matrix #
35
+ #########################
36
+
37
+ def _unsqueeze_dimensions(data_array, dimensions=None):
38
+ """Add scalar coordinates as dimensions of size 1."""
39
+ if dimensions is None:
40
+ dimensions = list(data_array.coords.keys())
41
+ for dim in dimensions:
42
+ if len(data_array.coords[dim].values.shape) == 0:
43
+ data_array = xr.concat([data_array], dim=dim)
44
+ return data_array
45
+
46
+
47
+ def problems_from_dataset(dataset: xr.Dataset,
48
+ bodies: Union[FloatingBody, Sequence[FloatingBody], Multibody, Sequence[Multibody]],
49
+ ) -> List[LinearPotentialFlowProblem]:
50
+ """Generate a list of problems from a test matrix.
51
+
52
+ Parameters
53
+ ----------
54
+ dataset : xarray Dataset
55
+ Test matrix containing the problems parameters.
56
+ bodies : FloatingBody or list of FloatingBody
57
+ The bodies on which the computations of the test matrix will be applied.
58
+ They should all have different names.
59
+
60
+ Returns
61
+ -------
62
+ list of LinearPotentialFlowProblem
63
+
64
+ Raises
65
+ ------
66
+ ValueError
67
+ if required fields are missing in the dataset
68
+ """
69
+ if isinstance(bodies, (FloatingBody, Multibody)):
70
+ bodies = [bodies]
71
+
72
+ # Should be done before looking for `frequency_keys`, otherwise
73
+ # frequencies provided as a scalar dimension will be skipped.
74
+ dataset = _unsqueeze_dimensions(dataset)
75
+
76
+ # SANITY CHECKS
77
+ assert len(list(set(body.name for body in bodies))) == len(bodies), \
78
+ "All bodies should have different names."
79
+
80
+ # Warn user in case of key with unrecognized name (e.g. misspells)
81
+ keys_in_dataset = set(dataset.dims)
82
+ accepted_keys = {'wave_direction', 'radiating_dof', 'influenced_dof',
83
+ 'body_name', 'omega', 'freq', 'period', 'wavelength', 'wavenumber',
84
+ 'forward_speed', 'water_depth', 'rho', 'g', 'theta'}
85
+ unrecognized_keys = keys_in_dataset.difference(accepted_keys)
86
+ if len(unrecognized_keys) > 0:
87
+ LOG.warning(f"Unrecognized key(s) in dataset: {unrecognized_keys}")
88
+
89
+ if ("radiating_dof" not in keys_in_dataset) and ("wave_direction" not in keys_in_dataset):
90
+ raise ValueError("Neither 'radiating_dof' nor 'wave_direction' has been provided in the dataset. "
91
+ "No linear potential flow problem can be inferred.")
92
+
93
+ frequency_keys = keys_in_dataset & {'omega', 'freq', 'period', 'wavelength', 'wavenumber'}
94
+ if len(frequency_keys) > 1:
95
+ raise ValueError("Setting problems requires at most one of the following: omega (angular frequency) OR freq (in Hz) OR period OR wavenumber OR wavelength.\n"
96
+ "Received {}".format(frequency_keys))
97
+ # END SANITY CHECKS
98
+
99
+ if len(frequency_keys) == 0:
100
+ freq_type = "omega"
101
+ freq_range = [_default_parameters['omega']]
102
+ else: # len(frequency_keys) == 1
103
+ freq_type = list(frequency_keys)[0] # Get the only item
104
+ freq_range = dataset[freq_type].data
105
+
106
+ water_depth_range = dataset['water_depth'].data if 'water_depth' in dataset else [_default_parameters['water_depth']]
107
+ rho_range = dataset['rho'].data if 'rho' in dataset else [_default_parameters['rho']]
108
+ g_range = dataset['g'].data if 'g' in dataset else [_default_parameters['g']]
109
+ forward_speed_range = dataset['forward_speed'] if 'forward_speed' in dataset else [_default_parameters['forward_speed']]
110
+
111
+ wave_direction_range = dataset['wave_direction'].data if 'wave_direction' in dataset else None
112
+ radiating_dofs = dataset['radiating_dof'].data.astype(object) if 'radiating_dof' in dataset else None
113
+ # astype(object) is meant to convert Numpy internal string type numpy.str_ to Python general string type.
114
+
115
+ if 'body_name' in dataset:
116
+ assert set(dataset['body_name'].data) <= {body.name for body in bodies}, \
117
+ "Some body named in the dataset was not given as argument to `problems_from_dataset`."
118
+ body_range = {body.name: body for body in bodies if body.name in dataset['body_name'].data}
119
+ # Only the bodies listed in the dataset have been kept
120
+ else:
121
+ body_range = {body.name: body for body in bodies}
122
+
123
+ problems = []
124
+ if wave_direction_range is not None:
125
+ for freq, wave_direction, water_depth, body_name, forward_speed, rho, g \
126
+ in product(freq_range, wave_direction_range, water_depth_range, body_range,
127
+ forward_speed_range, rho_range, g_range):
128
+ problems.append(
129
+ DiffractionProblem(body=body_range[body_name], **{freq_type: freq},
130
+ wave_direction=wave_direction, water_depth=water_depth,
131
+ forward_speed=forward_speed, rho=rho, g=g)
132
+ )
133
+
134
+ if radiating_dofs is not None:
135
+ for freq, radiating_dof, water_depth, body_name, forward_speed, rho, g \
136
+ in product(freq_range, radiating_dofs, water_depth_range, body_range, forward_speed_range, rho_range, g_range):
137
+ if forward_speed == 0.0:
138
+ problems.append(
139
+ RadiationProblem(body=body_range[body_name], **{freq_type: freq},
140
+ radiating_dof=radiating_dof, water_depth=water_depth,
141
+ forward_speed=forward_speed, rho=rho, g=g)
142
+ )
143
+ else:
144
+ if wave_direction_range is None:
145
+ LOG.warning("Dataset contains non-zero forward speed (forward_speed=%.2f) but no wave_direction has been provided. Wave direction of 0 rad (x-axis) has been assumed.", forward_speed)
146
+ wave_direction_range = [0.0]
147
+ for wave_direction in wave_direction_range:
148
+ problems.append(
149
+ RadiationProblem(body=body_range[body_name], **{freq_type: freq},
150
+ radiating_dof=radiating_dof, water_depth=water_depth,
151
+ forward_speed=forward_speed, wave_direction=wave_direction,
152
+ rho=rho, g=g)
153
+ )
154
+
155
+ return sorted(problems)
156
+
157
+
158
+ ########################
159
+ # Dataframe creation #
160
+ ########################
161
+
162
+ def _detect_bemio_results(results, calling_function="_detect_bemio_results"):
163
+ error_msg = (
164
+ f"The function {calling_function} expected either a non-empty list of LinearPotentialFlowResult or a bemio.io object.\n"
165
+ f"Instead, it received:\n{repr(results)}"
166
+ )
167
+
168
+ if hasattr(results, '__iter__'):
169
+ if len(results) == 0:
170
+ raise ValueError("Iterable provided to `assemble_dataset` is empty.")
171
+ try:
172
+ if 'capytaine' in results[0].__module__:
173
+ bemio_import = False
174
+ else:
175
+ raise TypeError(error_msg)
176
+ except:
177
+ raise TypeError(error_msg)
178
+
179
+ else:
180
+ try:
181
+ if 'bemio.io' in results.__module__:
182
+ bemio_import = True
183
+ else:
184
+ raise TypeError(error_msg)
185
+ except:
186
+ raise TypeError(error_msg)
187
+
188
+ return bemio_import
189
+
190
+
191
+ def assemble_dataframe(results, wavenumber=True, wavelength=True):
192
+ if _detect_bemio_results(results, calling_function="assemble_dataframe"):
193
+ return dataframe_from_bemio(results, wavenumber, wavelength) # TODO add hydrostatics
194
+
195
+ records_list = [record for result in results for record in result.records]
196
+ df = pd.DataFrame(records_list)
197
+
198
+ all_dofs_in_order = list({k: None for r in results for k in r.body.dofs.keys()})
199
+ # Using a dict above to remove duplicates while conserving ordering
200
+ inf_dof_cat = pd.CategoricalDtype(categories=all_dofs_in_order)
201
+ df["influenced_dof"] = df["influenced_dof"].astype(inf_dof_cat)
202
+ if 'added_mass' in df.columns:
203
+ rad_dof_cat = pd.CategoricalDtype(categories=all_dofs_in_order)
204
+ df["radiating_dof"] = df["radiating_dof"].astype(rad_dof_cat)
205
+
206
+ return df
207
+
208
+
209
+ ######################
210
+ # Dataset creation #
211
+ ######################
212
+
213
+ def _squeeze_dimensions(data_array, dimensions=None):
214
+ """Remove dimensions if they are of size 1. The coordinates become scalar coordinates."""
215
+ if dimensions is None:
216
+ dimensions = data_array.dims
217
+ for dim in dimensions:
218
+ if len(data_array[dim]) == 1:
219
+ data_array = data_array.squeeze(dim, drop=False)
220
+ return data_array
221
+
222
+
223
+ def _dataset_from_dataframe(df: pd.DataFrame,
224
+ variables: Union[str, Sequence[str]],
225
+ dimensions: Sequence[str],
226
+ optional_dims: Sequence[str],
227
+ ) -> Union[xr.DataArray, xr.Dataset]:
228
+ """Transform a pandas.Dataframe into a xarray.Dataset.
229
+
230
+ Parameters
231
+ ----------
232
+ df: pandas.DataFrame
233
+ the input dataframe
234
+ variables: string or sequence of strings
235
+ the variables that will be stored in the output dataset.
236
+ If a single name is provided, a DataArray of this variable will be provided instead.
237
+ dimensions: sequence of strings
238
+ Names of dimensions the variables depends on.
239
+ They will always appear as dimension in the output dataset.
240
+ optional_dims: sequence of strings
241
+ Names of dimensions the variables depends on.
242
+ They will appears as dimension in the output dataset only if they have
243
+ more than one different values.
244
+ """
245
+ df = df.drop_duplicates(optional_dims + dimensions)
246
+ df = df.set_index(optional_dims + dimensions)
247
+ da = df.to_xarray()[variables]
248
+ da = _squeeze_dimensions(da, dimensions=optional_dims)
249
+ return da
250
+
251
+
252
+ def hydrostatics_dataset(bodies: Sequence[FloatingBody]) -> xr.Dataset:
253
+ """Create a dataset by looking for 'inertia_matrix' and 'hydrostatic_stiffness'
254
+ for each of the bodies in the list passed as argument.
255
+ """
256
+ dataset = xr.Dataset()
257
+ for body_property in ['inertia_matrix', 'hydrostatic_stiffness']:
258
+ bodies_properties = {body.name: body.__getattribute__(body_property) for body in bodies if hasattr(body, body_property)}
259
+ if len(bodies_properties) > 0:
260
+ bodies_properties = xr.concat(bodies_properties.values(), pd.Index(bodies_properties.keys(), name='body_name'))
261
+ bodies_properties = _squeeze_dimensions(bodies_properties, dimensions=['body_name'])
262
+ dataset = xr.merge([dataset, {body_property: bodies_properties}], compat="no_conflicts", join="outer")
263
+ return dataset
264
+
265
+
266
+ def kochin_data_array(results: Sequence[LinearPotentialFlowResult],
267
+ theta_range: Sequence[float],
268
+ **kwargs,
269
+ ) -> xr.Dataset:
270
+ """Compute the Kochin function for a list of results and fills a dataset.
271
+
272
+ .. seealso::
273
+ :meth:`~capytaine.post_pro.kochin.compute_kochin`
274
+ The present function is just a wrapper around :code:`compute_kochin`.
275
+ """
276
+ # TODO: this not very good to mix computation and data manipulation here...
277
+ records = pd.DataFrame([
278
+ dict(**result.problem._asdict(), theta=theta, kochin=kochin, kind=result.__class__.__name__)
279
+ for result in results
280
+ for theta, kochin in zip(theta_range.data,
281
+ compute_kochin(result, theta_range, **kwargs))
282
+ ])
283
+
284
+ main_freq_type = Counter((res.provided_freq_type for res in results)).most_common(1)[0][0]
285
+
286
+ kochin_data = xr.Dataset()
287
+
288
+ if "RadiationResult" in set(records['kind']):
289
+ radiation = _dataset_from_dataframe(
290
+ records[records['kind'] == "RadiationResult"],
291
+ variables=['kochin'],
292
+ dimensions=[main_freq_type, 'radiating_dof', 'theta'],
293
+ optional_dims=['g', 'rho', 'body_name', 'water_depth', 'forward_speed', 'wave_direction']
294
+ )
295
+ kochin_data['kochin_radiation'] = radiation['kochin']
296
+
297
+ if "DiffractionResult" in set(records['kind']):
298
+ diffraction = _dataset_from_dataframe(
299
+ records[records['kind'] == "DiffractionResult"],
300
+ ['kochin'],
301
+ dimensions=[main_freq_type, 'wave_direction', 'theta'],
302
+ optional_dims=['g', 'rho', 'body_name', 'water_depth', 'forward_speed']
303
+ )
304
+ kochin_data['kochin_diffraction'] = diffraction['kochin']
305
+
306
+ return kochin_data
307
+
308
+ VARIABLES_ATTRIBUTES = {
309
+ "omega": {
310
+ 'long_name': 'Angular frequency',
311
+ 'units': 'rad/s',
312
+ },
313
+ "freq": {
314
+ 'long_name': 'Frequency',
315
+ 'units': 'Hz',
316
+ },
317
+ "period": {
318
+ 'long_name': 'Period',
319
+ 'units': 's',
320
+ },
321
+ "wavenumber": {
322
+ 'long_name': "Angular wavenumber",
323
+ 'units': 'rad/m',
324
+ },
325
+ "wavelength": {
326
+ 'long_name': "Wave length",
327
+ 'units': 'm',
328
+ },
329
+ "encounter_omega": {
330
+ 'long_name': "Encounter angular frequency",
331
+ 'units': 'rad/s',
332
+ },
333
+ "encounter_wave_direction": {
334
+ 'long_name': "Encounter wave direction",
335
+ 'units': 'rad',
336
+ },
337
+ "wave_direction": {
338
+ 'long_name': "Wave direction",
339
+ 'units': "rad"
340
+ },
341
+ "radiating_dof": {
342
+ 'long_name': 'Radiating DOF',
343
+ },
344
+ "influenced_dof": {
345
+ 'long_name': 'Influenced DOF',
346
+ },
347
+ "added_mass": {
348
+ 'long_name': 'Added mass',
349
+ },
350
+ "radiation_damping": {
351
+ 'long_name': 'Radiation damping',
352
+ },
353
+ "diffraction_force": {
354
+ 'long_name': "Diffraction force",
355
+ },
356
+ "Froude_Krylov_force": {
357
+ 'long_name': "Froude Krylov force",
358
+ },
359
+ }
360
+
361
+ def assemble_dataset(results,
362
+ omega=True, freq=True, wavenumber=True, wavelength=True, period=True,
363
+ mesh=False, hydrostatics=True, attrs=None) -> xr.Dataset:
364
+ """Transform a list of :class:`LinearPotentialFlowResult` into a :class:`xarray.Dataset`.
365
+
366
+ .. todo:: The :code:`mesh` option to store information on the mesh could be improved.
367
+ It could store the full mesh in the dataset to ensure the reproducibility of
368
+ the results.
369
+
370
+ Parameters
371
+ ----------
372
+ results: list of LinearPotentialFlowResult or BEMIO dataset
373
+ The results that will be read.
374
+ omega: bool, optional
375
+ If True, the coordinate 'omega' will be added to the output dataset.
376
+ freq: bool, optional
377
+ If True, the coordinate 'freq' will be added to the output dataset.
378
+ wavenumber: bool, optional
379
+ If True, the coordinate 'wavenumber' will be added to the output dataset.
380
+ wavelength: bool, optional
381
+ If True, the coordinate 'wavelength' will be added to the output dataset.
382
+ period: bool, optional
383
+ If True, the coordinate 'period' will be added to the output dataset.
384
+ mesh: bool, optional
385
+ If True, store some infos on the mesh in the output dataset.
386
+ hydrostatics: bool, optional
387
+ If True, store the hydrostatic data in the output dataset if they exist.
388
+ attrs: dict, optional
389
+ Attributes that should be added to the output dataset.
390
+ """
391
+ bemio_import = _detect_bemio_results(results, calling_function="assemble_dataset")
392
+
393
+ records = assemble_dataframe(results)
394
+
395
+ if bemio_import:
396
+ main_freq_type = "omega"
397
+ else:
398
+ main_freq_type = Counter((res.provided_freq_type for res in results)).most_common(1)[0][0]
399
+
400
+ if np.any(records["free_surface"] != 0.0):
401
+ LOG.warning("Datasets only support cases with a free surface (free_surface=0.0).\n"
402
+ "Cases without a free surface (free_surface=inf) are ignored.\n"
403
+ "See also https://github.com/mancellin/capytaine/issues/88")
404
+ records = records[records["free_surface"] == 0.0]
405
+
406
+ if attrs is None:
407
+ attrs = {}
408
+ attrs['creation_of_dataset'] = datetime.now().isoformat()
409
+
410
+ kinds_of_results = set(records['kind'])
411
+
412
+ optional_dims = ['g', 'rho', 'body_name', 'water_depth', 'forward_speed']
413
+
414
+ dataset = xr.Dataset()
415
+
416
+ # RADIATION RESULTS
417
+ if "RadiationResult" in kinds_of_results:
418
+ radiation_cases = _dataset_from_dataframe(
419
+ records[records['kind'] == "RadiationResult"],
420
+ variables=['added_mass', 'radiation_damping'],
421
+ dimensions=[main_freq_type, 'radiating_dof', 'influenced_dof'],
422
+ optional_dims=optional_dims + ['wave_direction'])
423
+ dataset = xr.merge([dataset, radiation_cases], compat="no_conflicts", join="outer")
424
+
425
+ # DIFFRACTION RESULTS
426
+ if "DiffractionResult" in kinds_of_results:
427
+ diffraction_cases = _dataset_from_dataframe(
428
+ records[records['kind'] == "DiffractionResult"],
429
+ variables=['diffraction_force', 'Froude_Krylov_force'],
430
+ dimensions=[main_freq_type, 'wave_direction', 'influenced_dof'],
431
+ optional_dims=optional_dims)
432
+ dataset = xr.merge([dataset, diffraction_cases], compat="no_conflicts", join="outer")
433
+ dataset['excitation_force'] = dataset['Froude_Krylov_force'] + dataset['diffraction_force']
434
+
435
+ # OTHER FREQUENCIES TYPES
436
+ if omega and main_freq_type != "omega":
437
+ omega_ds = _dataset_from_dataframe(
438
+ records,
439
+ variables=['omega'],
440
+ dimensions=[main_freq_type],
441
+ optional_dims=['g', 'water_depth'] if main_freq_type in {'wavelength', 'wavenumber'} else []
442
+ )
443
+ dataset.coords['omega'] = omega_ds['omega']
444
+
445
+ if freq and main_freq_type != "freq":
446
+ freq_ds = _dataset_from_dataframe(
447
+ records,
448
+ variables=['freq'],
449
+ dimensions=[main_freq_type],
450
+ optional_dims=['g', 'water_depth'] if main_freq_type in {'wavelength', 'wavenumber'} else []
451
+ )
452
+ dataset.coords['freq'] = freq_ds['freq']
453
+
454
+ if period and main_freq_type != "period":
455
+ period_ds = _dataset_from_dataframe(
456
+ records,
457
+ variables=['period'],
458
+ dimensions=[main_freq_type],
459
+ optional_dims=['g', 'water_depth'] if main_freq_type in {'wavelength', 'wavenumber'} else []
460
+ )
461
+ dataset.coords['period'] = period_ds['period']
462
+
463
+ if wavenumber and main_freq_type != "wavenumber":
464
+ wavenumber_ds = _dataset_from_dataframe(
465
+ records,
466
+ variables=['wavenumber'],
467
+ dimensions=[main_freq_type],
468
+ optional_dims=['g', 'water_depth'] if main_freq_type in {'period', 'omega'} else []
469
+ )
470
+ dataset.coords['wavenumber'] = wavenumber_ds['wavenumber']
471
+
472
+ if wavelength and main_freq_type != "wavelength":
473
+ wavelength_ds = _dataset_from_dataframe(
474
+ records,
475
+ variables=['wavelength'],
476
+ dimensions=[main_freq_type],
477
+ optional_dims=['g', 'water_depth'] if main_freq_type in {'period', 'omega'} else []
478
+ )
479
+ dataset.coords['wavelength'] = wavelength_ds['wavelength']
480
+
481
+ if not all(records["forward_speed"] == 0.0):
482
+ omegae_ds = _dataset_from_dataframe(
483
+ records,
484
+ variables=['encounter_omega'],
485
+ dimensions=['forward_speed', 'wave_direction', main_freq_type],
486
+ optional_dims=['g', 'water_depth'],
487
+ )
488
+ dataset.coords['encounter_omega'] = omegae_ds['encounter_omega']
489
+
490
+ encounter_wave_direction_ds = _dataset_from_dataframe(
491
+ records,
492
+ variables=['encounter_wave_direction'],
493
+ dimensions=['forward_speed', 'wave_direction', main_freq_type],
494
+ optional_dims=[],
495
+ )
496
+ dataset.coords['encounter_wave_direction'] = encounter_wave_direction_ds['encounter_wave_direction']
497
+
498
+ if mesh:
499
+ if bemio_import:
500
+ LOG.warning('Bemio data does not include mesh data. mesh=True is ignored.')
501
+ else:
502
+ # TODO: Store full mesh...
503
+ bodies = list({result.body for result in results}) # Filter out duplicate bodies in the list of results
504
+ nb_faces = {body.name: body.mesh.nb_faces for body in bodies}
505
+
506
+ def name_or_str(c):
507
+ return c.name if hasattr(c, 'name') else str(c)
508
+ quad_methods = {body.name: name_or_str(body.mesh.quadrature_method) for body in bodies}
509
+
510
+ if len(nb_faces) > 1:
511
+ dataset.coords['nb_faces'] = ('body_name', [nb_faces[name] for name in dataset.coords['body_name'].data])
512
+ dataset.coords['quadrature_method'] = ('body_name', [quad_methods[name] for name in dataset.coords['body_name'].data])
513
+ else:
514
+ def the_only(d):
515
+ """Return the only element of a 1-element dictionary"""
516
+ return next(iter(d.values()))
517
+ dataset.coords['nb_faces'] = the_only(nb_faces)
518
+ dataset.coords['quadrature_method'] = the_only(quad_methods)
519
+
520
+ # HYDROSTATICS
521
+ if hydrostatics:
522
+ if bemio_import:
523
+ LOG.warning('Bemio data import being used, hydrostatics=True is ignored.')
524
+ else:
525
+ bodies = list({result.body for result in results})
526
+ dataset = xr.merge([dataset, hydrostatics_dataset(bodies)], compat="no_conflicts", join="outer")
527
+
528
+ for var in set(dataset) | set(dataset.coords):
529
+ if var in VARIABLES_ATTRIBUTES:
530
+ dataset[var].attrs.update(VARIABLES_ATTRIBUTES[var])
531
+
532
+ dataset.attrs.update(attrs)
533
+ dataset.attrs['capytaine_version'] = __version__
534
+ return dataset
535
+
536
+
537
+ def assemble_matrices(results):
538
+ """Simplified version of assemble_dataset, returning only bare matrices.
539
+ Meant mainly for teaching without introducing Xarray to beginners.
540
+
541
+ Parameters
542
+ ----------
543
+ results: list of LinearPotentialFlowResult
544
+ The results that will be read.
545
+
546
+ Returns
547
+ -------
548
+ 3-ple of (np.arrays or None)
549
+ The added mass matrix, the radiation damping matrix and the excitation force.
550
+ If the data are no available in the results, returns None instead.
551
+ """
552
+
553
+ ds = assemble_dataset(results)
554
+
555
+ if "added_mass" in ds:
556
+ A = np.atleast_2d(ds.added_mass.values.squeeze())
557
+ else:
558
+ A = None
559
+
560
+ if "radiation_damping" in ds:
561
+ B = np.atleast_2d(ds.radiation_damping.values.squeeze())
562
+ else:
563
+ B = None
564
+
565
+ if "excitation_force" in ds:
566
+ F = np.atleast_1d(ds.excitation_force.values.squeeze())
567
+ else:
568
+ F = None
569
+
570
+ return A, B, F
571
+
572
+
573
+
574
+ ################################
575
+ # Handling of complex values #
576
+ ################################
577
+
578
+ def separate_complex_values(ds: xr.Dataset) -> xr.Dataset:
579
+ """Return a new Dataset where complex-valued arrays of shape (...)
580
+ have been replaced by real-valued arrays of shape (2, ...).
581
+
582
+ .. seealso::
583
+ :func:`merge_complex_values`
584
+ The invert operation
585
+ """
586
+ ds = ds.copy()
587
+ for variable in ds.data_vars:
588
+ if ds[variable].dtype == complex:
589
+ da = ds[variable]
590
+ new_da = xr.DataArray(np.asarray((np.real(da).data, np.imag(da).data)),
591
+ dims=('complex',) + da.dims)
592
+ ds[variable] = new_da
593
+ ds.coords['complex'] = ['re', 'im']
594
+ return ds
595
+
596
+
597
+ def merge_complex_values(ds: xr.Dataset) -> xr.Dataset:
598
+ """Return a new Dataset where real-valued arrays of shape (2, ...)
599
+ have been replaced by complex-valued arrays of shape (...).
600
+
601
+ .. seealso::
602
+ :func:`separate_complex_values`
603
+ The invert operation
604
+ """
605
+ if 'complex' in ds.coords:
606
+ ds = ds.copy()
607
+ for variable in ds.data_vars:
608
+ if 'complex' in ds[variable].coords:
609
+ da = ds[variable]
610
+ new_dims = [d for d in da.dims if d != 'complex']
611
+ new_da = xr.DataArray(da.sel(complex='re').data + 1j*da.sel(complex='im').data, dims=new_dims)
612
+ ds[variable] = new_da
613
+ ds = ds.drop_vars('complex')
614
+ return ds
615
+
616
+
617
+ ##################
618
+ # Save dataset #
619
+ ##################
620
+
621
+ def save_dataset_as_netcdf(filename, dataset):
622
+ """Save `dataset` as a NetCDF file with name (or path) `filename`"""
623
+ ds = separate_complex_values(dataset)
624
+
625
+ # Workaround https://github.com/capytaine/capytaine/issues/683
626
+ ds['radiating_dof'] = ds['radiating_dof'].astype('str')
627
+ ds['influenced_dof'] = ds['influenced_dof'].astype('str')
628
+
629
+ # Make sure all strings are exported as strings and not Python objects
630
+ encoding = {'radiating_dof': {'dtype': 'U'},
631
+ 'influenced_dof': {'dtype': 'U'}}
632
+
633
+ ds.to_netcdf(filename, encoding=encoding)
634
+
635
+
636
+ def export_dataset(filename, dataset, format=None, **kwargs):
637
+ """Save `dataset` into a format, provided by the `format` argument or inferred by the `filename`.
638
+
639
+ Parameters
640
+ ----------
641
+ filename: str or Path
642
+ Where to store the data
643
+ dataset: xarray.Dataset
644
+ Dataset, which is assumed to have been computed by Capytaine
645
+ format: str, optional
646
+ Format of output. Accepted values: "netcdf"
647
+ **kwargs: optional
648
+ Remaining argument are passed to the specific export function,
649
+ such as ``save_dataset_as_netcdf``, ``export_to_wamit`` or ``write_dataset_as_tecplot_files``.
650
+
651
+ Returns
652
+ -------
653
+ None
654
+ """
655
+ if (
656
+ (format is not None and format.lower() == "netcdf") or
657
+ (format is None and str(filename).endswith(".nc"))
658
+ ):
659
+ save_dataset_as_netcdf(filename, dataset, **kwargs)
660
+ elif (
661
+ (format is not None and format.lower() == "wamit")
662
+ ):
663
+ from capytaine.io.wamit import export_to_wamit
664
+ export_to_wamit(dataset, filename, **kwargs)
665
+ elif (
666
+ (format is not None and format.lower() == "nemoh")
667
+ ):
668
+ from capytaine.io.legacy import write_dataset_as_tecplot_files
669
+ Path(filename).mkdir(exist_ok=True)
670
+ write_dataset_as_tecplot_files(filename, dataset, **kwargs)
671
+ else:
672
+ raise ValueError("`export_dataset` could not infer export format based on filename or `format` argument.\n"
673
+ f"provided filename: {filename}\nprovided format: {format}")
@@ -0,0 +1,2 @@
1
+ from .meshes import Mesh
2
+ from .symmetric_meshes import ReflectionSymmetricMesh, RotationSymmetricMesh