Ejemplo n.º 1
0
def mesh_statistics(in_file):
    """ Compute mesh statistics for a .msh mesh realization

    Parameters
    ----------
    in_file : Path
        Path to a .msh file

    Returns
    -------

    """
    in_file = Path(in_file)
    assert in_file.suffix == ".msh"
    assert in_file.is_file()

    import gmsh

    gmsh.initialize()
    gmsh.option.setNumber("Print.PostGamma", 1)
    gmsh.option.setNumber("Print.PostEta", 1)
    gmsh.option.setNumber("Print.PostSICN", 1)
    gmsh.option.setNumber("Print.PostSIGE", 1)

    gmsh.open(in_file)

    gmsh.finalize()
Ejemplo n.º 2
0
def mesh_bar_gmshapi(
    name, Lx, Ly, lc, tdim, order=1, msh_file=None, comm=MPI.COMM_WORLD
):
    """
    Create mesh of 3d tensile test specimen according to ISO 6892-1:2019 using the Python API of Gmsh.
    """
    # Perform Gmsh work only on rank = 0

    if comm.rank == 0:

        import gmsh

        # Initialise gmsh and set options
        gmsh.initialize()
        gmsh.option.setNumber("General.Terminal", 1)

        # gmsh.option.setNumber("Mesh.Algorithm", 6)

        gmsh.option.setNumber("Mesh.Algorithm", 5)
        gmsh.model.mesh.optimize("Netgen")
        model = gmsh.model()
        model.add("Rectangle")
        model.setCurrent("Rectangle")
        p0 = model.geo.addPoint(0.0, 0.0, 0, lc, tag=0)
        p1 = model.geo.addPoint(Lx, 0.0, 0, lc, tag=1)
        p2 = model.geo.addPoint(Lx, Ly, 0.0, lc, tag=2)
        p3 = model.geo.addPoint(0, Ly, 0, lc, tag=3)
        # points = [p0, p1, p2, p3]
        bottom = model.geo.addLine(p0, p1)
        right = model.geo.addLine(p1, p2)
        top = model.geo.addLine(p2, p3)
        left = model.geo.addLine(p3, p0)
        cloop1 = model.geo.addCurveLoop([bottom, right, top, left])
        # surface_1 =
        model.geo.addPlaneSurface([cloop1])

        model.geo.synchronize()
        surface_entities = [model[1] for model in model.getEntities(tdim)]
        model.addPhysicalGroup(tdim, surface_entities, tag=5)
        model.setPhysicalName(tdim, 5, "Rectangle surface")

        # Set geometric order of mesh cells
        gmsh.model.mesh.setOrder(order)
        gmsh.model.addPhysicalGroup(tdim - 1, [3, 0], tag=6)
        gmsh.model.setPhysicalName(tdim - 1, 6, "left")
        gmsh.model.addPhysicalGroup(tdim - 1, [1, 2], tag=7)
        gmsh.model.setPhysicalName(tdim - 1, 7, "right")
        gmsh.model.addPhysicalGroup(tdim - 1, [2, 3], tag=8)
        gmsh.model.setPhysicalName(tdim - 1, 8, "top")
        gmsh.model.addPhysicalGroup(tdim - 1, [0, 1], tag=9)
        gmsh.model.setPhysicalName(tdim - 1, 9, "bottom")

        model.mesh.generate(tdim)

        # Optional: Write msh file
        if msh_file is not None:
            os.makedirs(os.path.dirname(msh_file), exist_ok=True)
            gmsh.write(msh_file)

    return gmsh.model if comm.rank == 0 else None, tdim
Ejemplo n.º 3
0
def convertMEDfile(med_file):
    """
    This function opens an MED file by means of gmsh
    and saves it in .msh2 format.

    :param str med_file: has to end with .med

    """
    filename, ext = os.path.splitext(med_file)
    if ext != ".med":
        print("You must provide a med file!")
        sys.exit(0)
    # initialize gmsh
    gmsh.initialize()
    # gmsh writes out messages
    gmsh.option.setNumber("General.Terminal", 1)
    # add a new model
    gmsh.model.add("new_model")
    # open med file
    gmsh.open(med_file)
    # need dirty hack to write in correct format
    gmsh.write(filename + ".msh2")
    gmsh.finalize()
    with open(filename + ".msh2", 'r') as mesh_file:
        mesh = mesh_file.read()
    with open(filename + ".msh2", 'w') as mesh_file:
        mesh_file.write(mesh.replace(',', '.'))
    return
Ejemplo n.º 4
0
def create_model(res_points, outer_points, cntr, name):
    model = gmsh.model
    factory = model.geo

    gmsh.initialize()
    gmsh.option.setNumber("General.Terminal", 1)

    model.add("rotor")
    lc = 1e-2

    factory.addPoint(cntr[0], cntr[1], 0, lc, 1)
    for i in range(4):
        factory.addPoint(outer_points[i][0], outer_points[i][1], 0, lc, i + 2)
    factory.addLine(2, 3, 1)
    factory.addCircleArc(3, 1, 4, 2)
    factory.addLine(4, 5, 3)
    factory.addCircleArc(5, 1, 2, 4)

    point_cnt = 5
    for i in range(len(res_points)):
        for j in range(len(res_points[i])):
            point_cnt += 1
            factory.addPoint(res_points[i][j][0], res_points[i][j][1], 0, lc,
                             point_cnt)
        start = point_cnt - len(res_points[i]) + 1
        for j in range(len(res_points[i]) - 1):
            factory.addLine(start + j, start + j + 1)
        factory.addLine(point_cnt, start)

    factory.synchronize()
    model.mesh.generate(2)

    gmsh.write(name)
    gmsh.finalize()
