⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 dolfin-convert

📁 Dolfin provide a high-performance linear algebra library
💻
📖 第 1 页 / 共 2 页
字号:
#!/usr/bin/env python## Copyright (C) 2006 Anders Logg# Licensed under the GNU LGPL Version 2.1## Modified by Garth N. Wells (gmsh function)# Modified by Alexander H. Jarosch (gmsh fix)# Modified by Angelo Simone (Gmsh and Medit fix)# Modified by Andy R. Terrel (gmsh fix)# Modified by Magnus Vikstrom (metis and scotch function)# Modified by Bartosz Sawicki (diffpack function)## Script for converting between various data formatsimport getoptimport sysfrom commands import getoutputimport redef main(argv):    "Main function"    # Get command-line arguments    try:        opts, args = getopt.getopt(argv, "hi:o:", ["help", "input=", "output="])    except getopt.GetoptError:        usage()        sys.exit(2)            # Get options    input_format = ""    output_format = ""    for opt, arg in opts:        if opt in ("-h", "--help"):            usage()            sys.exit()        elif opt in ("-i", "--input"):            input_format = arg        elif opt in ("-o", "--output"):            output_format = arg    # Check that we got two filenames    if not len(args) == 2:        usage()        sys.exit(2)            # Get filenames and suffixes    ifilename = args[0]    ofilename = args[1]    isuffix = ifilename.split(".")[-1]    osuffix = ofilename.split(".")[-1]    # Choose format based on suffixes if not specified    if input_format == "":        input_format = format_from_suffix(isuffix)    if output_format == "":        output_format = format_from_suffix(osuffix)    # Choose conversion    if input_format == "mesh" and output_format == "xml":        # Convert from mesh to xml format        mesh2xml(ifilename, ofilename)    elif input_format == "gmsh" and output_format == "xml":        # Convert from gmsh to xml format        gmsh2xml(ifilename, ofilename)    elif input_format == "xml-old" and output_format == "xml":        # Convert from old to new xml format        xml_old2xml(ifilename, ofilename)    elif input_format == "metis" and output_format == "xml":        # Convert from metis graph to dolfin graph xml format        metis_graph2graph_xml(ifilename, ofilename)    elif input_format == "scotch" and output_format == "xml":        # Convert from scotch graph to dolfin graph xml format        scotch_graph2graph_xml(ifilename, ofilename)    elif input_format == "diffpack" and output_format == "xml":        # Convert from Diffpack tetrahedral grid format to xml format        diffpack2xml(ifilename, ofilename)    else:        error("Sorry, cannot convert between .%s and .%s file formats." % (isuffix, osuffix))def usage():    "Display usage"    print """\Usage: dolfin-convert [OPTIONS] ... input.x output.yOptions:  -h         display this help text and exit  -i format  specify input format  -o format  specify output formatAlternatively, the following long options may be used:  --help     same as -h  --input    same as -i  --output   same as -oSupported formats:  xml      - DOLFIN XML mesh format (current)  xml-old  - DOLFIN XML mesh format (DOLFIN 0.6.2 and earlier)  mesh     - Medit, generated by tetgen with option -g  gmsh     - Gmsh, version 2.0 file format  metis    - Metis graph file format  scotch   - Scotch graph file format  diffpack - Diffpack terahedral grid formatIf --input or --output are not specified, the format willbe deduced from the suffix:  .xml  - xml  .mesh - mesh  .gmsh - gmsh  .msh  - gmsh    .gra  - metis  .grf  - scotch  .grid - diffpack"""def format_from_suffix(suffix):    "Return format for given suffix"    if suffix == "xml":        return "xml"    elif suffix == "mesh":        return "mesh"    elif suffix == "gmsh":        return "gmsh"    elif suffix == "msh":        return "gmsh"    elif suffix == "gra":		  return "metis"    elif suffix == "grf":		  return "scotch"    elif suffix == "grid":		  return "diffpack"    else:        error("Sorry, unknown suffix %s." % suffix)def error(message):    "Write an error message"    for line in message.split("\n"):        print "*** %s" % line    sys.exit(2)def mesh2xml(ifilename, ofilename):    """Convert between .mesh and .xml, parser implemented as a    state machine:            0 = read 'Dimension'        1 = read dimension        2 = read 'Vertices'        3 = read number of vertices        4 = read next vertex        5 = read 'Triangles' or 'Tetrahedra'        6 = read number of cells        7 = read next cell        8 = done           """        print "Converting from Medit format (.mesh) to DOLFIN XML format"    # Open files    ifile = open(ifilename, "r")    ofile = open(ofilename, "w")    # Scan file for cell type    cell_type = None    dim = 0    while 1:        # Read next line        line = ifile.readline()        if not line: break        # Remove newline        if line[-1] == "\n":            line = line[:-1]        # Read dimension        if line == "Dimension":            line = ifile.readline()            num_dims = int(line)            if num_dims == 2:                cell_type = "triangle"                dim = 2            elif num_dims == 3:                cell_type = "tetrahedron"                dim = 3            break    # Check that we got the cell type    if cell_type == None:        error("Unable to find cell type.")    # Step to beginning of file    ifile.seek(0)    # Write header    write_header_mesh(ofile, cell_type, dim)    # Current state    state = 0    # Write data    num_vertices_read = 0    num_cells_read = 0    while 1:        # Read next line        line = ifile.readline()        if not line: break        # Skip comments        if line[0] == '#':            continue        # Remove newline        if line[-1] == "\n":            line = line[:-1]        if state == 0:            if line == "Dimension":                state += 1        elif state == 1:            num_dims = int(line)            state +=1        elif state == 2:            if line == "Vertices":                state += 1        elif state == 3:            num_vertices = int(line)            write_header_vertices(ofile, num_vertices)            state +=1        elif state == 4:            if num_dims == 2:                (x, y, tmp) = line.split()                x = float(x)                y = float(y)                z = 0.0            elif num_dims == 3:                (x, y, z, tmp) = line.split()                x = float(x)                y = float(y)                z = float(z)            write_vertex(ofile, num_vertices_read, x, y, z)            num_vertices_read +=1            if num_vertices == num_vertices_read:                write_footer_vertices(ofile)                state += 1        elif state == 5:            if line == "Triangles" and num_dims == 2:                state += 1            if line == "Tetrahedra" and num_dims == 3:                state += 1        elif state == 6:            num_cells = int(line)            write_header_cells(ofile, num_cells)            state +=1        elif state == 7:            if num_dims == 2:                (n0, n1, n2, tmp) = line.split()                n0 = int(n0) - 1                n1 = int(n1) - 1                n2 = int(n2) - 1                write_cell_triangle(ofile, num_cells_read, n0, n1, n2)            elif num_dims == 3:                (n0, n1, n2, n3, tmp) = line.split()                n0 = int(n0) - 1                n1 = int(n1) - 1                n2 = int(n2) - 1                n3 = int(n3) - 1                write_cell_tetrahedron(ofile, num_cells_read, n0, n1, n2, n3)            num_cells_read +=1            if num_cells == num_cells_read:                write_footer_cells(ofile)                state += 1        elif state == 8:            break    # Check that we got all data    if state == 8:        print "Conversion done"    else:        error("Missing data, unable to convert")    # Write footer    write_footer_mesh(ofile)    # Close files    ifile.close()    ofile.close()def gmsh2xml(ifilename, ofilename):    """Convert between .gmsh v2.0 format (http://www.geuz.org/gmsh/) and .xml,     parser implemented as a state machine:            0 = read 'MeshFormat'        1 = read  mesh format data        2 = read 'EndMeshFormat'        3 = read 'Nodes'        4 = read  number of vertices        5 = read  vertices        6 = read 'EndNodes'        7 = read 'Elements'        8 = read  number of cells        9 = read  cells        10 = done           """    print "Converting from Gmsh format (.msh, .gmsh) to DOLFIN XML format"    # Open files    ifile = open(ifilename, "r")    ofile = open(ofilename, "w")    # Scan file for cell type    cell_type = None    dim = 0    line = ifile.readline()    while line:        # Remove newline        if line[-1] == "\n":            line = line[:-1]        # Read dimension        if line.find("$Elements") == 0:                                    line = ifile.readline()            num_cells  = int(line)            num_cells_counted = 0            if num_cells == 0:                error("No cells found in gmsh file.")            line = ifile.readline()            # Now iterate through elements to find largest dimension.  Gmsh            # format might include elements of lower dimensions in the element list.            # We also need to count number of elements of correct dimensions.            # Also determine which vertices are not used.            dim_2_count = 0            dim_3_count = 0            vertices_2_used = []            vertices_3_used = []            while line.find("$EndElements") == -1:                element = line.split()                elem_type = int(element[1])                num_tags = int(element[2])                if elem_type == 2:                    if dim < 2:                        cell_type = "triangle"                        dim = 2                    node_num_list = [int(node) for node in element[3 + num_tags:]]                    vertices_2_used.extend(node_num_list)                    dim_2_count += 1                elif elem_type == 4:                    if dim < 3:                        cell_type = "tetrahedron"                        dim = 3                        vertices_2_used = None                    node_num_list = [int(node) for node in element[3 + num_tags:]]                    vertices_3_used.extend(node_num_list)                    dim_3_count += 1                line = ifile.readline()        else:            # Read next line            line = ifile.readline()    # Check that we got the cell type and set num_cells_counted    if cell_type == None:        error("Unable to find cell type.")    if dim == 3:        num_cells_counted = dim_3_count        vertex_set = set(vertices_3_used)        vertices_3_used = None    elif dim == 2:        num_cells_counted = dim_2_count        vertex_set = set(vertices_2_used)        vertices_2_used = None    vertex_dict = {}    for n,v in enumerate(vertex_set):        vertex_dict[v] = n    # Step to beginning of file    ifile.seek(0)    # Write header    write_header_mesh(ofile, cell_type, dim)        # Initialise node list (gmsh does not export all vertexes in order)    nodelist = {}        # Current state    state = 0        # Write data    num_vertices_read = 0    num_cells_read = 0    while state != 10:        # Read next line        line = ifile.readline()        if not line: break        # Skip comments        if line[0] == '#':            continue        # Remove newline        if line[-1] == "\n":            line = line[:-1]        if state == 0:            if line == "$MeshFormat":                state = 1        elif state == 1:            (version, file_type, data_size) = line.split()            state = 2        elif state == 2:            if line == "$EndMeshFormat":

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -