Exemple #1
0
def visualize_with_gmsh(obj):
    """
    View a grid or grid function with Gmsh

    Parameters
    ----------
    obj : bempp.api.Grid or bempp.api.GridFunction
        Grid or grid function to visualize.

    Notes
    -----
    This function writes the data into a temp file and
    visualizes it. 

    """

    import tempfile
    import subprocess
    from bempp.api import export, GMSH_PATH, TMP_PATH, GridFunction
    from bempp.api.grid import Grid
    from numpy import real

    if GMSH_PATH is None:
        print("Gmsh not available for visualization.")
        return None

    f = tempfile.NamedTemporaryFile(suffix=".msh",dir=TMP_PATH, delete=False)
    if isinstance(obj, Grid):
        export(grid=obj,file_name=f.name)
    elif isinstance(obj, GridFunction):
        export(grid_function=obj,file_name=f.name,transformation=real)
    f.close()

    subprocess.Popen([GMSH_PATH,f.name])
Exemple #2
0
 def ext_neumann2dirichlet(self):
     self.adjoint_double = boundary.helmholtz.adjoint_double_layer(
         self.dp0_space,
         self.dp0_space,
         self.p1_space,
         self.k,
         device_interface='opencl')
     self.hyper_single = boundary.helmholtz.hypersingular(
         self.p1_space,
         self.dp0_space,
         self.p1_space,
         self.k,
         device_interface='opencl')
     self.identity = boundary.sparse.identity(self.dp0_space,
                                              self.dp0_space, self.p1_space)
     left_side = self.hyper_single
     right_side = (-0.5 * self.identity -
                   self.adjoint_double) * self.neumann_fun
     dirichlet_fun, info, _ = bempp.api.linalg.gmres(left_side,
                                                     right_side,
                                                     tol=1e-6,
                                                     return_residuals=True)
     self.dirichlet_fun = dirichlet_fun
     export('./modedata/left.msh', grid_function=left_side * dirichlet_fun)
     export('./modedata/right.msh', grid_function=right_side)
Exemple #3
0
def work(file_list):
    sphere = boundary_mesh(grid=bempp.api.shapes.sphere(h=0.02,r = 0.2))
    pole_matrix = PolesMatrix()
    pole_matrix.sample_points(0.1)
    pole_matrix.assemble_matrix()
    print('pole matrix initialized')

    for dirname in tqdm(file_list):
        if os.path.exists(dirname+'/displacements.npy'):
            continue
        vertices = np.load(dirname+'/vertices.npy')
        print(dirname)
        boundary_faces = np.load(dirname+'/boundary_faces.npy')
        print(boundary_faces.shape)
        tets = np.load(dirname + '/tets.npy')
        current_model = boundary_mesh(vertices=vertices, faces=boundary_faces)
        #=====================FEM modal analysis=================
        fem = FEM_model(vertices, tets)
        fem.set_material(Material.Iron)
        fem.create_matrix()
        fem.compute_modes(min_freq=20,max_freq=20000)
        print(len(fem.omega_d))
        if len(fem.omega_d) < 5:
            continue
        if fem.omega_d[0]/(2*np.pi) < 500:
            continue
        #=====================save data==========================
        export(dirname+'/mesh.msh', grid=current_model.grid)
        np.save(dirname+'/face_centers', current_model.face_centers())
        np.save(dirname+'/face_normals', current_model.normals())
        np.save(dirname+'/omegas', fem.omega_d)
        modes_num = len(fem.vals)
        poles_coeffs = np.zeros((modes_num, pole_matrix.poles.pole_number), dtype = np.complex)
        displacements = np.zeros((modes_num, len(boundary_faces)))
        for i in range(modes_num):
            omega = fem.omega_d[i]
            k_ = omega / SPEED_OF_SOUND
            freq_idx = pole_matrix.wavenumber2index(k_)
            k = pole_matrix.wave_numbers[freq_idx]
            #=================BEM=======================
            displacement = fem.vecs[:,i].reshape(-1,3)
            displacement = displacement[boundary_faces].mean(1)
            displacement = (displacement*current_model.normals()).sum(1)
            displacements[i] = displacement
            neumann_coeff = AIR_DENSITY*omega**2*displacement
            neumann_fun =  GridFunction(current_model.dp0_space, coefficients=np.asarray(neumann_coeff))
            current_model.set_wave_number(k)
            current_model.set_neumann_fun(neumann_fun)
            current_model.ext_neumann2dirichlet()
            #==================least square method=================
            b = current_model.points_dirichlet(pole_matrix.points)
            A = pole_matrix.all_matrix[freq_idx]
            weights, res, _, _ = lstsq(A,b)
            poles_coeffs[i] = weights
        np.save(dirname+'/poles_coeffs', poles_coeffs)
        np.save(dirname+'/displacements', displacements)
