Exemplo n.º 1
0
def DetectorArrays(stat):
    """
  Return a dictionary of detector array lists contained in the supplied stat
  """

    # Detector array data is divided in the stat into one path per array entry. We
    # want to collapse this into a dictionary of one path per array. This involves
    # lots of horrible parsing of stat paths.

    # Find all detector array names and the paths for each entry in the array
    arrays = {}  # The arrays
    notArrayNames = []  # List of candidate array names that are, in fact, not
    # detector array names
    for path in stat.PathLists():
        if isinstance(stat[stat.FormPathFromList(path)], Stat):
            # This isn't a leaf node
            continue

        # Look for an array marker in the path. This appears as:
        #   [path]%arrayname_index[%component]
        # and for coordinates as:
        #   arrayname_index[%component]

        if len(path) >= 2 and path[1] == "position":
            # This might be a coordinate entry

            firstKey = path[0]
            keySplit = firstKey.split("_")
            # We have an entry in an array if:
            #   1. We have more than one entry in the split
            #   2. The final entry in the split contains one of zero (for scalars) or
            #      two (for vector and tensors) array path delimiters
            #   3. The first stat path split of the final entry is an integer (the
            #      index)
            if len(keySplit) <= 1 \
              or not len(stat.SplitPath(keySplit[-1])) in [1, 2] \
              or not utils.IsIntString(stat.SplitPath(keySplit[-1])[0]):
                # This definitely can't be an entry in a detector array
                continue

            # OK, we have something that looks a bit like an entry for a detector
            # array

            # Find the array name and the index for this entry
            arrayName = utils.FormLine(
                [utils.FormLine(keySplit[:-1], delimiter="_", newline=False)] +
                path[1:],
                delimiter=stat.GetDelimiter(),
                newline=False)
            index = int(keySplit[-1])
        else:
            # This might be a field entry

            finalKey = path[-1]
            keySplit = finalKey.split("_")
            # We have an entry in an array if:
            #   1. We have more than one entry in the split
            #   2. The final entry in the split contains one of zero or one (for field
            #      components) array path delimiters
            #   3. The first stat path split of the final entry is an integer (the
            #      index)
            if len(keySplit) <= 1 \
              or not len(stat.SplitPath(keySplit[-1])) in [1, 2] \
              or not utils.IsIntString(stat.SplitPath(keySplit[-1])[0]):
                # This definitely can't be an entry in a detector array
                continue

            # OK, we have something that looks a bit like an entry for a detector
            # array

            # Find the array name and the index for this entry
            arrayName = utils.FormLine(
                path[:-1] +
                [utils.FormLine(keySplit[:-1], delimiter="_", newline=False)],
                delimiter=stat.GetDelimiter(),
                newline=False)
            if len(stat.SplitPath(keySplit[-1])) > 1:
                # This array name references a field component

                # We need to append the component to the array name. This needs to be
                # added to the last but one part of the stat path (the final entry is the
                # name of this detector array as configured in Fluidity).
                splitName = stat.SplitPath(arrayName)
                splitName[-2] = stat.FormPath(splitName[-2],
                                              stat.SplitPath(keySplit[-1])[1])
                arrayName = stat.FormPathFromList(splitName)
                index = int(stat.SplitPath(keySplit[-1])[0])
            else:
                # This array name references a field

                index = int(keySplit[-1])

        if arrayName in notArrayNames:
            # We've already discovered that this candidate array name isn't in fact a
            # detector array
            continue

        if index <= 0:
            # This isn't a valid index

            # This candidate array name isn't in fact a detector array
            notArrayNames.append(arrayName)
            if arrayName in arrays:
                arrays.remove(arrayName)
            continue
        if arrayName in arrays and index in arrays[arrayName]:
            # We've seen this index more than once for this array name

            # This candidate apparent array name isn't in fact a detector array
            notArrayNames.append(arrayName)
            arrays.remove(arrayName)
            continue

        if arrayName in arrays:
            arrays[arrayName][index] = stat[stat.FormPathFromList(path)]
        else:
            # This is a new array name
            arrays[arrayName] = {}
            arrays[arrayName][index] = stat[stat.FormPathFromList(path)]

    # Convert the dictionaries of data to lists, and check for consecutive
    # indices
    for name in arrays:
        array = arrays[name]
        indices = array.keys()
        data = [array[index] for index in indices]
        indices, data = utils.KeyedSort(indices, data, returnSortedKeys=True)
        arrays[name] = numpy.array(data)

        for i, index in enumerate(indices):
            if not i + 1 == index:
                # The indices are not consecutive from one. After all the hard work
                # above, we still have an array name that isn't in fact a detector
                # array.
                arrays.remove(name)
                break

    # Fantastic! We have our detectors dictionary!
    debug.dprint("Detector keys:")
    debug.dprint(arrays.keys())

    return arrays