Ejemplo n.º 5
0
def woofersSLA(maxElementSize=0.01):
    r = 0.0635  # Effective membrane radius of Eminence Alpha 6a (computed from Sd as per spec sheet)
    zOffset = 0.0
    gmsh.initialize()
    gmsh.option.setNumber("General.Terminal", 1)
    gmsh.model.add("disk")
    gmsh.model.geo.addPoint(0.0, 0.0, zOffset, maxElementSize, 1)
    gmsh.model.geo.addPoint(r, 0.0, zOffset, maxElementSize, 2)
    gmsh.model.geo.addPoint(0.0, r, zOffset, maxElementSize, 3)
    gmsh.model.geo.addPoint(-r, 0.0, zOffset, maxElementSize, 4)
    gmsh.model.geo.addPoint(0.0, -r, zOffset, maxElementSize, 5)

    gmsh.model.geo.addCircleArc(2, 1, 3, 1)
    gmsh.model.geo.addCircleArc(3, 1, 4, 2)
    gmsh.model.geo.addCircleArc(4, 1, 5, 3)
    gmsh.model.geo.addCircleArc(5, 1, 2, 4)

    gmsh.model.geo.addCurveLoop([1, 2, 3, 4], 1)
    gmsh.model.geo.addPlaneSurface([1], 1)
    gmsh.model.geo.translate([(2, 1)], 0.0, r + 0.005, 0.0)
    w2 = gmsh.model.geo.copy([(2, 1)])
    gmsh.model.geo.translate(w2, 0.0, 2.0 * r + 0.01, 0.0)
    w3 = gmsh.model.geo.copy([(2, 1)])
    gmsh.model.geo.translate(w3, 0.0, -(2 * r + 0.01), 0.0)
    w4 = gmsh.model.geo.copy([(2, 1)])
    gmsh.model.geo.translate(w4, 0.0, -(4.0 * r + 0.02), 0.0)
    gmsh.model.addPhysicalGroup(2, [1, w2[0][1], w3[0][1], w4[0][1]], 1)
    gmsh.model.setPhysicalName(2, 1, "Woofers")
    gmsh.model.geo.synchronize()

    oMesh = getTriangleMesh("WoofersSLA")
    gmsh.finalize()

    return oMesh
Ejemplo n.º 6
0
def disk(r=0.1, z_offset=1.0, name="Disk", max_element_size=0.01):
    gmsh.initialize()
    gmsh.option.setNumber("General.Terminal", 1)
    gmsh.model.add("disk")
    gmsh.model.geo.addPoint(0.0, 0.0, z_offset, max_element_size, 1)
    gmsh.model.geo.addPoint(r, 0.0, z_offset, max_element_size, 2)
    gmsh.model.geo.addPoint(0.0, r, z_offset, max_element_size, 3)
    gmsh.model.geo.addPoint(-r, 0.0, z_offset, max_element_size, 4)
    gmsh.model.geo.addPoint(0.0, -r, z_offset, max_element_size, 5)

    gmsh.model.geo.addCircleArc(2, 1, 3, 1)
    gmsh.model.geo.addCircleArc(3, 1, 4, 2)
    gmsh.model.geo.addCircleArc(4, 1, 5, 3)
    gmsh.model.geo.addCircleArc(5, 1, 2, 4)

    gmsh.model.geo.addCurveLoop([1, 2, 3, 4], 1)
    gmsh.model.geo.addPlaneSurface([1], 1)
    gmsh.model.addPhysicalGroup(2, [1], 1)
    gmsh.model.setPhysicalName(2, 1, name)
    gmsh.model.geo.synchronize()

    mesh = get_triangle_mesh(name)
    gmsh.finalize()

    return mesh
Ejemplo n.º 7
0
def read_from_msh(filename: str, cell_data=False, facet_data=False, gdim=None):
    """
    Reads a mesh from a msh-file and returns the dolfin-x mesh.
    Input:
        filename: Name of msh file
        cell_data: Boolean, True of a mesh tag for cell data should be returned
                   (Default: False)
        facet_data: Boolean, True if a mesh tag for facet data should be
                    returned (Default: False)
        gdim: Geometrical dimension of problem (Default: 3)
    """
    if MPI.COMM_WORLD.rank == 0:
        # Check if gmsh is already initialized
        try:
            current_model = gmsh.model.getCurrent()
        except ValueError:
            current_model = None
            gmsh.initialize()

        gmsh.model.add("Mesh from file")
        gmsh.merge(filename)
    output = gmsh_model_to_mesh(gmsh.model, cell_data=cell_data,
                                facet_data=facet_data, gdim=gdim)
    if MPI.COMM_WORLD.rank == 0:
        if current_model is None:
            gmsh.finalize()
        else:
            gmsh.model.setCurrent(current_model)
    return output
Ejemplo n.º 8
0
 def test_nx_ny_21_with_material(self):
     """Test nx, ny with 2 levels of 1 division and a material."""
     ref_groups = groups_21_with_material
     ref_centroids = centroids_21
     mocmg.initialize()
     gmsh.initialize()
     rectangular_grid(bb_44, nx=[2, 2], ny=[2, 2], material="material_UO2")
     group_nums = gmsh.model.getPhysicalGroups()
     names = [gmsh.model.getPhysicalName(*grp) for grp in group_nums]
     ref_names = list(ref_groups.keys())
     # Check correct names/entities
     for i, name in enumerate(ref_names):
         self.assertEqual(name, names[i])
         index = names.index(name)
         group_ents = list(
             gmsh.model.getEntitiesForPhysicalGroup(*group_nums[index]))
         ref_group_ents = ref_groups[name]
         self.assertEqual(group_ents, ref_group_ents)
     # Check correct area/centroid
     for ent in gmsh.model.getEntities(2):
         tag = ent[1]
         mass = gmsh.model.occ.getMass(2, tag)
         self.assertAlmostEqual(1.0,
                                mass,
                                places=5,
                                msg="1 width, 1 height, 1 area")
         x, y, z = gmsh.model.occ.getCenterOfMass(2, tag)
         centroid = (x, y, z)
         for i in range(3):
             self.assertAlmostEqual(centroid[i], ref_centroids[tag][i])
     # Check materials
     gmsh.clear()
     gmsh.finalize()