Exemple #4
0
def test_something():
    mobj = larf.mesh.Object()
    assert len(mobj.points) == 0
    cyl = larf.shapes.cylinder()
    mobj.gen(cyl)
    assert len(mobj.points) > 0
    assert mobj.points.shape[1] == 3

    mobj2 = mobj.copy()
    assert len(mobj2.points) > 0
    assert mobj2.points.shape[1] == 3

    mobj2.translate([-5, 0, 0])
    assert len(mobj2.points) > 0
    assert mobj2.points.shape[1] == 3

    mobj2.rotate(30 * deg)
    assert len(mobj2.points) > 0
    assert mobj2.points.shape[1] == 3

    scene = larf.mesh.Scene()
    scene.add(mobj, 1)
    scene.add(mobj2, 2)
    grid = scene.grid()

    filename = "test_mesh.msh"
    print('gmsh %s' % filename)
    bem.export(grid=grid, file_name=filename)

    dat = scene.asdict()
    scene2 = larf.mesh.Scene()
    scene2.fromdict(dat)
    compare_scene(scene, scene2)
    grid2 = scene2.grid()
    compare_grid(grid, grid2)

    string = scene.dumps()
    scene3 = larf.mesh.Scene()
    scene3.loads(string)
    compare_scene(scene, scene3)
    grid3 = scene3.grid()
    compare_grid(grid, grid3)

    filename = "test_mesh.json"
    print "writing %s" % filename
    with open(filename, "w") as fp:
        fp.write(string)

    import json
    dats = open(filename).read()
    scene4 = larf.mesh.Scene()
    scene4.loads(dats)
    compare_scene(scene, scene4)
    grid4 = scene4.grid()
    compare_grid(grid, grid4)
Exemple #5
0
def visualize_with_paraview(obj, mode="element", transformation=None):
    """
    View a grid or grid function with Paraview.

    Parameters
    ----------
    obj : bempp.api.Grid or bempp.api.GridFunction
        Grid or grid function to visualize.
    mode : string
        One of 'element' or 'node'
        (default 'vertices')
    transformation : callable
        A function object that is applied to the data before
        writing it out

    Notes
    -----
    This function writes the data into a temp file and
    visualizes it.

    """
    import tempfile
    import subprocess
    from bempp.api import export, TMP_PATH, GridFunction
    from bempp.api.grid.grid import Grid
    from bempp.api.utils import which
    import os

    if os.name == "nt":
        pview = which("paraview.exe")
    else:
        pview = which("paraview")

    if pview is None:
        raise EnvironmentError(
            "Could not find Paraview." +
            "Interactive plotting with Paraview not available.")

    outfile = tempfile.NamedTemporaryFile(suffix=".vtu",
                                          dir=TMP_PATH,
                                          delete=False)
    if isinstance(obj, Grid):
        export(outfile.name, grid=obj)
    elif isinstance(obj, GridFunction):
        export(
            outfile.name,
            grid_function=obj,
            transformation=transformation,
            data_type=mode,
        )
    outfile.close()

    subprocess.Popen([pview, outfile.name])
