Exemple #1
0
def test_resolution():
    cylinder = cpt.HorizontalCylinder(
        length=5.0,
        radius=1.0,
        center=(0, 0, -2),
        nr=2,
        nx=10,
        ntheta=5,
    )
    # cylinder.show()
    cylinder.add_translation_dof(name="Heave")

    test_matrix = xr.Dataset(coords={
        "omega": np.linspace(0.5, 3.0, 2),
        "radiating_dof": ["Heave"],
    })

    solver = cpt.BEMSolver()

    cylinder.mesh.compute_quadrature(quadpy.quadrilateral.sommariva_01())
    data_1 = solver.fill_dataset(test_matrix, [cylinder], mesh=True)

    cylinder.mesh.compute_quadrature(quadpy.quadrilateral.sommariva_03())
    data_3 = solver.fill_dataset(test_matrix, [cylinder], mesh=True)

    assert data_1['quadrature_method'] == "Sommariva 1"
    assert data_3['quadrature_method'] == "Sommariva 3"
    assert np.allclose(data_1["added_mass"].data,
                       data_3["added_mass"].data,
                       rtol=1e-2)
Exemple #2
0
def make_cylinder(resolution):
    """Make cylinder with a mesh of a given resolution in panels/meter."""
    radius = 1.0
    length = 5.0
    body = cpt.HorizontalCylinder(
        length=length, radius=radius,
        center=(0, 0, -1.5*radius),
        nr=int(resolution*radius),
        nx=int(length*resolution),
        ntheta=int(2*pi*length*resolution),
    )
    # Store the number of panels in the name of the body
    body.name = f"cylinder_{body.mesh.nb_faces:04d}"
    body.add_translation_dof(name="Heave")
    return body
Exemple #3
0
    def generate_tube(self):
        """Generates an elastic tube mesh with all attached rigid body and modal degrees of freedom

        Args:
            None

        Returns:
            tube (an instance of a Capytaine FloatingBody)

        """
        #print('\tGenerating tube.')
        tube = cpt.HorizontalCylinder(radius=self.static_radius,
                                      length=self.length,
                                      center=(0, 0, self.submergence),
                                      nx=int(1.50 * self.length),
                                      ntheta=25,
                                      nr=int(5 * self.static_radius),
                                      clever=False)
        tube.keep_immersed_part()
        # Mesh convergence test
        # length: 0.5, 0.8, 1.0, 1.25, 1.50  # ntheta: 10, 15, 20, 20, 25  # nr: 2, 3, 4, 5, 5
        # Final result: nx=int(1.25*self.length), ntheta=20, nr=int(5*self.static_radius), clever=False

        # Add all elastic mode DOFs
        for k in range(self.mode_count):
            key_name = 'Bulge Mode ' + str(k)
            tube.dofs[key_name] = np.array([
                self.mode_shape_derivatives(x, y, z, mode_number=k)
                for x, y, z in tube.mesh.faces_centers
            ])

        modal_mass_matrix = self.total_mass * np.eye(N=self.mode_count)
        modal_stiffness_matrix = np.diag(self.total_mass *
                                         (self.mode_frequency_list**2))

        tube.mass = tube.add_dofs_labels_to_matrix(modal_mass_matrix)
        tube.hydrostatic_stiffness = tube.add_dofs_labels_to_matrix(
            modal_stiffness_matrix)

        self.tube = tube

        self.dissipation = tube.add_dofs_labels_to_matrix(
            self.damping_matrix())
def test_showmatplotlib_with_colors(tmp_path):
    cylinder = cpt.HorizontalCylinder(
        length=5.0, radius=1.0, center=(0, 0, -2), nr=5, nx=20, ntheta=20,
    )

    problem = cpt.DiffractionProblem(body=cylinder, wave_direction=0.0, omega=1.0)
    solver = cpt.BEMSolver()
    results = solver.solve(problem)

    cylinder.show_matplotlib(saveas=tmp_path / "showmpl.png")

    fig = plt.figure()
    ax = fig.add_subplot(111,projection='3d')
    import matplotlib.cm as cm
    colormap = cm.get_cmap('cividis')
    cylinder.show_matplotlib(color_field=np.abs(results.potential),
                             ax=ax, cbar_label=r'$\phi (m^2/s)$')
    ax.set_title('Potential distribution')
    plt.savefig(tmp_path / "showmpl_with_color_field.png")