def grupos_fisicos(archivo, dim=-1):
    ''' Lee un archivo de texto con extensión .msh que contiene los datos de
        una malla generada en GMSH.
        Si se especifica el argumento dim, solo se reportan los grupos físicos
        de tal dimensión, si no, se reportan todos.
        Retorna:
            - Un diccionario en el cual las claves son las ETIQUETAS de los 
              grupos físicos y los valores son tuplas con la DIMENSIÓN y el
              NOMBRE asociados a cada etiqueta.
            - Un diccionario en el cual las claves son las etiquetas de los
              grupos físicos y los valores son listas con los nodos asociados
              a cada grupo físico.
    '''
    if archivo[-4:] != '.msh':
        raise ValueError('Solo se admite un archivo de extensión .msh')

    gmsh.initialize()
    gmsh.open(archivo)

    grupos = gmsh.model.getPhysicalGroups(dim)
    dims = [d[0] for d in grupos]
    tags = [d[1] for d in grupos]
    nombres = [(dim, gmsh.model.getPhysicalName(dim, tag))
                for dim, tag in grupos]

    dict1 = dict(zip(tags, nombres))  # Primer diccionario a reportar

    nodos = [gmsh.model.mesh.getNodesForPhysicalGroup(dims[i], tags[i])[0]
             for i in range(len(dims))]
    dict2 = dict(zip(tags, nodos))  # Segundo diccionario a reportar

    gmsh.finalize()

    return dict1, dict2
Ejemplo n.º 10
0
 def test_nx_y_11(self):
     """Test nx, y with 1 division."""
     ref_groups = groups_11
     ref_centroids = centroids_11
     mocmg.initialize()
     gmsh.initialize()
     rectangular_grid(bb_44, nx=[2], y=[[2.0]])
     group_nums = gmsh.model.getPhysicalGroups()
     names = [gmsh.model.getPhysicalName(*grp) for grp in group_nums]
     ref_names = list(ref_groups.keys())
     # Check correct names/entities
     for i, name in enumerate(ref_names):
         self.assertEqual(name, names[i])
         index = names.index(name)
         group_ents = list(
             gmsh.model.getEntitiesForPhysicalGroup(*group_nums[index]))
         ref_group_ents = ref_groups[name]
         self.assertEqual(group_ents, ref_group_ents)
     # Check correct area/centroid
     for ent in gmsh.model.getEntities(2):
         tag = ent[1]
         mass = gmsh.model.occ.getMass(2, tag)
         self.assertAlmostEqual(4.0,
                                mass,
                                places=5,
                                msg="2 width, 2 height, 4 area")
         x, y, z = gmsh.model.occ.getCenterOfMass(2, tag)
         centroid = (x, y, z)
         for i in range(3):
             self.assertAlmostEqual(centroid[i], ref_centroids[tag][i])
     gmsh.clear()
     gmsh.finalize()
Ejemplo n.º 11
0
 def test_x_y_nonuniform_2(self):
     """Test x, y with nonuniform grid with 2 levels."""
     ref_groups = groups_nu2
     ref_centroids = centroids_nu2
     ref_areas = areas_nu2
     mocmg.initialize()
     gmsh.initialize()
     rectangular_grid(bb_12_4,
                      x=[[0.0, 12.0], [2.0, 10.0]],
                      y=[[2.0], [1.0, 3.0]])
     group_nums = gmsh.model.getPhysicalGroups()
     names = [gmsh.model.getPhysicalName(*grp) for grp in group_nums]
     ref_names = list(ref_groups.keys())
     # Check correct names/entities
     for i, name in enumerate(ref_names):
         self.assertEqual(name, names[i])
         index = names.index(name)
         group_ents = list(
             gmsh.model.getEntitiesForPhysicalGroup(*group_nums[index]))
         ref_group_ents = ref_groups[name]
         self.assertEqual(group_ents, ref_group_ents)
     # Check correct area/centroid
     for ent in gmsh.model.getEntities(2):
         tag = ent[1]
         mass = gmsh.model.occ.getMass(2, tag)
         self.assertAlmostEqual(ref_areas[tag], mass, places=5)
         x, y, z = gmsh.model.occ.getCenterOfMass(2, tag)
         centroid = (x, y, z)
         for i in range(3):
             self.assertAlmostEqual(centroid[i], ref_centroids[tag][i])
     gmsh.clear()
     gmsh.finalize()
Ejemplo n.º 12
0
    def test_gmsh_primitives(self):
        shapes = [
            Box(np.array([0, 0, 0]), np.array([1, 1, 1])),
            Sphere(np.array([0, 0, 0]), 1),
            Cylinder(np.array([0, 0, 0]), np.array([1, 1, 1]), 1),
            Cone(np.array([0, 0, 0]), np.array([1, 1, 1]), 1, 2)
        ]

        gmsh.initialize()
        model = gmsh.model
        factory = model.occ

        for i, shape in enumerate(shapes):
            model.add(str(i))
            tag = shape.as_gmsh(model)
            factory.synchronize()

            x = model.occ.getCenterOfMass(3, tag)
            y = shape.center_of_mass
            self.assertTrue(np.linalg.norm(x - y) < 1E-13)

            model.mesh.generate(3)
            vtx_order, vtices, _ = model.mesh.getNodes()
            self.assertTrue(len(vtx_order))
            model.remove()

        gmsh.finalize()