Exemple #6
0
def check():
    r_in = 0.1
    r_out = 0.1 * 3**(0.5)
    sphere = boundary_mesh(grid=bempp.api.shapes.sphere(h=0.01, r=r_out))
    current_model = boundary_mesh(grid=bempp.api.shapes.sphere(h=0.01, r=r_in))
    c = 343
    omega = 1000 * 6.28
    k = omega / c

    scale = 10
    poles = special.Multipole(scale)
    weights = np.zeros(poles.pole_number)
    weights[0] = 0.3
    weights[10] = 0.3
    weights[5] = 0.3
    neumann_coeff = []
    dirichlet_coeff = []
    for point in current_model.face_centers():
        poles.reset(k, point)
        poles.dirichlet_reset()
        poles.neumann_reset()
        neumann_coeff.append((poles.neumann * weights).sum())
        dirichlet_coeff.append((poles.dirichlet * weights).sum())

    neumann_fun = GridFunction(current_model.dp0_space,
                               coefficients=np.asarray(neumann_coeff))
    dirichlet_fun = GridFunction(current_model.dp0_space,
                                 coefficients=np.asarray(dirichlet_coeff))

    current_model.set_wave_number(k)
    current_model.set_neumann_fun(neumann_fun)
    current_model.ext_neumann2dirichlet()

    export(f'./modedata/test_N.msh', grid_function=current_model.neumann_fun)
    export(f'./modedata/test_D.msh', grid_function=current_model.dirichlet_fun)
    export(f'./modedata/test_D_truth.msh', grid_function=dirichlet_fun)

    coeff = current_model.points_dirichlet(sphere.face_centers())
    print(coeff.shape)
    print(sphere.faces.shape)
    export(f'./modedata/sphere_predict.msh',
           grid_function=GridFunction(sphere.dp0_space, coefficients=coeff))
    coeff = []
    for point in sphere.face_centers():
        poles.reset(k, point)
        poles.dirichlet_reset()
        coeff.append((poles.dirichlet * weights).sum())
    coeff = np.asarray(coeff)
    dirichlet_fun = GridFunction(sphere.dp0_space, coefficients=coeff)
    export(f'./modedata/shpere_truth.msh', grid_function=dirichlet_fun)
Exemple #7
0
def visualize_with_gmsh(obj, mode='element', transformation=None):
    """
    View a grid or grid function with Gmsh

    Parameters
    ----------
    obj : bempp.api.Grid or bempp.api.GridFunction
        Grid or grid function to visualize.
    mode : string
        One of 'element' or 'node'
        (default 'vertices')
    transformation : callable
        A function object that is applied to the data before
        writing it out

    Notes
    -----
    This function writes the data into a temp file and
    visualizes it.

    """
    import tempfile
    import subprocess
    from bempp.api import export, GMSH_PATH, TMP_PATH, GridFunction
    from bempp.api.grid.grid import Grid
    import numpy as np

    if transformation is None:
        transformation = np.real

    if GMSH_PATH is None:
        print("Gmsh not available for visualization.")
        return None

    outfile = tempfile.NamedTemporaryFile(suffix=".msh",
                                          dir=TMP_PATH,
                                          delete=False)
    if isinstance(obj, Grid):
        export(grid=obj, file_name=outfile.name)
    elif isinstance(obj, GridFunction):
        export(grid_function=obj,
               file_name=outfile.name,
               transformation=transformation,
               data_type=mode)
    outfile.close()

    subprocess.Popen([GMSH_PATH, outfile.name])
Exemple #8
0
def check():
    vox = Hexa_model('dataset/7.obj')
    vox.create_tetra_and_boundary()
    vox.set_transform([center_scale(0.2)])
    print(vox.tets.shape)
    return
    r_in = 0.1
    r_out = 0.2
    sphere = boundary_mesh(grid=bempp.api.shapes.sphere(h=0.02,r = r_out))
    current_model = boundary_mesh(vertices=vox.vertices, faces=vox.boundary_faces)
    c = 343
    omega = 1000*6.28
    k = omega / c
    print(k)
    scale = 10
    poles = special.Multipole(scale)
    weights = np.zeros(poles.pole_number)
    weights[1] = 0.3
    weights[5] = 0.3
    neumann_coeff = []
    dirichlet_coeff = []
    for point,normal in zip(current_model.face_centers(), current_model.normals()):
        #print(point, normal)
        poles.reset(k,point)
        poles.dirichlet_reset()
        poles.neumann_reset(normal)
        neumann_coeff.append((poles.neumann*weights).sum())
        dirichlet_coeff.append((poles.dirichlet*weights).sum())

    neumann_fun =  GridFunction(current_model.dp0_space, coefficients=np.asarray(neumann_coeff))
    dirichlet_fun = GridFunction(current_model.dp0_space, coefficients=np.asarray(dirichlet_coeff))

    os.makedirs(f'./modedata',exist_ok=True)
    current_model.set_wave_number(k)
    current_model.set_neumann_fun(neumann_fun)
    current_model.ext_neumann2dirichlet()
    
    export(f'./modedata/test_N.msh',grid_function=current_model.neumann_fun)
    
    identity = boundary.sparse.identity(
                        current_model.p1_space, current_model.dp0_space, current_model.p1_space)
    export(f'./modedata/test_D.msh',grid_function=identity*current_model.dirichlet_fun)
    export(f'./modedata/test_D_truth.msh',grid_function=dirichlet_fun)

    

    
    coeff = current_model.points_dirichlet(sphere.face_centers())
    print(coeff.shape)
    print(sphere.faces.shape)
    export(f'./modedata/sphere_predict.msh', grid_function=GridFunction(sphere.dp0_space, 
                                                            coefficients=coeff))
    coeff = []
