def WriteHalos(halos, filename): """ Write a Fluidity .halo file """ xmlfile = xml.dom.minidom.Document() halosRootEle = xmlfile.createElement("halos") halosRootEle.setAttribute("process", str(halos.GetProcess())) halosRootEle.setAttribute("nprocs", str(halos.GetNProcesses())) xmlfile.appendChild(halosRootEle) halos = halos.LevelHaloDict() for level in halos.keys(): halo = halos[level] haloEle = xmlfile.createElement("halo") haloEle.setAttribute("level", str(level)) haloEle.setAttribute("n_private_nodes", str(halo.GetNOwnedNodes())) halosRootEle.appendChild(haloEle) for i, process in enumerate(range(halo.GetNProcesses())): haloDataEle = xmlfile.createElement("halo_data") haloDataEle.setAttribute("process", str(i)) haloEle.appendChild(haloDataEle) sendEle = xmlfile.createElement("send") haloDataEle.appendChild(sendEle) if level > 0: sendText = xmlfile.createTextNode(utils.FormLine(utils.OffsetList(utils.ExpandList(halo.GetSends(process = i)), 1), delimiter = " ", newline = False)) else: sendText = xmlfile.createTextNode(utils.FormLine(utils.ExpandList(halo.GetSends(process = i)), delimiter = " ", newline = False)) sendEle.appendChild(sendText) receiveEle = xmlfile.createElement("receive") haloDataEle.appendChild(receiveEle) if level > 0: receiveText = xmlfile.createTextNode(utils.FormLine(utils.OffsetList(utils.ExpandList(halo.GetReceives(process = i)), 1), delimiter = " ", newline = False)) else: receiveText = xmlfile.createTextNode(utils.FormLine(utils.ExpandList(halo.GetReceives(process = i)), delimiter = " ", newline = False)) receiveEle.appendChild(receiveText) handle = open(filename, "w") if XmlExtSupport(): xml.dom.ext.PrettyPrint(xmlfile, handle) else: xmlfile.writexml(handle) handle.flush() handle.close() return
def WriteGid(mesh, filename): """ Write a GiD file with the given filename """ debug.dprint("Writing GiD mesh with filename " + filename) fileHandle = open(filename, "w") # Write the header fileHandle.write(utils.FormLine(["MESH", "dimension", mesh.GetDim(), "ElemType", "Unknown", "Nnode", mesh.VolumeElementFixedNodeCount()])) # Write the nodes fileHandle.write("Coordinates\n") for i, nodeCoord in enumerate(mesh.GetNodeCoords()): fileHandle.write(" " + utils.FormLine([i + 1, nodeCoord])) fileHandle.write("end coordinates\n") # Write the volume elements fileHandle.write("Elements\n") for i, element in enumerate(mesh.GetVolumeElements()): # Note: GiD file indexes nodes from 1, Mesh s index nodes from 0 fileHandle.write(" " + utils.FormLine([i + 1, ToGidNodeOrder(utils.OffsetList(element.GetNodes(), 1), elements.ElementType(dim = mesh.GetDim(), nodeCount = element.NodeCount()))])) fileHandle.write("end elements\n") fileHandle.close() debug.dprint("Finished writing GiD mesh") return mesh
def WriteTriangle(mesh, baseName): """ Write triangle files with the given base name """ def FileFooter(): return "# Created by triangletools.WriteTriangle\n" + \ "# Command: " + " ".join(sys.argv) + "\n" + \ "# " + str(time.ctime()) + "\n" debug.dprint("Writing triangle mesh with base name " + baseName) # Write the .node file debug.dprint("Writing .node file") nodeHandle = open(baseName + ".node", "w") # Write the meta data nodeHandle.write(utils.FormLine([mesh.NodeCount(), mesh.GetDim(), 0, 0])) # Write the nodes for i in range(mesh.NodeCount()): nodeHandle.write(utils.FormLine([i + 1, mesh.GetNodeCoord(i)])) nodeHandle.write(FileFooter()) nodeHandle.close() if mesh.GetDim() == 1: # Write the .bound file debug.dprint("Writing .bound file") boundHandle = open(baseName + ".bound", "w") # Write the meta data nBoundIds = 0 for i in range(mesh.SurfaceElementCount()): if i == 0: nBoundIds = len(mesh.GetSurfaceElement(i).GetIds()) else: assert(nBoundIds == len(mesh.GetSurfaceElement(i).GetIds())) boundHandle.write(utils.FormLine([mesh.SurfaceElementCount(), nBoundIds])) # Write the bounds for i in range(mesh.SurfaceElementCount()): boundHandle.write(utils.FormLine([i + 1, utils.OffsetList(mesh.GetSurfaceElement(i).GetNodes(), 1), mesh.GetSurfaceElement(i).GetIds()])) boundHandle.write(FileFooter()) boundHandle.close() elif mesh.GetDim() == 2: # Write the .edge file debug.dprint("Writing .edge file") edgeHandle = open(baseName + ".edge", "w") # Write the meta data nEdgeIds = 0 for i in range(mesh.SurfaceElementCount()): if i == 0: nEdgeIds = len(mesh.GetSurfaceElement(i).GetIds()) else: assert(nEdgeIds == len(mesh.GetSurfaceElement(i).GetIds())) edgeHandle.write(utils.FormLine([mesh.SurfaceElementCount(), nEdgeIds])) # Write the edges for i in range(mesh.SurfaceElementCount()): edgeHandle.write(utils.FormLine([i + 1, utils.OffsetList(mesh.GetSurfaceElement(i).GetNodes(), 1), mesh.GetSurfaceElement(i).GetIds()])) edgeHandle.write(FileFooter()) edgeHandle.close() elif mesh.GetDim() == 3: # Write the .face file debug.dprint("Writing .face file") faceHandle = open(baseName + ".face", "w") # Write the meta data nFaceIds = 0 for i in range(mesh.SurfaceElementCount()): if i == 0: nFaceIds = len(mesh.GetSurfaceElement(i).GetIds()) else: assert(nFaceIds == len(mesh.GetSurfaceElement(i).GetIds())) faceHandle.write(utils.FormLine([mesh.SurfaceElementCount(), nFaceIds])) # Write the faces for i in range(mesh.SurfaceElementCount()): faceHandle.write(utils.FormLine([i + 1, utils.OffsetList(mesh.GetSurfaceElement(i).GetNodes(), 1), mesh.GetSurfaceElement(i).GetIds()])) faceHandle.write(FileFooter()) faceHandle.close() # Write the .ele file debug.dprint("Writing .ele file") eleHandle = open(baseName + ".ele", "w") # Write the meta data nNodesPerEle = 0 nEleIds = 0 for i in range(mesh.VolumeElementCount()): if i == 0: nEleIds = len(mesh.GetVolumeElement(i).GetIds()) nNodesPerEle = mesh.GetVolumeElement(i).GetLoc() else: assert(nEleIds == len(mesh.GetVolumeElement(i).GetIds())) assert(nNodesPerEle == mesh.GetVolumeElement(i).GetLoc()) eleHandle.write(utils.FormLine([mesh.VolumeElementCount(), nNodesPerEle, nEleIds])) # Write the eles for i in range(mesh.VolumeElementCount()): # Note: Triangle mesh indexes nodes from 1, Mesh s index nodes from 0 eleHandle.write(utils.FormLine([i + 1, utils.OffsetList(mesh.GetVolumeElement(i).GetNodes(), 1), mesh.GetVolumeElement(i).GetIds()])) eleHandle.write(FileFooter()) eleHandle.close() halos = mesh.GetHalos() if halos.HaloCount() > 0: # Write the .halo file debug.dprint("Writing .halo file") if mesh_halos.HaloIOSupport(): mesh_halos.WriteHalos(halos, baseName + ".halo") else: debug.deprint("Warning: No .halo I/O support") debug.dprint("Finished writing triangle file") return
def WritePoly(mesh, filename, holeMesh=None): """ Write a .poly file with the given base name """ def FileFooter(): return "# Created by WritePoly\n" + \ "# Command: " + " ".join(sys.argv) + "\n" + \ "# " + str(time.ctime()) + "\n" polyHandle = open(filename, "w") # Write the node meta data polyHandle.write("# Nodes\n") polyHandle.write(utils.FormLine([mesh.NodeCount(), mesh.GetDim(), 0, 0])) # Write the nodes for i in range(mesh.NodeCount()): polyHandle.write(utils.FormLine([i + 1, mesh.GetNodeCoord(i)])) # Write the facets meta data polyHandle.write("# Facets\n") nFacetIds = 0 for i in range(mesh.SurfaceElementCount()): if i == 0: nFacetIds = len(mesh.GetSurfaceElement(i).GetIds()) else: assert (nFacetIds == len(mesh.GetSurfaceElement(i).GetIds())) polyHandle.write(utils.FormLine([mesh.SurfaceElementCount(), nFacetIds])) # Write the facets if mesh.GetDim() == 2: # This is the facet specification as in the Triangle documentation # http://www.cs.cmu.edu/~quake/triangle.poly.html for i in range(mesh.SurfaceElementCount()): # Note: .poly indexes nodes from 1, Mesh s index nodes from 0 polyHandle.write( utils.FormLine([ i + 1, utils.OffsetList(mesh.GetSurfaceElement(i).GetNodes(), 1), mesh.GetSurfaceElement(i).GetIds() ])) else: # This is the facet specification as in the Tetgen documentation # http://tetgen.berlios.de/fformats.poly.html for i in range(mesh.SurfaceElementCount()): polyHandle.write( utils.FormLine([1, 0, mesh.GetSurfaceElement(i).GetIds()])) # Note: .poly indexes nodes from 1, Mesh s index nodes from 0 polyHandle.write( utils.FormLine([ mesh.GetSurfaceElement(i).NodeCount(), utils.OffsetList(mesh.GetSurfaceElement(i).GetNodes(), 1) ])) # Write the hole list meta data polyHandle.write("# Holes\n") if holeMesh is None: polyHandle.write(utils.FormLine([0])) else: polyHandle.write(utils.FormLine([holeMesh.NodeCount()])) # Write the holes for i in range(holeMesh.NodeCount()): polyHandle.write(utils.FormLine([i + 1, holeMesh.GetNodeCoord(i)])) polyHandle.write(FileFooter()) polyHandle.close() return
def WriteMsh(mesh, filename, binary = True): """ Write a Gmsh msh file """ if binary: # Binary format fileHandle = open(filename, "wb") # Write the MeshFormat section fileHandle.write("$MeshFormat\n") version = 2.1 fileType = 1 dataSize = ctypes.sizeof(ctypes.c_double) fileHandle.write(utils.FormLine([version, fileType, dataSize])) iArr = array.array("i", [1]) iArr.tofile(fileHandle) fileHandle.write("\n") fileHandle.write("$EndMeshFormat\n") # Write the Nodes section fileHandle.write("$Nodes\n") fileHandle.write(utils.FormLine([mesh.NodeCoordsCount()])) for i, nodeCoord in enumerate(mesh.GetNodeCoords()): nodeCoord = list(nodeCoord) while len(nodeCoord) < 3: nodeCoord.append(0.0) assert(len(nodeCoord) == 3) iArr = array.array("i", [i + 1]) rArr = array.array("d", nodeCoord) iArr.tofile(fileHandle) rArr.tofile(fileHandle) fileHandle.write("\n") fileHandle.write("$EndNodes\n") # Write the Elements section fileHandle.write("$Elements\n") fileHandle.write(utils.FormLine([mesh.SurfaceElementCount() + mesh.VolumeElementCount()])) eleSort = {} for ele in mesh.GetSurfaceElements() + mesh.GetVolumeElements(): eleType = ele.GetType() gmshType = GmshElementType(dim = eleType.GetDim(), nodeCount = eleType.GetNodeCount()) key = (gmshType.GetGmshElementTypeId(), len(ele.GetIds())) if key in eleSort: eleSort[key].append(ele) else: eleSort[key] = [ele] index = 1 for gmshEleId, nIds in eleSort: eles = eleSort[(gmshEleId, nIds)] iArr = array.array("i", [gmshEleId, len(eles), nIds]) iArr.tofile(fileHandle) for ele in eles: iArr = array.array("i", [index] + list(ele.GetIds()) + utils.OffsetList(ToGmshNodeOrder(ele.GetNodes(), ele.GetType()), 1)) iArr.tofile(fileHandle) index += 1 assert(index == mesh.SurfaceElementCount() + mesh.VolumeElementCount() + 1) fileHandle.write("\n") fileHandle.write("$EndElements\n") else: # ASCII format fileHandle = open(filename, "w") # Write the MeshFormat section fileHandle.write("$MeshFormat\n") version = 2.1 fileType = 0 dataSize = ctypes.sizeof(ctypes.c_double) fileHandle.write(utils.FormLine([version, fileType, dataSize])) fileHandle.write("$EndMeshFormat\n") # Write the Nodes section fileHandle.write("$Nodes\n") fileHandle.write(utils.FormLine([mesh.NodeCoordsCount()])) for i, nodeCoord in enumerate(mesh.GetNodeCoords()): nodeCoord = list(nodeCoord) while len(nodeCoord) < 3: nodeCoord.append(0.0) assert(len(nodeCoord) == 3) fileHandle.write(utils.FormLine([i + 1, nodeCoord])) fileHandle.write("$EndNodes\n") # Write the Elements section fileHandle.write("$Elements\n") fileHandle.write(utils.FormLine([mesh.SurfaceElementCount() + mesh.VolumeElementCount()])) for i, ele in enumerate(mesh.GetSurfaceElements() + mesh.GetVolumeElements()): eleType = ele.GetType() gmshType = GmshElementType(dim = eleType.GetDim(), nodeCount = eleType.GetNodeCount()) ids = ele.GetIds() fileHandle.write(utils.FormLine([i + 1, gmshType.GetGmshElementTypeId(), len(ids), ids, utils.OffsetList(ToGmshNodeOrder(ele.GetNodes(), eleType), 1)])) fileHandle.write("$EndElements\n") return
def ReadMsh(filename): """ Read a Gmsh msh file """ def ReadNonCommentLine(fileHandle): line = fileHandle.readline() while len(line) > 0: line = line.strip() if len(line) > 0: return line line = fileHandle.readline() return line fileHandle = open(filename, "r") basename = filename.split(".")[0] hasHalo = filehandling.FileExists(basename + ".halo") # Read the MeshFormat section line = ReadNonCommentLine(fileHandle) assert(line == "$MeshFormat") line = ReadNonCommentLine(fileHandle) lineSplit = line.split() assert(len(lineSplit) == 3) version = float(lineSplit[0]) fileType = int(lineSplit[1]) dataSize = int(lineSplit[2]) if fileType == 1: # Binary format if dataSize == 4: realFormat = "f" elif dataSize == 8: realFormat = "d" else: raise Exception("Unrecognised real size " + str(dataSize)) iArr = array.array("i") iArr.fromfile(fileHandle, 1) if iArr[0] == 1: swap = False else: iArr.byteswap() if iArr[0] == 1: swap = True else: raise Exception("Invalid one byte") line = ReadNonCommentLine(fileHandle) assert(line == "$EndMeshFormat") # Read the Nodes section line = ReadNonCommentLine(fileHandle) assert(line == "$Nodes") line = ReadNonCommentLine(fileHandle) nNodes = int(line) # Assume dense node IDs, but not necessarily ordered seenNode = [False for i in range(nNodes)] nodeIds = [] nodes = [] lbound = [calc.Inf() for i in range(3)] ubound = [-calc.Inf() for i in range(3)] for i in range(nNodes): iArr = array.array("i") rArr = array.array(realFormat) iArr.fromfile(fileHandle, 1) rArr.fromfile(fileHandle, 3) if swap: iArr.byteswap() rArr.byteswap() nodeId = iArr[0] coord = rArr assert(nodeId > 0) assert(not seenNode[nodeId - 1]) seenNode[nodeId - 1] = True nodeIds.append(nodeId) nodes.append(coord) for j in range(3): lbound[j] = min(lbound[j], coord[j]) ubound[j] = max(ubound[j], coord[j]) line = ReadNonCommentLine(fileHandle) assert(line == "$EndNodes") nodes = utils.KeyedSort(nodeIds, nodes) bound = bounds.BoundingBox(lbound, ubound) indices = bound.UsedDimIndices() dim = len(indices) if dim < 3: nodes = [[coord[index] for index in indices] for coord in nodes] mesh = meshes.Mesh(dim) mesh.AddNodeCoords(nodes) # Read the Elements section line = ReadNonCommentLine(fileHandle) assert(line == "$Elements") line = ReadNonCommentLine(fileHandle) nEles = int(line) i = 0 while i < nEles: iArr = array.array("i") iArr.fromfile(fileHandle, 3) if swap: iArr.byteswap() typeId = iArr[0] nSubEles = iArr[1] nIds = iArr[2] type = GmshElementType(gmshElementTypeId = typeId) for j in range(nSubEles): iArr = array.array("i") iArr.fromfile(fileHandle, 1 + nIds + type.GetNodeCount()) if swap: iArr.byteswap() eleId = iArr[0] assert(eleId > 0) ids = iArr[1:1 + nIds] nodes = FromGmshNodeOrder(utils.OffsetList(iArr[-type.GetNodeCount():], -1), type) element = elements.Element(nodes, ids) if type.GetDim() == dim - 1: mesh.AddSurfaceElement(element) elif type.GetDim() == dim: mesh.AddVolumeElement(element) else: debug.deprint("Warning: Element of type " + str(type) + " encountered in " + str(dim) + " dimensions") i += nSubEles assert(i == nEles) line = ReadNonCommentLine(fileHandle) assert(line == "$EndElements") elif fileType == 0: # ASCII format line = ReadNonCommentLine(fileHandle) assert(line == "$EndMeshFormat") # Read the Nodes section line = ReadNonCommentLine(fileHandle) assert(line == "$Nodes") line = ReadNonCommentLine(fileHandle) nNodes = int(line) # Assume dense node IDs, but not necessarily ordered seenNode = [False for i in range(nNodes)] nodeIds = [] nodes = [] lbound = [calc.Inf() for i in range(3)] ubound = [-calc.Inf() for i in range(3)] for i in range(nNodes): line = ReadNonCommentLine(fileHandle) lineSplit = line.split() assert(len(lineSplit) == 4) nodeId = int(lineSplit[0]) coord = [float(comp) for comp in lineSplit[1:]] assert(nodeId > 0) assert(not seenNode[nodeId - 1]) seenNode[nodeId - 1] = True nodeIds.append(nodeId) nodes.append(coord) for j in range(3): lbound[j] = min(lbound[j], coord[j]) ubound[j] = max(ubound[j], coord[j]) line = ReadNonCommentLine(fileHandle) assert(line == "$EndNodes") nodes = utils.KeyedSort(nodeIds, nodes) bound = bounds.BoundingBox(lbound, ubound) indices = bound.UsedDimIndices() dim = len(indices) if dim < 3: nodes = [[coord[index] for index in indices] for coord in nodes] mesh = meshes.Mesh(dim) mesh.AddNodeCoords(nodes) # Read the Elements section line = ReadNonCommentLine(fileHandle) assert(line == "$Elements") line = ReadNonCommentLine(fileHandle) nEles = int(line) for i in range(nEles): line = ReadNonCommentLine(fileHandle) lineSplit = line.split() assert(len(lineSplit) > 3) eleId = int(lineSplit[0]) assert(eleId > 0) typeId = int(lineSplit[1]) nIds = int(lineSplit[2]) type = GmshElementType(gmshElementTypeId = typeId) ids = [int(id) for id in lineSplit[3:3 + nIds]] nodes = FromGmshNodeOrder([int(node) - 1 for node in lineSplit[-type.GetNodeCount():]], type) element = elements.Element(nodes, ids) if type.GetDim() == dim - 1: mesh.AddSurfaceElement(element) elif type.GetDim() == dim: mesh.AddVolumeElement(element) else: debug.deprint("Warning: Element of type " + str(type) + " encountered in " + str(dim) + " dimensions") line = ReadNonCommentLine(fileHandle) assert(line == "$EndElements") # Ignore all remaining sections else: raise Exception("File type " + str(fileType) + " not recognised") fileHandle.close() if hasHalo: # Read the .halo file debug.dprint("Reading .halo file") if mesh_halos.HaloIOSupport(): halos = mesh_halos.ReadHalos(basename + ".halo") mesh.SetHalos(halos) else: debug.deprint("Warning: No .halo I/O support") return mesh
def ReadBinaryMshV4(fileHandle, dataSize): if dataSize == 4: sizeFormat = "i" elif dataSize == 8: sizeFormat = "l" else: raise Exception("Unrecognised size_t size " + str(dataSize)) swap = ByteSwap(fileHandle) line = ReadNonCommentLine(fileHandle) assert (line == "$EndMeshFormat") # skip ahead to Nodes section (possibly bypassing Entities) while line != "$Nodes": line = ReadNonCommentLine(fileHandle) assert (line == "$Nodes") # numEntityBlock(size_t) numNodes(size_t) # minNodeTag(size_t) maxNodeTag(size_t) # # entityDim(int) entityTag(int) parametric(int) numNodes(size_t) # # nodeTag(size_t) ... # x(double) y(double) z(double) ... # ... sArr = array.array(sizeFormat) sArr.fromfile(fileHandle, 4) if swap: sArr.byteswap() numBlocks = sArr[0] numNodes = sArr[1] # assume dense nodes (we can check using the min/max id fields) seenNode = [False] * numNodes nodeIds = [] nodes = [] lbound = [calc.Inf() for i in range(3)] ubound = [-calc.Inf() for i in range(3)] for b in range(numBlocks): iArr = array.array("i") sArr = array.array(sizeFormat) iArr.fromfile(fileHandle, 3) sArr.fromfile(fileHandle, 1) if swap: iArr.byteswap() sArr.byteswap() subNodes = sArr[0] tagArr = array.array(sizeFormat) tagArr.fromfile(fileHandle, subNodes) if swap: tagArr.byteswap() for i in range(subNodes): rArr = array.array("d") rArr.fromfile(fileHandle, 3) if swap: rArr.byteswap() nodeId = tagArr[i] coord = rArr assert (nodeId > 0) assert (not seenNode[nodeId - 1]) seenNode[nodeId - 1] = True nodeIds.append(nodeId) nodes.append(coord) for j in range(3): lbound[j] = min(lbound[j], coord[j]) ubound[j] = max(ubound[j], coord[j]) line = ReadNonCommentLine(fileHandle) assert (line == "$EndNodes") nodes = utils.KeyedSort(nodeIds, nodes) bound = bounds.BoundingBox(lbound, ubound) indices = bound.UsedDimIndices() dim = len(indices) if dim < 3: nodes = [[coord[index] for index in indices] for coord in nodes] mesh = meshes.Mesh(dim) mesh.AddNodeCoords(nodes) # read the Elements section line = ReadNonCommentLine(fileHandle) assert (line == "$Elements") # numEntityBlocks(size_t) numElements(size_t) # minElementTag(size_t) maxElementTag(size_t) # # entityDim(int) entityTag(int) elementType(int) numElems(size_t) # elementTag(size_t) nodeTag(size_t) ... # ... # ... sArr = array.array(sizeFormat) sArr.fromfile(fileHandle, 4) if swap: sArr.byteswap() numEntities = sArr[0] numElems = sArr[1] for i in range(numEntities): iArr = array.array("i") sArr = array.array(sizeFormat) iArr.fromfile(fileHandle, 3) sArr.fromfile(fileHandle, 1) if swap: iArr.byteswap() sArr.byteswap() entityDim = iArr[0] entityTag = iArr[1] elementType = iArr[2] elemsInBlock = sArr[0] type = GmshElementType(gmshElementTypeId=elementType) for j in range(elemsInBlock): sArr = array.array(sizeFormat) sArr.fromfile(1 + type.GetNodeCount()) if swap: sArr.byteswap() ids = [entityTag, sArr[0]] nodes = FromGmshNodeOrder(utils.OffsetList(sArr[1:], -1), type) element = elements.Element(nodes, ids) if type.GetDim() == dim - 1: mesh.AddSurfaceElement(element) elif type.GetDim() == dim: mesh.AddVolumeElement(element) else: debug.deprint("Warning: Element of type " + str(type) + " encountered in " + str(dim) + " dimensions") line = ReadNonCommentLine(fileHandle) assert (line == "$EndElements") return mesh
def ReadBinaryMshV2(fileHandle, dataSize): if dataSize == 4: realFormat = "f" elif dataSize == 8: realFormat = "d" else: raise Exception("Unrecognised real size " + str(dataSize)) swap = ByteSwap(fileHandle) line = ReadNonCommentLine(fileHandle) assert (line == "$EndMeshFormat") # Read the Nodes section (no PhysicalNames section in binary) line = ReadNonCommentLine(fileHandle) assert (line == "$Nodes") # number-of-nodes # node-number x-coord y-coord z-coord # ... line = ReadNonCommentLine(fileHandle) nNodes = int(line) # Assume dense node IDs, but not necessarily ordered seenNode = [False for i in range(nNodes)] nodeIds = [] nodes = [] lbound = [calc.Inf() for i in range(3)] ubound = [-calc.Inf() for i in range(3)] for i in range(nNodes): iArr = array.array("i") rArr = array.array(realFormat) iArr.fromfile(fileHandle, 1) rArr.fromfile(fileHandle, 3) if swap: iArr.byteswap() rArr.byteswap() nodeId = iArr[0] coord = rArr assert (nodeId > 0) assert (not seenNode[nodeId - 1]) seenNode[nodeId - 1] = True nodeIds.append(nodeId) nodes.append(coord) for j in range(3): lbound[j] = min(lbound[j], coord[j]) ubound[j] = max(ubound[j], coord[j]) line = ReadNonCommentLine(fileHandle) assert (line == "$EndNodes") nodes = utils.KeyedSort(nodeIds, nodes) bound = bounds.BoundingBox(lbound, ubound) indices = bound.UsedDimIndices() dim = len(indices) if dim < 3: nodes = [[coord[index] for index in indices] for coord in nodes] mesh = meshes.Mesh(dim) mesh.AddNodeCoords(nodes) # Read the Elements section line = ReadNonCommentLine(fileHandle) assert (line == "$Elements") # number-of-elements # element-header-binary # element-binary # ... # where element-header-binary is: elm-type num-elm num-tags # where element-binary is: # num-elm * (4 + num-tags*4 + node-num*4) # node-num physical-tag elementary-tag node-nums ... line = ReadNonCommentLine(fileHandle) nEles = int(line) i = 0 while i < nEles: iArr = array.array("i") iArr.fromfile(fileHandle, 3) if swap: iArr.byteswap() typeId = iArr[0] nSubEles = iArr[1] nIds = iArr[2] type = GmshElementType(gmshElementTypeId=typeId) for j in range(nSubEles): iArr = array.array("i") iArr.fromfile(fileHandle, 1 + nIds + type.GetNodeCount()) if swap: iArr.byteswap() eleId = iArr[0] assert (eleId > 0) ids = iArr[1:1 + nIds] nodes = FromGmshNodeOrder( utils.OffsetList(iArr[-type.GetNodeCount():], -1), type) element = elements.Element(nodes, ids) if type.GetDim() == dim - 1: mesh.AddSurfaceElement(element) elif type.GetDim() == dim: mesh.AddVolumeElement(element) else: debug.deprint("Warning: Element of type " + str(type) + " encountered in " + str(dim) + " dimensions") i += nSubEles assert (i == nEles) line = ReadNonCommentLine(fileHandle) assert (line == "$EndElements") return mesh
def ReadHalos(filename): """ Read a Fluidity .halo file """ xmlFile = xml.dom.minidom.parse(filename) halosRootEle = xmlFile.getElementsByTagName("halos") assert(len(halosRootEle) == 1) halosRootEle = halosRootEle[0] haloProcess = int(halosRootEle.attributes["process"].nodeValue) nprocs = int(halosRootEle.attributes["nprocs"].nodeValue) halosEle = halosRootEle.getElementsByTagName("halo") halos = Halos(process = haloProcess, nProcesses = nprocs) for haloEle in halosEle: try: level = int(haloEle.attributes["level"].nodeValue) except KeyError: # Backwards compatibility level = int(haloEle.attributes["tag"].nodeValue) n_private_nodes = int(haloEle.attributes["n_private_nodes"].nodeValue) halo = Halo(process = haloProcess, nProcesses = nprocs, nOwnedNodes = n_private_nodes) processes = [] haloDataEles = haloEle.getElementsByTagName("halo_data") for haloDataEle in haloDataEles: process = int(haloDataEle.attributes["process"].nodeValue) assert(process >= 0 and process < nprocs) assert(not process in processes) processes.append(process) sendEle = haloDataEle.getElementsByTagName("send") assert(len(sendEle) == 1) sendEle = sendEle[0] sendEleChildren = sendEle.childNodes sends = None for child in sendEleChildren: if child.nodeType == child.TEXT_NODE: sends = map(int, child.nodeValue.split()) break if not sends is None: if level > 0: halo.SetSends(utils.OffsetList(sends, -1), process = process) else: halo.SetSends(sends, process = process) receiveEle = haloDataEle.getElementsByTagName("receive") assert(len(receiveEle) == 1) receiveEle = receiveEle[0] receiveEleChildren = receiveEle.childNodes receives = None for child in receiveEleChildren: if child.nodeType == child.TEXT_NODE: receives = map(int, child.nodeValue.split()) break if not receives is None: if level > 0: halo.SetReceives(utils.OffsetList(receives, -1), process = process) else: halo.SetReceives(receives, process = process) if level > 0: assert(not halos.HasNodeHalo(level)) halos.SetNodeHalo(level, halo) else: assert(not halos.HasElementHalo(-level)) halos.SetElementHalo(-level, halo) return halos