Ejemplo n.º 13
0
 def wrapper(*args, **kwargs):
     gmsh.initialize()
     logging.info('Gmsh initialized')
     out = f(*args, **kwargs) if f is not None else None
     gmsh.finalize()
     logging.info('Gmsh finalized')
     return out
Ejemplo n.º 14
0
def test_inf(type='gap'):
    global gap, mur, mus, ref, TEST, PRINT, PRINTF
    TEST = True
    [PRINT, PRINTF] = 2 * [False]

    gmsh.initialize(sys.argv)
    # gmsh.write("ndt.unv")

    gmsh.option.setNumber("General.Terminal", 1)
    gmsh.option.setNumber("View[0].IntervalsType", 3)
    gmsh.option.setNumber("View[0].NbIso", 20)
    if type == 'all' or type == 'gap':
        for gap in np.arange(0.0001, 0.005, 0.0005):
            # MIN GAP : 0.1 cm
            # MAX GAP : 2.0 cm
            create_geometry()
            model.mesh.generate(2)
            solve()
            # gmsh.fltk.run()
        ALL = np.zeros((3, len(xgap)))
        ALL[0] = np.array(xgap)
        ALL[1] = np.array(ymin)
        ALL[2] = np.array(ymax)
        np.save('influences/numpy/gap', ALL)
    if type == 'all' or type == 'ref':
        for ref in range(1, 6):
            print('REF ======= %d' % ref)
            create_geometry()
            model.mesh.generate(2)
            solve()
            # gmsh.fltk.run()
        ALL = np.zeros((3, len(xref)))
        ALL[0] = np.array(xref)
        ALL[1] = np.array(ymin)
        ALL[2] = np.array(ymax)
        np.save('influences/numpy/ref', ALL)
    if type == 'all' or type == 'perm':
        gap = 0.2 * cm
        for mur in range(1, 300):
            create_geometry()
            model.mesh.generate(2)
            solve()
            # gmsh.fltk.run()
        ALL = np.zeros((3, len(xgap)))
        ALL[0] = np.arange(1, 300)
        ALL[1] = np.array(ymin)
        ALL[2] = np.array(ymax)
        np.save('influences/numpy/perm', ALL)
    if type == 'all' or type == 'experm':
        gap = 0.2 * cm
        for (mur, mat) in mus.items():
            create_geometry()
            model.mesh.generate(2)
            solve()
            # gmsh.fltk.run()
        ALL = np.zeros((3, len(xgap)))
        ALL[0] = np.array(list(mus.keys()))
        ALL[1] = np.array(ymin)
        ALL[2] = np.array(ymax)
        np.save('influences/numpy/experm', ALL)
Ejemplo n.º 15
0
def get_mesh():
    gmsh.initialize()
    air_tag, pec_tags, isrc_tag = g03.make_geom()
    gmsh.model.occ.synchronize()
    isrc, pec, air = g03.assign_physicals(air_tag, pec_tags, isrc_tag)
    #gmsh.model.mesh.setSize(gmsh.model.getEntities(0), 3)
    gmsh.model.mesh.setSize(gmsh.model.getEntities(0), 0.7)
    gmsh.option.setNumber("Mesh.Algorithm", 8)
    nodes, elems = g03.gen_mesh()
    gmsh.finalize()
    ret_elems = []
    for e in elems:
        attr = ()
        if e[0] == isrc:
            ptype = 'e'
            x = e[3][0].reshape(-1, 2) - 1
            attr = ([0, 0, 1], )
        elif e[0] == pec:
            ptype = 'b'
            x = e[3][0].reshape(-1, 3) - 1
        elif e[0] == air:
            ptype = 'v'
            x = e[3][0].reshape(-1, 4) - 1
            attr = (0, p04.e0, p04.u0)
        x.sort()
        ret_elems.append((ptype, attr, x))
    return nodes[1].reshape(-1, 3), ret_elems
Ejemplo n.º 16
0
def create_fluid():
    dx = 1
    gmsh.initialize()
    gmsh.open('t.msh')
    # Launch the GUI to see the results:
    # if '-nopopup' not in sys.argv:
    #     gmsh.fltk.run()

    nodeTags, nodesCoord, parametricCoord = gmsh.model.mesh.getNodes()
    liquid_x = nodesCoord[0::3]
    liquid_y = nodesCoord[2::3]
    liquid_z = nodesCoord[1::3]
    liquid_y = liquid_y + abs(min(liquid_y))
    liquid_x = liquid_x + abs(min(liquid_x))

    liquid_x = liquid_x[0::3]
    liquid_y = liquid_y[0::3]
    liquid_z = liquid_z[0::3]
    # x, y, z = np.meshgrid(liquid_x, liquid_y, liquid_z)
    # x = x.ravel()
    # y = y.ravel()
    # z = z.ravel()

    # return x * 1e-3, y * 1e-3, z * 1e-3
    return liquid_x * 1e-3, liquid_y * 1e-3, liquid_z * 1e-3