Exemple #9
0
def preprocess(dirname):
    displacements = np.load(dirname+'/displacements.npy')
    poles_coeffs = np.load(dirname+'/poles_coeffs.npy')
    omegas = np.load(dirname+'/omegas.npy')
    
    mesh = boundary_mesh(np.load(dirname+'/vertices.npy'),np.load(dirname+'/boundary_faces.npy'))

    modes_dict = {i:[] for i in range(freq.resolution)}
    for i,omega in enumerate(omegas):
        modes_dict[freq.omega2index(omega)].append(i)

    for i in range(23,24):
        idxs = modes_dict[i]
        if len(idxs) == 0:
            continue
        omega = freq.index2omega(i)
        k = omega / SPEED_OF_SOUND
        displace = displacements[idxs]
        displace = abs(displace)
        coeff = poles_coeffs[idxs]
        print(coeff)
        # A = (displace.T[...,np.newaxis]*coeff).sum(-2)
        # c = A.sum(0)
        # print(c.shape)
        # A = A - c
        # U,S,V = scipy.sparse.linalg.svds(A,k=2)
        # print(U.shape)
        # export(f'modedata/{i}_1.msh',grid_function=GridFunction(mesh.dp0_space, coefficients=U[:,0]))
        # export(f'modedata/{i}_2.msh',grid_function=GridFunction(mesh.dp0_space, coefficients=U[:,1]))

        for j,displace_ in enumerate(displace):
            export(f'modedata/{i}_dis{j}.msh',grid_function=GridFunction(mesh.dp0_space, coefficients=displace_))
        export(f'modedata/{i}_dis_all.msh',grid_function=GridFunction(mesh.dp0_space, coefficients=displace.sum(0)))
        export(f'modedata/{i}_dis_all_square.msh',grid_function=GridFunction(mesh.dp0_space, coefficients=(displace**2).sum(0)**0.5))

        sphere = boundary_mesh(grid=bempp.api.shapes.sphere(h=0.02,r = 0.2))
        for j,coeff_ in enumerate(coeff):
            export(f'modedata/{i}_coeff{j}.msh',grid_function=pole_matrix.get_grid_function(sphere, coeff_, k))
        export(f'modedata/{i}_coeff_all.msh',grid_function=pole_matrix.get_grid_fun_from_list(sphere, coeff, k))
Exemple #10
0
def test():
    scale = 0.2
    vox = Plate_model(200)
    vox.create_tetra_and_boundary()
    vox.set_transform([center_scale(scale)])
    fem = FEM_model(vox.vertices, vox.tets)
    fem.set_material(0)
    fem.create_matrix()
    fem.compute_modes()

    print('==========modal data=============')
    print(fem.vals.shape)
    print(fem.vecs.shape)
    print(fem.vertices.max(), fem.vertices.min())

    sphere = boundary_mesh(
        grid=bempp.api.shapes.sphere(h=0.01, r=0.1 * 3**(0.5)))
    current_model = boundary_mesh(vertices=vox.vertices,
                                  faces=vox.boundary_faces)

    for i in range(len(fem.vals)):
        c = 343
        omega = fem.vals[i]
        displacement = fem.vecs[:, i]
        k = omega / c
        displacement = displacement.reshape(-1, 3)
        displacement = displacement[vox.boundary_faces].mean(1)
        c = (displacement * current_model.grid.normals).sum(1)
        neumann_fun = GridFunction(current_model.dp0_space, coefficients=c)

        current_model.set_wave_number(k)
        current_model.set_neumann_fun(neumann_fun)
        current_model.ext_neumann2dirichlet()

        export(f'./modedata/{i}stMode.msh',
               grid_function=current_model.neumann_fun)
        export(f'./modedata/{i}stMode_d.msh',
               grid_function=current_model.dirichlet_fun)

        coeffs = current_model.points_dirichlet(sphere.face_centers())
        print(coeffs.shape)
        print(sphere.faces.shape)
        export(f'./modedata/{i}st_sphere.msh',
               grid_function=GridFunction(sphere.dp0_space,
                                          coefficients=coeffs))