Exemplo n.º 2
0
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
Exemplo n.º 3
0
def JoinStat(*args):
    """
  Joins a series of stat files together. Useful for combining checkpoint .stat
  files. Selects data in later stat files over earlier stat files. Assumes
  data in stat files are sorted by ElapsedTime.
  """

    nStat = len(args)
    assert (nStat > 0)
    times = [stat["ElapsedTime"] for stat in args]

    startT = [t[0] for t in times]
    permutation = utils.KeyedSort(startT, range(nStat))
    stats = [args[index] for index in permutation]
    startT = [startT[index] for index in permutation]
    times = [times[index] for index in permutation]

    endIndices = numpy.array([len(time) for time in times], dtype=int)
    for i, t in enumerate(times[:-1]):
        for j, time in enumerate(t):
            if calc.AlmostEquals(startT[i + 1], time, tolerance=1.0e-6):
                endIndices[i] = max(j - 1, 0)
                break
            elif startT[i + 1] < time:
                endIndices[i] = j
                break
    debug.dprint("Time ranges:")
    if len(times) > 0:
        for i in range(nStat):
            debug.dprint((startT[i], times[i][endIndices[i] - 1]))
    else:
        debug.dprint("No data")

    dataIndices = numpy.empty(len(args) + 1, dtype=int)
    dataIndices[0] = 0
    for i, index in enumerate(endIndices):
        dataIndices[i + 1] = dataIndices[i] + index

    stat = stats[0]
    data = {}
    for key in stat.keys():
        arr = stat[key]
        shape = list(arr.shape)
        shape[0] = dataIndices[-1]
        data[key] = numpy.empty(shape, dtype=arr.dtype)
        data[key][:dataIndices[1]] = arr[:endIndices[0]]
        data[key][dataIndices[1]:] = calc.Nan()
    delimiter = stat.GetDelimiter()

    for i in range(1, nStat):
        stat = stats[i]
        for key in stat.keys():
            arr = stat[key]
            if not key in data:
                shape = list(arr.shape)
                shape[0] = dataIndices[-1]
                data[key] = numpy.empty(shape, dtype=arr.dtype)
                data[key][:dataIndices[i]] = calc.Nan()
                data[key][dataIndices[i + 1]:] = calc.Nan()
            data[key][dataIndices[i]:dataIndices[i + 1]] = arr[:endIndices[i]]

    output = Stat(delimiter=delimiter)
    for key in data.keys():
        output[key] = numpy.array(data[key])

    return output
Exemplo n.º 4
0
def ReadAsciiMshV4(fileHandle):
    line = ReadNonCommentLine(fileHandle)
    assert (line == "$EndMeshFormat")

    # skip to the Nodes section
    while line != "$Nodes":
        line = ReadNonCommentLine(fileHandle)
    assert (line == "$Nodes")

    line = ReadNonCommentLine(fileHandle)
    lineSplit = line.split()
    numBlocks = int(lineSplit[0])
    numNodes = int(lineSplit[1])
    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):
        line = ReadNonCommentLine(fileHandle)
        lineSplit = line.split()
        subNodes = int(lineSplit[3])
        tagArr = [int(ReadNonCommentLine(fileHandle)) for i in range(subNodes)]
        for i in range(subNodes):
            line = ReadNonCommentLine(fileHandle)
            lineSplit = line.split()
            assert (len(lineSplit) == 3)

            nodeId = tagArr[i]
            coord = [float(comp) for comp in lineSplit]
            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)
    lineSplit = line.split()
    numEntities = int(lineSplit[0])
    numElems = int(lineSplit[1])
    for i in range(numEntities):
        line = ReadNonCommentLine(fileHandle)
        lineSplit = line.split()

        entityDim = int(lineSplit[0])
        entityTag = int(lineSplit[1])
        elementType = int(lineSplit[2])
        elemsInBlock = int(lineSplit[3])

        type = GmshElementType(gmshElementTypeId=elementType)

        for j in range(elemsInBlock):
            line = ReadNonCommentLine(fileHandle)
            lineSplit = line.split()
            assert (len(lineSplit) == 1 + type.GetNodeCount())

            ids = [entityTag, int(lineSplit[0])]
            nodes = FromGmshNodeOrder(
                [int(node) - 1 for node in lineSplit[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
Exemplo n.º 5
0
def ReadAsciiMshV2(fileHandle):
    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")

    return mesh
Exemplo n.º 6
0
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
Exemplo n.º 7
0
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