Exemple #5
0
def test_vertical_elastic_dof():

    bodies = [
        cpt.VerticalCylinder(
            length=10.0, radius=5.0,
            center=(0.0,0.0,0.0),
            nr=100, nx=100, ntheta=100,
        ),

        cpt.Sphere(
            radius=100,
            center=(0,0,0),
            nphi=50, ntheta=50,
        ),

        cpt.HorizontalCylinder(
            length=5.0, radius=1.0,
            center=(0,10,0),
            nr=20, nx=20, ntheta=10,
        )
    ]

    for body in bodies:
        body.center_of_mass = body.center_of_buoyancy
        body.keep_immersed_part()
        faces_centers = body.mesh.faces_centers
        body.dofs["elongate"] = np.zeros_like(faces_centers)
        body.dofs["elongate"][:,2] = faces_centers[:,2]

        divergence = np.ones(body.mesh.faces_centers.shape[0])

        density = 1000
        gravity = 9.80665
        capy_hs = body.each_hydrostatic_stiffness("elongate", "elongate",
                    influenced_dof_div=divergence, rho=density, g=gravity).values[0][0]

        analytical_hs = - (density * gravity * 4 * body.volume
                        * body.center_of_buoyancy[2])

        assert np.isclose(capy_hs, analytical_hs)
Exemple #6
0
def test_all_hydrostatics():
    density = 1000
    gravity = 9.80665

    sphere = cpt.Sphere(
        radius=10.0,
        center=(0,0,-1),
        nphi=100, ntheta=50,
    )
    horizontal_cylinder = cpt.HorizontalCylinder(
        length=10.0, radius=5.0,
        center=(0,10,-1),
        nr=100, nx=100, ntheta=10,
    )
    vertical_cylinder = cpt.VerticalCylinder(
        length=10.0, radius=5.0,
        center=(10,0,0),
        nr=200, nx=200, ntheta=10,
    )
    body = sphere + horizontal_cylinder + vertical_cylinder
    body.add_all_rigid_body_dofs()
    body.center_of_mass = body.center_of_buoyancy

    capy_hsdb = body.compute_hydrostatics(rho=density, g=gravity)

    stiff_compare_dofs = ["Heave", "Roll", "Pitch"]
    capy_hsdb["stiffness_matrix"] = capy_hsdb["hydrostatic_stiffness"].sel(
        influenced_dof=stiff_compare_dofs, radiating_dof=stiff_compare_dofs
        ).values

    mass_compare_dofs = ["Roll", "Pitch", "Yaw"]
    capy_hsdb["inertia_matrix"] = capy_hsdb["inertia_matrix"].sel(
        influenced_dof=mass_compare_dofs, radiating_dof=mass_compare_dofs
        ).values


    # =============================================================================
    # Meshmagick
    # =============================================================================
    case_dir = Path(__file__).parent / "Hydrostatics_cases"
    # case_dir.mkdir(parents=True, exist_ok=True)
    # import meshmagick.mesh as mmm
    # import meshmagick.hydrostatics as mmhs
    # body_mesh = mmm.Mesh(body.mesh.vertices, body.mesh.faces, name=body.mesh.name)
    # mm_hsdb = mmhs.compute_hydrostatics(body_mesh, body.center_of_mass, density, gravity)
    # mm_hsdb["inertia_matrix"] = body_mesh.eval_plain_mesh_inertias(
    # rho_medium=density).inertia_matrix
    # mm_hsdb["mesh"] = ""
    # with open(f'{case_dir}/sphere__hor_cyl__ver_cyl.pkl.json', 'w') as convert_file:
    #     mm_hsdb_json = {key:(value.tolist() if type(value)==np.ndarray else value)
    #                         for key, value in mm_hsdb.items() }
    #     convert_file.write(json.dumps(mm_hsdb_json))

    with open(f'{case_dir}/sphere__hor_cyl__ver_cyl.pkl.json', 'r',
              encoding="UTF-8") as f:
        mm_hsdb = json.load(f)

    # =============================================================================
    # Testing
    # =============================================================================

    for var in capy_hsdb.keys():
        if var in mm_hsdb.keys():
            # if not np.isclose(capy_hsdb[var], mm_hsdb[var],
            #                   rtol=1e-2, atol=1e-3).all():
            #     print(f"{var}:")
            #     print(f"    Capytaine  - {capy_hsdb[var]}")
            #     print(f"    Meshmagick - {mm_hsdb[var]}")
            assert np.isclose(capy_hsdb[var], mm_hsdb[var],
                              rtol=1e-2, atol=1e-3).all()