Exemple #11
0
slices = mtf.getSlices()
s = slices['0']

sol = xx[s[0]:s[1]]
d = mtf.domains.getIndexDom('0')
(space, _), (_, _) = mtf.spaces[d]

n, = sol.shape
n = int(n / 2)
sold, soln = sol[:n], sol[n:]

gsold = bem.GridFunction(space, coefficients=sold)
gsoln = bem.GridFunction(space, coefficients=soln)

bem.export(grid_function=gsold, file_name="soldR.msh", transformation=np.real)
bem.export(grid_function=gsold, file_name="soldI.msh", transformation=np.imag)

print('solution saved.')

# Nx = 200
# Ny = 200
# xmin, xmax, ymin, ymax = [-0.5, 4.5, -0.5, 1.5]
# plot_grid = np.mgrid[xmin:xmax:Nx * 1j, ymin:ymax:Ny * 1j]
# points = np.vstack((plot_grid[0].ravel(),
#                     plot_grid[1].ravel(),
#                     np.zeros(plot_grid[0].size)))
# u = np.zeros(points.shape[1], dtype=np.complex)
# u[:] = np.nan

# slp = bem.operators.potential.helmholtz.single_layer(
Exemple #12
0
    def work(filename):
        dirname = os.path.basename(filename)[:-3]
        output_dir = 'modedata/' + dirname
        os.makedirs(output_dir, exist_ok=True)
        dirname = glob('dataset/*/test/' + dirname)[0]

        print(dirname)
        vertices = np.load(dirname + '/vertices.npy')
        omegas = np.load(dirname + '/omegas.npy')
        poles_coeffs = np.load(dirname + '/poles_coeffs.npy')
        boundary_faces = np.load(dirname + '/boundary_faces.npy')
        mesh = boundary_mesh(vertices, boundary_faces)

        n = 2048
        data = torch.load(filename)
        faces_num = len(data.x)
        mask_list = torch.ones(faces_num)
        #==================================w====================
        if mask_list.sum() > n:
            mask = torch.multinomial(mask_list, n, replacement=False)
        else:
            mask = torch.multinomial(mask_list, n, replacement=True)

        data1 = Data()
        data1.pos = data.pos[mask]
        data1.normal = data.normal[mask]
        data1.batch = torch.zeros(len(data1.pos), dtype=torch.int64)
        data1 = data1.to(device)
        out = model_w(data1).view(32, 200).cpu().numpy()
        out_w = out[:, :100] + 1j * out[:, 100:]
        w = data.w.view(32, 200).cpu().numpy()
        w = w[:, :100] + 1j * w[:, 100:]
        #================================dis=======================
        dis = data.dis.cpu().numpy()
        out_dis = np.zeros_like(dis)
        while mask_list.sum() > n:
            mask = torch.multinomial(mask_list, n, replacement=False)
            mask_list[mask] = 0
            data1 = Data()
            data1.pos = data.pos[mask]
            data1.normal = data.normal[mask]
            data1.batch = torch.zeros(len(data1.pos), dtype=torch.int64)
            data1 = data1.to(device)
            out = model_dis(data1)
            out_dis[mask] = out.cpu().numpy()

        mask = torch.multinomial(mask_list, n, replacement=True)
        data1 = Data()
        data1.pos = data.pos[mask]
        data1.normal = data.normal[mask]
        data1.batch = torch.zeros(len(data1.pos), dtype=torch.int64)
        data1 = data1.to(device)
        out = model_dis(data1)
        out_dis[mask] = out.cpu().numpy()

        modes_dict = {i: [] for i in range(freq.resolution)}
        for i, omega in enumerate(omegas):
            modes_dict[freq.omega2index(omega)].append(i)
        for i in range(23, 24):
            if data.s[0, i] == 0:
                continue
            coeff = poles_coeffs[modes_dict[i]]
            export(f'{output_dir}/gt{i}.msh',
                   grid_function=GridFunction(mesh.dp0_space,
                                              coefficients=dis[:, i]))
            export(f'{output_dir}/predict{i}.msh',
                   grid_function=GridFunction(mesh.dp0_space,
                                              coefficients=out_dis[:, i]))
            export(f'{output_dir}/{i}_sphere.msh',
                   grid_function=pole_matrix.get_grid_function(
                       sphere, out_w[i],
                       freq.index2omega(i) / SPEED_OF_SOUND))
            export(f'{output_dir}/{i}_sphere_gt.msh',
                   grid_function=pole_matrix.get_grid_function(
                       sphere, w[i],
                       freq.index2omega(i) / SPEED_OF_SOUND))
            export(f'{output_dir}/{i}_sphere_gt2.msh',
                   grid_function=pole_matrix.get_grid_fun_from_list(
                       sphere, coeff,
                       freq.index2omega(i) / SPEED_OF_SOUND))