Ejemplo n.º 17
0
def mesh_bar_gmshapi(name, msh_file=None, comm=MPI.COMM_WORLD):
    """
    Create mesh.
    """

    # http://jsdokken.com/converted_files/tutorial_gmsh.html
    # https://moorejustinmusic.com/trending/how-do-i-use-gmsh-in-python/
    # https://stackoverflow.com/questions/54951925/questions-about-the-gmsh-python-api

    # Perform Gmsh work only on rank = 0

    if comm.rank == 0:

        import gmsh
        import warnings
        warnings.filterwarnings("ignore")
        # Initialise gmsh and set options
        gmsh.initialize()
        # gmsh.option.setNumber("General.Terminal", 1)
        # gmsh.option.setNumber("Mesh.Algorithm", 6)
        # model = gmsh.model()
        gmsh.model.add("Bool 2D")
        L, H, r = 1., 1., .1
        hole = gmsh.model.occ.addCircle(L / 2, L / 2, 0., r, tag=1)
        domain = gmsh.model.occ.addRectangle(0,
                                             0,
                                             0.,
                                             L,
                                             H,
                                             tag=2,
                                             roundedRadius=.1)
        boolean = gmsh.model.occ.cut([(2, hole)], [(2, domain)], tag=3)
Ejemplo n.º 18
0
    def make_geometry():
        gmsh.initialize()
        gmsh.option.setNumber("General.Terminal", 0)

        # cube
        box = gmsh.model.occ.addBox(-1000, -1000, -1000, 2000, 2000, 2000)
        # two "wells" extending above and bellow
        left_hole = gmsh.model.occ.addBox(-500, 0, -1200, 30, 30, 2400)
        right_hole = gmsh.model.occ.addBox(500, 0, -1200, 30, 30, 2400)
        gmsh.model.occ.synchronize()

        box = (3, box)
        b_box = gmsh.model.getBoundary([box], oriented=False)

        l_hole = (3, left_hole)
        r_hole = (3, right_hole)
        b_lhole = gmsh.model.getBoundary([l_hole], oriented=False)
        b_rhole = gmsh.model.getBoundary([r_hole], oriented=False)

        box_names = ["left", "right", "front", "back", "bottom", "top"]
        b_box_names = dict(zip(b_box, box_names))
        b_lhole_names = dict(zip(b_lhole, ["lhole_" + n for n in box_names]))
        b_rhole_names = dict(zip(b_rhole, ["rhole_" + n for n in box_names]))
        names = b_box_names
        names.update(b_lhole_names)
        names.update(b_rhole_names)

        holes = [l_hole, r_hole]
        b_holes = b_lhole + b_rhole
        return b_box, holes, b_holes, names