Exemple #7
0
#!/usr/bin/env python

import capytaine as cpt

# Generate the mesh of a cylinder
cylinder = cpt.HorizontalCylinder(
    length=10.0,
    radius=1.0,  # Dimensions
    center=(0, 0, -2),  # Position
    nr=1,
    nx=8,
    ntheta=6,  # Fineness of the mesh
)

# Use Nemoh to compute the influence matrices
solver = cpt.Nemoh(hierarchical_matrices=False)
S, K = solver.build_matrices(cylinder.mesh, cylinder.mesh, wavenumber=1.0)

# Plot the absolute value of the matrix V
#
import matplotlib.pyplot as plt
plt.imshow(abs(S))
plt.colorbar()
plt.title("$|S|$")
plt.tight_layout()
plt.show()
Exemple #8
0
import logging
import numpy as np
import xarray as xr
import matplotlib.pyplot as plt
import capytaine as cpt

# Set up logging
logging.basicConfig(level=logging.INFO,
                    format="%(levelname)s:\t%(message)s")

# Generate body
body = cpt.HorizontalCylinder(
    length=3.0, radius=1.0,  # Dimensions
    center=(0, 0, -1.01),     # Position
    nr=5, nx=15, ntheta=30,   # Fineness of the mesh
)
body.add_translation_dof(name="Heave")

test_matrix = xr.Dataset(coords={
    'omega': np.linspace(0.5, 4, 40),
    'radiating_dof': list(body.dofs.keys()),
})

ds2 = cpt.BEMSolver(green_function=cpt.XieDelhommeau()).fill_dataset(test_matrix, body)
ds1 = cpt.BEMSolver(green_function=cpt.Delhommeau()).fill_dataset(test_matrix, body)

plt.figure()
ds1['added_mass'].plot(x='omega', label='Delhommeau')
ds2['added_mass'].plot(x='omega', label='XieDelhommeau')
plt.legend()
Exemple #9
0
sphere.add_translation_dof(name="Heave")

# Define the second body
other_sphere = cpt.Sphere(radius=0.5,
                          center=(-2, -3, -1),
                          ntheta=20,
                          nphi=20,
                          name="sphere_2")
other_sphere.add_translation_dof(name="Surge")
other_sphere.add_translation_dof(name="Heave")

# Define the third body
cylinder = cpt.HorizontalCylinder(length=5.0,
                                  radius=1.0,
                                  center=(1.5, 3.0, -3.0),
                                  nx=20,
                                  nr=3,
                                  ntheta=20,
                                  name="cylinder")
cylinder.add_translation_dof(name="Surge")
cylinder.add_translation_dof(name="Heave")

# Combine the three individual bodies into a single body.
all_bodies = cylinder + sphere + other_sphere

print("Merged body name:", all_bodies.name)
print("Merged body dofs:", list(all_bodies.dofs.keys()))

# The merged body can be used to define the problems in the usual way
problems = [
    cpt.RadiationProblem(body=all_bodies, radiating_dof=dof, omega=1.0)
    dr = sin(mode_number * 2 * pi * x / length)

    u = 0.0
    v = (y / radius) * dr
    w = ((z - z_s) / radius) * dr

    return (u, v, w)


# Generate tube mesh from input values
tube = cpt.HorizontalCylinder(
    radius=tube_radius,
    length=tube_length,
    center=(0, 0, tube_submergence),
    nx=50,
    ntheta=15,
    nr=3,
    clever=False,
)
tube.keep_immersed_part()
tube.show()

# Add all rigid DOFs
tube.add_all_rigid_body_dofs()

# Add all flexible DOFs
for k in range(mode_count):
    key_name = 'bulge_' + str(k + 1)
    tube.dofs[key_name] = np.array([
        bulging_mode(x,