Exemple #13
0
slices = mtf.getSlices()
s = slices['0']

sol = xx[s[0]:s[1]]
d = mtf.domains.getIndexDom('0')
(space, _) , (_, _) = mtf.spaces[d]

n, = sol.shape
n = int(n/2)
sold, soln = sol[:n], sol[n:]

gsold = bem.GridFunction(space, coefficients=sold)
gsoln = bem.GridFunction(space, coefficients=soln)

bem.export(grid_function=gsold,
           file_name="soldR.msh",
           transformation=np.real)
bem.export(grid_function=gsold,
           file_name="soldI.msh",
           transformation=np.imag)

print('solution saved.')

# Nx = 200
# Ny = 200
# xmin, xmax, ymin, ymax = [-0.5, 4.5, -0.5, 1.5]
# plot_grid = np.mgrid[xmin:xmax:Nx * 1j, ymin:ymax:Ny * 1j]
# points = np.vstack((plot_grid[0].ravel(),
#                     plot_grid[1].ravel(),
#                     np.zeros(plot_grid[0].size)))
# u = np.zeros(points.shape[1], dtype=np.complex)
Exemple #14
0
dlp = bempp.api.operators.boundary.helmholtz.double_layer(	
    p1_space, p1_space, p1_space,k)	
slp = bempp.api.operators.boundary.helmholtz.single_layer(	
    dp0_space, p1_space, p1_space,k)

def hankel(n,z,derivative=False):
    return special.spherical_jn(n,z,derivative) + 1j*special.spherical_yn(n,z,derivative)

@bempp.api.complex_callable(jit=False)
def dirichlet_data(x, n_, domain_index, result):	
    r = (x[0]**2+x[1]**2+x[2]**2)**0.5
    #phi = np.arccos(x[0]/r)
    phi = np.arctan2(x[1],x[0])
    theta =  np.arccos(x[2]/r)
    result[0] = hankel(n,r*k)*special.sph_harm(m,n,phi,theta)

@bempp.api.complex_callable(jit=False)
def neumann_data(x, n_, domain_index, result):	
    r = (x[0]**2+x[1]**2+x[2]**2)**0.5
    # phi = np.arccos(x[0]/r)
    phi = np.arctan2(x[1],x[0])
    theta =  np.arccos(x[2]/r)
    result[0] = k*hankel(n,r*k, True)*special.sph_harm(m,n,phi,theta)

dirichlet_fun = bempp.api.GridFunction(p1_space, fun=dirichlet_data)
neumann_fun = bempp.api.GridFunction(dp0_space, fun=neumann_data)
export('neumann.msh',grid_function= neumann_fun)
export('dirichlet.msh', grid_function= dirichlet_fun)

dirichlet_fun_predict, info = bempp.api.gmres(-0.5*identity + dlp, slp*neumann_fun)
export('dirichlet_predict.msh', grid_function= dirichlet_fun_predict)