Ejemplo n.º 19
0
def main():

    args = docopt(__doc__)

    qc_surf = args['<qc_surf>']
    C = np.load(args['<C>'])
    R = np.load(args['<R>'])
    b = np.load(args['<bounds>'])
    out = args['<out>']

    # Construct parameteric surface coordinates
    X, Y = np.meshgrid(np.linspace(b[0, 0] + 1, b[0, 1] - 1),
                       np.linspace(b[1, 0] + 1, b[1, 1] - 1))
    XX = X.flatten()
    YY = Y.flatten()
    poly_arr = np.c_[np.ones(XX.shape[0]), XX, YY, XX * YY, XX * XX, YY * YY]
    Z = np.dot(poly_arr, C)
    poly_coords = np.matmul(R, np.c_[XX, YY, Z].T).T

    # Load in mesh
    gmsh.initialize()
    gmsh.open(qc_surf)
    entity = gmsh.model.getEntities()[0]
    n_tag, n_coord, params = gmsh.model.mesh.getNodes(entity[0], entity[1])

    samp_surf_coords = poly_coords.flatten(order='C')
    samp_surf_nodes = np.arange(max(n_tag), max(n_tag) + poly_coords.shape[0])
    grid = samp_surf_nodes.reshape((50, 50))
    n = grid.shape[0]

    # Construct mesh
    trig_list = np.zeros((6 * (n - 1)**2), dtype=np.int64)
    for j in np.arange(0, grid.shape[0] - 1):
        for i in np.arange(0, grid.shape[1] - 1):
            # Upper triangular
            trig_list[6 * i + 6 * (n - 1) * j] = grid[(j, i)]
            trig_list[6 * i + 1 + 6 * (n - 1) * j] = grid[(j, i + 1)]
            trig_list[6 * i + 2 + 6 * (n - 1) * j] = grid[(j + 1, i + 1)]

            # Lower triangular
            trig_list[6 * i + 3 + 6 * (n - 1) * j] = grid[(j + 1, i)]
            trig_list[6 * i + 4 + 6 * (n - 1) * j] = grid[(j, i)]
            trig_list[6 * i + 5 + 6 * (n - 1) * j] = grid[(j + 1, i + 1)]

    gmsh.initialize()
    gmsh.model.add('sampling_surf')
    tag = gmsh.model.addDiscreteEntity(2, 3002)
    gmsh.model.mesh.setNodes(2,
                             tag,
                             nodeTags=samp_surf_nodes,
                             coord=samp_surf_coords)
    gmsh.model.mesh.setElements(
        2,
        tag, [2],
        elementTags=[range(1,
                           len(trig_list) // 3 + 1)],
        nodeTags=[trig_list])
    gmsh.write(out)
    gmsh.finalize()
Ejemplo n.º 20
0
 def _write_stl(self, target_path):
     target_geo = os.path.join(target_path, 'new_surface.geo')
     target_stl = os.path.join(target_path, 'new_surface.stl')
     gmsh.initialize()
     gmsh.open(target_geo)
     gmsh.model.mesh.generate(3)
     gmsh.write(target_stl)
     gmsh.finalize()
Ejemplo n.º 21
0
def embed_mesh1d(mesh1d, bounding_shape, how, gmsh_args, **kwargs):
    '''
    Embed 1d in Xd mesh Xd padded hypercube. Embedding can be as 
    points / lines (these are gmsh options). 

    Returns: LineMeshEmbedding
    '''
    assert mesh1d.topology().dim() == 1
    assert mesh1d.geometry().dim() > 1

    # Some convenience API where we expand
    if isinstance(bounding_shape, str):
        bounding_shape = STLShape(bounding_shape)
        return embed_mesh1d(mesh1d, bounding_shape, how, gmsh_args, **kwargs)

    # int -> padded
    if is_number(bounding_shape):
        bounding_shape = (bounding_shape, ) * mesh1d.geometry().dim()
        return embed_mesh1d(mesh1d, bounding_shape, how, gmsh_args, **kwargs)

    # Padded to relative box
    if isinstance(bounding_shape, (tuple, list, np.ndarray)):
        bounding_shape = BoundingBox(bounding_shape)
        return embed_mesh1d(mesh1d, bounding_shape, how, gmsh_args, **kwargs)

    kwargs = configure_options(**kwargs)

    etime = Timer(
        'Emebdding %d vertices and %d edges in R^%d' %
        (mesh1d.num_vertices(), mesh1d.num_cells(), mesh1d.geometry().dim()))
    # At this point the type of bounding shape must check out
    assert isinstance(bounding_shape, BoundingShape)
    # FIXME: we should have that all 1d points are <= bounding shape
    #        later ... compute intersects for points on surface
    #        skip all for now

    model = gmsh.model

    gmsh.initialize(list(gmsh_args))
    gmsh.option.setNumber("General.Terminal", 1)

    if bounding_shape.is_inside(mesh1d, mesh1d.coordinates()):
        if how.lower() == 'as_lines':
            out = line.line_embed_mesh1d(model, mesh1d, bounding_shape,
                                         **kwargs)
        else:
            assert how.lower() == 'as_points'
            out = point.point_embed_mesh1d(model, mesh1d, bounding_shape,
                                           **kwargs)

        gmsh.finalize()
        etime.done()
        return out

    # FIXME: Doing points on manifolds is more involved in gmsh
    # because the surface needs to be broken apart (manually?)
    raise NotImplementedError
Ejemplo n.º 22
0
    def __init__(self, Meangen, IN):
        # Storing Meangen class.
        self.M = Meangen

        # Reading mesh parameters from input file.

        self.wedge = IN["WEDGE"][0]     # Importing mesh wedge angle
        self.n_sec = int(IN["SECTIONS_PER_DEGREE"][0]) * self.wedge     # Calculating number of tangential nodes
        self.n_point = int(IN["AXIAL_POINTS"][0])       # Importing axial node count
        self.inlet_fac = IN["INLET_FACTOR"][0]          # Importing inlet cell size factor
        self.outlet_fac = IN["OUTLET_FACTOR"][0]        # Importing outlet cell size factor
        self.rot_axis = IN["Rotation_axis"]

        self.Coords = type('', (), {})()
        # Initiating Gmesh.
        self.model = gmsh.model
        self.factory = self.model.geo
        gmsh.initialize()
        gmsh.option.setNumber("General.Terminal", 1)
        self.model.add("3DBFM")

        # Creating all the mesh points.
        self.makePoints()

        # Connecting the mesh points to create lines.
        self.makeLines()

        # Making periodic plane.
        self.makePlane()

        # Revolving plane around rotation axis to create 3D wedge.
        self.revolve()

        # Setting names to boundaries.
        self.nameBoundaries()

        # Creating 3D mesh.
        gmsh.model.geo.synchronize()

        # Applying mesh refinement along the lines in the mesh
        self.refineLines()

        # Generate the 3D mesh geometry
        gmsh.model.mesh.generate(3)

        # Saving mesh as su2 file
        gmsh.write(self.fileName)

        # Transforming mesh to periodic mesh.
        print("Building periodic mesh...")
        self.makePerio()
        print("Done!")

        # In case of selection of mesh visualization option, the gmesh GUI will display the 3D BFM mesh.
        if IN["PLOT_MESH"] == 'YES':
            self.plotmesh()
        gmsh.finalize()
Ejemplo n.º 23
0
    def __init__(self, Meangen):
        self.M = Meangen

        self.model = gmsh.model
        self.factory = self.model.geo
        gmsh.initialize()
        gmsh.option.setNumber("General.Terminal", 1)

        self.model.add("3DBFM")
Ejemplo n.º 24
0
def create_mesh(vol, F):
    gmsh.initialize()
    gmsh.option.setNumber("General.Terminal", 0)

    f = 0.01 * F
    a = (vol / (1 / 8 * 4 / 3 * math.pi * f**3 + 3 * 1 / 4 * math.pi * f**2 *
                (1 - f) + 3 * f * (1 - f)**2 + (1 - f)**3))**(1.0 / 3.0)

    internal = []
    gmsh.model.add("cubesphere")
    if (F < 1):
        # a cube
        gmsh.model.occ.addBox(0, 0, 0, a, a, a, 1)
        internal = [1, 3, 5]
        external = [2, 4, 6]

    elif (F > 99):
        # a sphere
        gmsh.model.occ.addSphere(0, 0, 0, a, 1, 0, math.pi / 2, math.pi / 2)
        internal = [2, 3, 4]
        external = [1]

    else:
        gmsh.model.occ.addBox(0, 0, 0, a, a, a, 1)
        gmsh.model.occ.fillet([1], [12, 7, 6], [f * a], True)
        internal = [1, 4, 6]
        external = [2, 3, 5, 7, 8, 9, 10]

    gmsh.model.occ.synchronize()

    gmsh.model.addPhysicalGroup(3, [1], 1)
    gmsh.model.setPhysicalName(3, 1, "fuel")

    gmsh.model.addPhysicalGroup(2, internal, 2)
    gmsh.model.setPhysicalName(2, 2, "internal")
    gmsh.model.addPhysicalGroup(2, external, 3)
    gmsh.model.setPhysicalName(2, 3, "external")

    gmsh.model.occ.synchronize()

    gmsh.option.setNumber("Mesh.ElementOrder", 2)
    gmsh.option.setNumber("Mesh.Optimize", 1)
    gmsh.option.setNumber("Mesh.OptimizeNetgen", 1)
    gmsh.option.setNumber("Mesh.HighOrderOptimize", 1)

    gmsh.option.setNumber("Mesh.CharacteristicLengthMin", a / 10)
    gmsh.option.setNumber("Mesh.CharacteristicLengthMax", a / 10)

    gmsh.model.mesh.generate(3)
    gmsh.write("cubesphere-%g.msh" % (F))

    gmsh.model.remove()
    #gmsh.fltk.run()

    gmsh.finalize()
    return
Ejemplo n.º 25
0
    def define_geometry(self) -> None:
        """Feed the geometry specified in self._data to gmsh."""
        gmsh.initialize()

        gmsh.option.setNumber("General.Verbosity", 3)

        # All geometries need their points
        self._point_tags = self._add_points()

        # The boundary, and the domain, must be specified prior to the
        # co-dimension 1 objects (fractures) so that the latter can be
        # embedded in the domain. This requires some specialized treatment
        # in 2d and 3d, since the boundary and fractures are made of up
        # different geometric objects in the two:
        if self._dim == 1:
            # This should not be difficult, but has not been prioritized.
            raise NotImplementedError("1d geometries are not implemented")

        elif self._dim == 2:
            # First add the domain. This will add the lines that form the domain
            # boundary, but not the fracture lines.
            self._domain_tag = self._add_domain_2d()

            # Next add the fractures (and constraints). This adds additional lines,
            # and embeds them in the domain.
            self._add_fractures_2d()

        else:
            # In 3d, we can first add lines to the description, they are only used
            # to define surfaces later.

            # Make a index list covering all the lines
            inds = np.arange(self._data.lines.shape[1])

            # The function to write lines assumes that the lines are formed by
            # point indices (first two rows), tags (third) and line index (fourth)
            # Add the latter, essentially saying that each line is a separate line.
            if self._data.lines.shape[0] < 4:
                self._data.lines = np.vstack((self._data.lines, inds))

            # Now we can write the lines
            # The lines are not directly embedded in the domain.
            # NOTE: If we ever get around to do a 1d-3d model (say a well), this may
            # be a place to do that.
            self._line_tags = self._add_lines(inds, embed_in_domain=False)

            # Next add the domain. This adds the boundary surfaces, embeds lines in
            # the relevant boundary surfaces, and constructs a 3d volume from the
            # surfaces
            self._domain_tag = self._add_domain_3d()

            # Finally, we can add the fractures and constraints and embed them in
            # the domain
            self._add_fractures_3d()

        gmsh.model.geo.synchronize()
Ejemplo n.º 26
0
 def __init__(self, name):
     gmsh.initialize()
     gmsh.clear()
     gmsh.model.add(name)
     self.name = name
     self.model = gmsh.model
     self.fac = self.model.occ
     self.pos = gmsh.view
     self.vertices = np.array([])
     self.tetra = np.array([])
 def __init__(self, settings, BoundaryNames, Polylines):
     self._boundary_name = BoundaryNames
     self.contour_polylines = Polylines
     self.mesh_size = settings["mesh_size"].GetDouble()
     self.user_2d_output = settings["output_gmsh_2d"].GetBool()
     self.gmsh_format = ".vtk"
     self.file_name_user = settings["file_name"].GetString()
     self.gmsh_kratos_format = settings["output_gmsh_2d_format"].GetString()
     gmsh.initialize(sys.argv)
     gmsh.model.add("Volumemesh")
Ejemplo n.º 28
0
 def __init__(self,
              name: Optional[str] = None,
              verbose: bool = False) -> None:
     gmsh.initialize(sys.argv)
     gmsh.model.add(name or f'{self.__class__.__name__}')
     self._verbose = False
     self.verbose = verbose
     self.model = gmsh.model
     self.mesh = gmsh.model.mesh
     self.occ = gmsh.model.occ
Ejemplo n.º 29
0
def volume_with_fracture():
    gmsh.initialize()
    gmsh.option.setNumber("General.Terminal", 1)
    gmsh.model.add("volume-with-fracture")
    gmsh.logger.start()
    kernel = gmsh.model.occ

    # Add outer box
    dx = dy = dz = 1
    outer_box = kernel.addBox(0, 0, 0, dx, dy, dz)

    # Add inner box
    cx = cy = cz = dx / 2  # Center  # Set to dx/2 in production
    sx = sy = sz = 0.2  # Radius
    corner = (cx - sx, cy - sy, cz - sz)
    size = (2 * sx, 2 * sy, 2 * sz)
    inner_box = kernel.addBox(*corner, *size)
    kernel.synchronize()

    # Add fracture
    xmin, ymin, zmin, xmax, ymax, zmax = gmsh.model.getBoundingBox(
        3, inner_box)
    dx = xmax - xmin
    dy = ymax - ymin
    dz = zmax - zmin

    angle = -math.pi / 6
    lx = dx / math.cos(angle)

    # Through-going fracture
    frac = kernel.addRectangle(xmin, ymin, zmin, lx, dy)
    # Rotate
    f = [(2, frac)]
    kernel.rotate([f[0]], xmin, ymin, zmin, 0, 1, 0, angle)

    # Insert the fracture to the domain
    f_out, f_m = kernel.fragment([(3, inner_box)], [f[0]])
    kernel.synchronize()

    # Partition domain
    box_dim = 3
    out, m = kernel.fragment(
        [(box_dim, outer_box)],
        f_out,
    )
    kernel.synchronize()

    # Mesh the domain
    gmsh.option.setNumber("Mesh.CharacteristicLengthMin", 0.05)
    gmsh.option.setNumber("Mesh.CharacteristicLengthMax", 0.05)

    gmsh.model.mesh.generate(3)

    gmsh.fltk.run()
    gmsh.finalize()
Ejemplo n.º 30
0
def test_gmsh_input_3d(order, cell_type):
    try:
        import gmsh
    except ImportError:
        pytest.skip()
    if cell_type == CellType.hexahedron and order > 2:
        pytest.xfail("GMSH permutation for order > 2 hexahedra not implemented in DOLFINx.")

    res = 0.2

    gmsh.initialize()
    if cell_type == CellType.hexahedron:
        gmsh.option.setNumber("Mesh.RecombinationAlgorithm", 2)
        gmsh.option.setNumber("Mesh.RecombineAll", 2)
    gmsh.option.setNumber("Mesh.CharacteristicLengthMin", res)
    gmsh.option.setNumber("Mesh.CharacteristicLengthMax", res)

    circle = gmsh.model.occ.addDisk(0, 0, 0, 1, 1)

    if cell_type == CellType.hexahedron:
        gmsh.model.occ.extrude([(2, circle)], 0, 0, 1, numElements=[5], recombine=True)
    else:
        gmsh.model.occ.extrude([(2, circle)], 0, 0, 1, numElements=[5])
    gmsh.model.occ.synchronize()

    gmsh.model.mesh.generate(3)
    gmsh.model.mesh.setOrder(order)

    idx, points, _ = gmsh.model.mesh.getNodes()
    points = points.reshape(-1, 3)
    idx -= 1
    srt = np.argsort(idx)
    assert np.all(idx[srt] == np.arange(len(idx)))
    x = points[srt]

    element_types, element_tags, node_tags = gmsh.model.mesh.getElements(dim=3)
    name, dim, order, num_nodes, local_coords, num_first_order_nodes = gmsh.model.mesh.getElementProperties(
        element_types[0])

    cells = node_tags[0].reshape(-1, num_nodes) - 1
    if cell_type == CellType.tetrahedron:
        gmsh_cell_id = MPI.COMM_WORLD.bcast(gmsh.model.mesh.getElementType("tetrahedron", order), root=0)
    elif cell_type == CellType.hexahedron:
        gmsh_cell_id = MPI.COMM_WORLD.bcast(gmsh.model.mesh.getElementType("hexahedron", order), root=0)
    gmsh.finalize()

    # Permute the mesh topology from GMSH ordering to DOLFINx ordering
    domain = ufl_mesh_from_gmsh(gmsh_cell_id, 3)
    cells = cells[:, perm_gmsh(cell_type, cells.shape[1])]

    mesh = create_mesh(MPI.COMM_WORLD, cells, x, domain)

    volume = assemble_scalar(form(1 * dx(mesh)))

    assert mesh.comm.allreduce(volume, op=MPI.SUM) == pytest.approx(np.pi, rel=10 ** (-1 - order))
Ejemplo n.º 31
0
  def __init__(self, filename):
    if not _gmsh_found: raise _gmsh_exeption

    # suppress loggin
    if not os.path.isfile(filename):
      raise IOError("No such file or directory: '%s'" % filename)
    gmsh.initialize()
    gmsh.open(filename)
    self._model = gmsh.model
    self._physical_cell_ids = None
    self._physical_face_ids = None
Ejemplo n.º 32
0
import gmsh
import math

model = gmsh.model
factory = model.occ

gmsh.initialize()
gmsh.option.setNumber("General.Terminal", 1)

model.add("spline")

for i in range(1, 11):
    factory.addPoint(i, math.sin(i/9.*2.*math.pi), 0, 0.1, i)

factory.addSpline(range(1, 11), 1)
factory.addBSpline(range(1, 11), 2)
factory.addBezier(range(1, 11), 3)

factory.addPoint(0.2,-1.6,0,0.1, 101) 
factory.addPoint(1.2,-1.6,0,0.1, 102) 
factory.addPoint(1.2,-1.1,0,0.1, 103) 
factory.addPoint(0.3,-1.1,0,0.1, 104) 
factory.addPoint(0.7,-1,0,0.1, 105) 

# periodic bspline through the control points
factory.addSpline([103,102,101,104,105,103], 100)

# periodic bspline from given control points and default parameters - will
# create a new vertex
factory.addBSpline([103,102,101,104,105,103], 101)
Ejemplo n.º 33
0
import gmsh
import sys

gmsh.initialize(sys.argv)
gmsh.option.setNumber("General.Terminal", 1)
print(gmsh.option.getNumber("Mesh.Algorithm"))

gmsh.open("square.msh")

model = gmsh.model

model.add("square")
factory = model.geo
factory.addPoint(0,0,0,0.1,1)
factory.addPoint(1,0,0,0.1,2)
factory.addPoint(1,1,0,0.1,3)
factory.addPoint(0,1,0,0.1,4)
factory.addLine(1,2,1)
factory.addLine(2,3,2)
factory.addLine(3,4,3)
line4 = factory.addLine(4,1)
print("line4 received tag ", line4)
factory.addCurveLoop([1,2,3,line4],1)
factory.addPlaneSurface([1],6)
factory.synchronize()

ptag = model.addPhysicalGroup(1,[1,2,3,4])
ent = model.getEntitiesForPhysicalGroup(1,ptag)
print("new physical group ",ptag,":",ent, type(ent))

model.addPhysicalGroup(2,[6])