Ejemplo n.º 1
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(
         self, module_manager,
         vtk.vtkXMLPUnstructuredGridWriter(), 'Writing vtkXMLPUnstructuredGrid.',
         ('vtkXMLPUnstructuredGrid',), (),
         replaceDoc=True,
         inputFunctions=None, outputFunctions=None)
Ejemplo n.º 2
0
def write_ugrid(data, basename, path='.'):
    """ Parallel safe data object writer"""

    comm = MPI.COMM_WORLD
    rank = comm.Get_rank()
    size = comm.Get_size()

    if size == 1:

        ### serial case

        filename = basename + '.vtu'

        writer = vtk.vtkXMLUnstructuredGridWriter()
        writer.SetFileName(path + '/' + filename)
        if vtk.vtkVersion.GetVTKMajorVersion() < 6:
            writer.SetInput(data)
        else:
            writer.SetInputData(data)
        writer.Write()

        return

    ## In parallel we make a directory and dump the files into it

    try:
        os.makedirs(path + '/' + basename)
    except OSError as exception:
        if exception.errno != errno.EEXIST:
            raise

    filename = basename + '.pvtu'

    writer = vtk.vtkXMLPUnstructuredGridWriter()
    writer.SetNumberOfPieces(size)
    writer.SetStartPiece(rank)
    writer.SetEndPiece(rank)

    writer.SetFileName(path + '/' + basename + '/' + filename)
    if vtk.vtkVersion.GetVTKMajorVersion() < 6:
        writer.SetInput(data)
    else:
        writer.SetInputData(data)
    writer.Write()

    if rank == 0:
        os.rename(path + '/' + basename + '/' + filename,
                  path + '/' + filename)

        stream = open(path + '/' + filename).read()
        stream = stream.replace('<Piece Source="' + basename,
                                '<Piece Source="' + basename + '/' + basename)
        outfile = open(path + '/' + filename, 'w')
        outfile.write(stream)
        outfile.flush()
        outfile.close()

    return
Ejemplo n.º 3
0
  def Write(self, filename=[]):
    """Writes the grid to a vtu file.
    If no filename is specified it will use the name of the file originally
    read in, thus overwriting it!
    """
    if filename==[]:
      filename=self.filename
    if filename is None:
      raise Exception("No file supplied")
    if filename.endswith('pvtu'):
      gridwriter=vtk.vtkXMLPUnstructuredGridWriter()
    else:
      gridwriter=vtk.vtkXMLUnstructuredGridWriter()

    gridwriter.SetFileName(filename)
    gridwriter.SetInputData(self.ugrid)
    gridwriter.Write()
Ejemplo n.º 4
0
  def Write(self, filename=[]):
    """Writes the grid to a vtu file.

    If no filename is specified it will use the name of the file originally
    read in, thus overwriting it!
    """
    if filename==[]:
      filename=self.filename
    if filename is None:
      raise Exception("No file supplied")
    if filename.endswith('pvtu'):
      gridwriter=vtk.vtkXMLPUnstructuredGridWriter()
    else:
      gridwriter=vtk.vtkXMLUnstructuredGridWriter()

    gridwriter.SetFileName(filename)
    gridwriter.SetInput(self.ugrid)
    gridwriter.Write()
Ejemplo n.º 5
0
    def psave(self, file_name, mpi_size, mpi_range):
        self.file_name = os.path.splitext(file_name)[0]

        file_name_out = self.file_name + "_%d" % mpi_range + ".vtu"
        writer = vtk.vtkXMLUnstructuredGridWriter()
        writer.SetFileName(file_name_out)
        if vtk.VTK_MAJOR_VERSION <= 5:
            writer.SetInput(self.reader.GetOutput())
        else:
            writer.SetInputData(self.reader.GetOutput())
        writer.Write()

        if (mpi_range == 0):
            pwriter = vtk.vtkXMLPUnstructuredGridWriter()
            pwriter.SetFileName(self.file_name + ".pvtu")
            pwriter.SetNumberOfPieces(mpi_size)

            if vtk.VTK_MAJOR_VERSION <= 5:
                pwriter.SetInput(self.reader.GetOutput())
            else:
                pwriter.SetInputData(self.reader.GetOutput())

            pwriter.Write()
            print "|_Vtk_writer.writer file: \'%s\' " % (file_name_out)
Ejemplo n.º 6
0
                os.remove(VTK_TEMP_DIR + "/%s_%d.%s" % (dataType, i, ext))
            else:
                os.remove(VTK_TEMP_DIR + "/%s/%s_%d.%s" %
                          (dataType, dataType, i, ext))

    assert da2.GetValue(0) == numTris


TestDataType('ImageData', vtk.vtkXMLPImageDataReader(),
             vtk.vtkXMLPImageDataWriter(), 'vti', 4924)
TestDataType('RectilinearGrid', vtk.vtkXMLPRectilinearGridReader(),
             vtk.vtkXMLPRectilinearGridWriter(), 'vtr', 4924)
TestDataType('StructuredGrid', vtk.vtkXMLPStructuredGridReader(),
             vtk.vtkXMLPStructuredGridWriter(), 'vts', 4924)
TestDataType('UnstructuredGrid', vtk.vtkXMLPUnstructuredGridReader(),
             vtk.vtkXMLPUnstructuredGridWriter(), 'vtu', 11856)

# Test writers with UseSubdirectory on
TestDataType('ImageData',
             vtk.vtkXMLPImageDataReader(),
             vtk.vtkXMLPImageDataWriter(),
             'vti',
             4924,
             useSubdir=True)
TestDataType('RectilinearGrid',
             vtk.vtkXMLPRectilinearGridReader(),
             vtk.vtkXMLPRectilinearGridWriter(),
             'vtr',
             4924,
             useSubdir=True)
TestDataType('StructuredGrid',
Ejemplo n.º 7
0
def write(
          filename,
          vtk_mesh,
          point_data = None,
          cell_data = None,
          field_data = None
          ):
    '''Writes mesh together with data to a file.

    :params filename: File to write to.
    :type filename: str

    :params point_data: Named additional point data to write to the file.
    :type point_data: dict
    '''
    import os

    extension = os.path.splitext(filename)[1]
    # add point data
    is_exodus_format = extension in [ '.ex2', '.exo', '.e' ]
    if point_data:
        for name, data in point_data.iteritems():
            new_name = name
            # There is a naming inconsistency in VTK when it comes to
            # multivectors in Exodus files:
            # If a vector 'v' has two components, they are called 'v_r',
            # 'v_z' (note the underscore), if it has three, then they are
            # called 'vx', 'vy', 'vz'.
            # Make this consistent by appending an underscore if needed.
            # Note that for VTK files, this problem does not occur since
            # the label of a vector is always stored as a string.
            is_3d_vector = len(data.shape) == 2 and data.shape[1] == 3
            if is_exodus_format and is_3d_vector and name[-1] != '_':
                new_name += '_'
            vtk_mesh.GetPointData() \
                    .AddArray(_create_vtkarray(data, new_name))

    # add cell data
    if cell_data:
        for key, value in cell_data.iteritems():
            vtk_mesh.GetCellData() \
                    .AddArray(_create_vtkarray(value, key))

    # add field data
    if field_data:
        for key, value in field_data.iteritems():
            vtk_mesh.GetFieldData() \
                    .AddArray(_create_vtkarray(value, key))

    import re
    extension = os.path.splitext(filename)[1]
    if extension == '.vtu': # VTK XML format
        from vtk import vtkXMLUnstructuredGridWriter
        writer = vtkXMLUnstructuredGridWriter()
    elif extension == '.pvtu': # parallel VTK XML format
        from vtk import vtkXMLPUnstructuredGridWriter
        writer = vtkXMLPUnstructuredGridWriter()
    elif extension == '.vtk': # classical VTK format
        from vtk import vtkUnstructuredGridWriter
        writer = vtkUnstructuredGridWriter()
        writer.SetFileTypeToASCII()
    elif extension == '.xmf': # XDMF format
        from vtk import vtkXdmfWriter
        writer = vtkXdmfWriter()
    elif extension in [ '.ex2', '.exo', '.e' ]: # Exodus II format
        from vtk import vtkExodusIIWriter
        writer = vtkExodusIIWriter()
        # If the mesh contains vtkModelData information, make use of it
        # and write out all time steps.
        writer.WriteAllTimeStepsOn()
    elif re.match('[^\.]*\.e\.\d+\.\d+', filename):
        # TODO handle parallel I/O with vtkPExodusIIWriter
        from vtk import vtkExodusIIWriter
        writer = vtkExodusIIWriter()
        # If the mesh contains vtkModelData information, make use of it
        # and write out all time steps.
        writer.WriteAllTimeStepsOn()
    else:
        raise IOError( 'Unknown file type \'%s\'.' % filename )

    writer.SetFileName( filename )

    writer.SetInputData( vtk_mesh )

    writer.Write()

    return
    da.InsertNextValue(ntris)

    da2 = vtk.vtkIntArray()
    da2.SetNumberOfTuples(1)
    contr.AllReduce(da, da2, vtk.vtkCommunicator.SUM_OP)

    if rank == 0:
        print(da2.GetValue(0))
        import os
        os.remove(filename)
        for i in range(npieces):
            if not useSubdir:
                os.remove(VTK_TEMP_DIR + "/%s_%d.%s" % (dataType, i, ext))
            else:
                os.remove(VTK_TEMP_DIR + "/%s/%s_%d.%s" %(dataType, dataType, i, ext))

    assert da2.GetValue(0) == numTris

TestDataType('ImageData', vtk.vtkXMLPImageDataReader(), vtk.vtkXMLPImageDataWriter(), 'vti', 4924)
TestDataType('RectilinearGrid', vtk.vtkXMLPRectilinearGridReader(), vtk.vtkXMLPRectilinearGridWriter(), 'vtr', 4924)
TestDataType('StructuredGrid', vtk.vtkXMLPStructuredGridReader(), vtk.vtkXMLPStructuredGridWriter(), 'vts', 4924)
TestDataType('UnstructuredGrid', vtk.vtkXMLPUnstructuredGridReader(), vtk.vtkXMLPUnstructuredGridWriter(), 'vtu', 11856)
TestDataType('Table', vtk.vtkXMLPTableReader(), vtk.vtkXMLPTableWriter(), 'vtt', 18522)

# Test writers with UseSubdirectory on
TestDataType('ImageData', vtk.vtkXMLPImageDataReader(), vtk.vtkXMLPImageDataWriter(), 'vti', 4924, useSubdir=True)
TestDataType('RectilinearGrid', vtk.vtkXMLPRectilinearGridReader(), vtk.vtkXMLPRectilinearGridWriter(), 'vtr', 4924, useSubdir=True)
TestDataType('StructuredGrid', vtk.vtkXMLPStructuredGridReader(), vtk.vtkXMLPStructuredGridWriter(), 'vts', 4924, useSubdir=True)
TestDataType('UnstructuredGrid', vtk.vtkXMLPUnstructuredGridReader(), vtk.vtkXMLPUnstructuredGridWriter(), 'vtu', 11856, useSubdir=True)
TestDataType('Table', vtk.vtkXMLPTableReader(), vtk.vtkXMLPTableWriter(), 'vtt', 18522, useSubdir=True)
Ejemplo n.º 9
0
def write_vtu(filename, fns, index = None, t = None):
    """
    Write the supplied Function or Function s to a vtu or pvtu file with the
    supplied filename base. If the Function s are defined on multiple function
    spaces then separate output files are written for each function space. The
    optional integer index can be used to add an index to the output filenames.
    If t is supplied then a scalar field equal to t and with name "time" is added
    to the output files.

    All Function s should be on the same mesh and have unique names. In 1D all
    Function s must have Lagrange basis functions (continuous or discontinous)
    with degree 0 to 3. In 2D and 3D all Function s must have Lagrange basis
    functions (continuous or discontinuous) with degree 0 to 2.
    """

    if isinstance(fns, dolfin.Function):
        return write_vtu(filename, [fns], index = index, t = t)
    if not isinstance(filename, str):
        raise InvalidArgumentException("filename must be a string")
    if not isinstance(fns, list):
        raise InvalidArgumentException("fns must be a Function or a list of Function s")
    if len(fns) == 0:
        raise InvalidArgumentException("fns must include at least one Function")
    for fn in fns:
        if not isinstance(fn, dolfin.Function):
            raise InvalidArgumentException("fns must be a Function or a list of Function s")
    if not index is None and not isinstance(index, int):
        raise InvalidArgumentException("index must be an integer")
    if not t is None and not isinstance(t, (float, dolfin.Constant)):
        raise InvalidArgumentException("t must be a float or Constant")

    mesh = fns[0].function_space().mesh()
    dim = mesh.geometry().dim()
    if not dim in [1, 2, 3]:
        raise NotImplementedException("Mesh dimension %i not supported by write_vtu" % dim)

    def expand_sub_fns(fn):
        n_sub_spaces = fn.function_space().num_sub_spaces()
        if n_sub_spaces > 1:
            fns = fn.split(deepcopy = True)
            for i, sfn in enumerate(copy.copy(fns)):
                sfn.rename("%s_%i" % (fn.name(), i + 1), "%s_%i" % (fn.name(), i + 1))
                if sfn.function_space().num_sub_spaces() > 0:
                    fns.remove(sfn)
                    fns += expand_sub_fns(sfn)
            return fns
        elif n_sub_spaces == 1:
            e = fn.function_space().ufl_element().extract_component(0)[1]
            space = dolfin.FunctionSpace(mesh, e.family(), e.degree())
            sfn = dolfin.Function(space, name = "%s_1" % fn.name())
            sfn.vector()[:] = fn.vector()
            return [sfn]
        else:
            return [fn]

    nfns = []
    for i, fn in enumerate(fns):
        space = fn.function_space()
        if not space.mesh().id() == mesh.id():
            raise InvalidArgumentException("Require exactly one mesh in write_vtu")
        n_sub_spaces = space.num_sub_spaces()
        nfns += expand_sub_fns(fn)
    fns = nfns;  del(nfns)

    spaces = []
    lfns = OrderedDict()
    for fn in fns:
        space = fn.function_space()
        assert(space.mesh().id() == mesh.id())
        e = space.ufl_element()
        assert(e.cell().geometric_dimension() == dim)
        assert(e.cell().topological_dimension() == dim)
        if (not e.family() in ["Lagrange", "Discontinuous Lagrange"]
            or not dim in [1, 2, 3]
            or (dim == 1 and not e.degree() in [1, 2, 3])
            or (dim in [2, 3] and not e.degree() in [1, 2])) and \
          (not e.family() == "Discontinuous Lagrange"
            or not dim in [1, 2, 3]
            or not e.degree() == 0):
            raise NotImplementedException('Element family "%s" with degree %i in %i dimension(s) not supported by write_vtu' % (e.family(), e.degree(), dim))
        if e in lfns:
            lfns[e].append(fn)
        else:
            spaces.append(space)
            lfns[e] = [fn]
    fns = lfns

    if len(spaces) == 1:
        filenames = [filename]
    else:
        filenames = []
        for space in spaces:
            e = space.ufl_element()
            lfilename = "%s_P%i" % (filename, e.degree())
            if e.family() == "Discontinuous Lagrange":
                lfilename = "%s_DG" % lfilename
            filenames.append(lfilename)

    if not t is None:
        for space in spaces:
            lt = dolfin.Function(space, name = "time")
            if isinstance(t, float):
                lt.vector()[:] = t
            else:
                lt.assign(t)
            fns[space.ufl_element()].append(lt)

    names = {e:[] for e in fns}
    for e in fns:
        for fn in fns[e]:
            name = fn.name()
            if name in names[e]:
                raise InvalidArgumentException("Duplicate Function name: %s" % name)
            names[e].append(name)

    for filename, space in zip(filenames, spaces):
        e = space.ufl_element()
        degree = e.degree()

        vtu = vtk.vtkUnstructuredGrid()

        dof = space.dofmap()
        nodes = set()
        for i in xrange(mesh.num_cells()):
            cell =  dof.cell_dofs(i)
            for node in cell:
                nodes.add(node)
        nodes = numpy.array(sorted(list(nodes)), dtype = numpy.intc)

        if degree == 0:
            xspace = dolfin.FunctionSpace(mesh, "CG", 1)
            xdof = xspace.dofmap()
            xnodes = set()
            for i in xrange(mesh.num_cells()):
                cell =  xdof.cell_dofs(i)
                for node in cell:
                    xnodes.add(node)
            xnodes = numpy.array(sorted(list(xnodes)), dtype = numpy.intc)
        else:
            xspace = space
            xdof = dof
            xnodes = nodes
        xnode_map = {node:i for i, node in enumerate(xnodes)}

        x = dolfin.interpolate(dolfin.Expression("x[0]"), xspace).vector().gather(xnodes)
        if dim > 1:
            y = dolfin.interpolate(dolfin.Expression("x[1]"), xspace).vector().gather(xnodes)
        if dim > 2:
            z = dolfin.interpolate(dolfin.Expression("x[2]"), xspace).vector().gather(xnodes)
        n = x.shape[0]

        points = vtk.vtkPoints()
        points.SetDataTypeToDouble()
        points.SetNumberOfPoints(n)
        if dim == 1:
            for i in xrange(n):
                points.SetPoint(i, x[i], 0.0, 0.0)
        elif dim == 2:
            for i in xrange(n):
                points.SetPoint(i, x[i], y[i], 0.0)
        else:
            for i in xrange(n):
                points.SetPoint(i, x[i], y[i], z[i])
        vtu.SetPoints(points)

        id_list = vtk.vtkIdList()
        if dim == 1:
            if degree in [0, 1]:
                cell_type = vtk.vtkLine().GetCellType()
                id_list.SetNumberOfIds(2)
                cell_map = None
            elif degree == 2:
                cell_type = vtk.vtkQuadraticEdge().GetCellType()
                id_list.SetNumberOfIds(3)
                cell_map = None
            else:
                cell_type = vtk.vtkCubicLine().GetCellType()
                id_list.SetNumberOfIds(4)
                cell_map = None
        elif dim == 2:
            if degree in [0, 1]:
                cell_type = vtk.vtkTriangle().GetCellType()
                id_list.SetNumberOfIds(3)
                cell_map = None
            else:
                cell_type = vtk.vtkQuadraticTriangle().GetCellType()
                id_list.SetNumberOfIds(6)
                cell_map = {0:0, 1:1, 2:2, 3:5, 4:3, 5:4}
        else:
            if degree in [0, 1]:
                cell_type = vtk.vtkTetra().GetCellType()
                id_list.SetNumberOfIds(4)
                cell_map = None
            else:
                cell_type = vtk.vtkQuadraticTetra().GetCellType()
                id_list.SetNumberOfIds(10)
                cell_map = {0:0, 1:1, 2:2, 3:3, 4:9, 5:6, 6:8, 7:7, 8:5, 9:4}
        for i in xrange(mesh.num_cells()):
            cell = xdof.cell_dofs(i)
            assert(len(cell) == id_list.GetNumberOfIds())
            if not cell_map is None:
                cell = [cell[cell_map[j]] for j in xrange(len(cell))]
            for j in xrange(len(cell)):
                id_list.SetId(j, xnode_map[cell[j]])
            vtu.InsertNextCell(cell_type, id_list)

        if degree == 0:
            for fn in fns[e]:
                if not fn.value_rank() == 0:
                    raise NotImplementException("Function rank %i not supported by write_vtu" % fn.value_rank())
                data = fn.vector().gather(nodes)
                cell_data = vtk.vtkDoubleArray()
                cell_data.SetNumberOfComponents(1)
                cell_data.SetNumberOfValues(mesh.num_cells())
                cell_data.SetName(fn.name())
                for i, datum in enumerate(data):
                    cell_data.SetValue(i, datum)
                vtu.GetCellData().AddArray(cell_data)
            vtu.GetCellData().SetActiveScalars(names[e][0])
        else:
            for fn in fns[e]:
                if not fn.value_rank() == 0:
                    raise NotImplementException("Function rank %i not supported by write_vtu" % fn.value_rank())
                data = fn.vector().gather(nodes)
                point_data = vtk.vtkDoubleArray()
                point_data.SetNumberOfComponents(1)
                point_data.SetNumberOfValues(n)
                point_data.SetName(fn.name())
                for i, datum in enumerate(data):
                    point_data.SetValue(i, datum)
                vtu.GetPointData().AddArray(point_data)
            vtu.GetPointData().SetActiveScalars(names[e][0])

        if dolfin.MPI.num_processes() > 1:
            writer = vtk.vtkXMLPUnstructuredGridWriter()
            writer.SetNumberOfPieces(dolfin.MPI.num_processes())
            writer.SetStartPiece(dolfin.MPI.process_number())
            writer.SetEndPiece(dolfin.MPI.process_number())
            ext = ".pvtu"
        else:
            writer = vtk.vtkXMLUnstructuredGridWriter()
            ext = ".vtu"
        if index is None:
            filename = "%s%s" % (filename, ext)
        else:
            filename = "%s_%i%s" % (filename, index, ext)
        writer.SetFileName(filename)
        writer.SetDataModeToAppended()
        writer.EncodeAppendedDataOff()
        writer.SetCompressorTypeToZLib()
        writer.GetCompressor().SetCompressionLevel(9)
        writer.SetBlockSize(2 ** 15)
        writer.SetInput(vtu)
        writer.Write()
        if not writer.GetProgress() == 1.0 or not writer.GetErrorCode() == 0:
            raise IOException("Failed to write vtu file: %s" % filename)

    return
Ejemplo n.º 10
0
import fluidity.diagnostics.fluiditytools as fluiditytools
import fluidity.diagnostics.vtutools as vtktools

if not len(sys.argv) == 2:
    print("Usage: genpvtu basename")
    sys.exit(1)
basename = sys.argv[1]
debug.dprint("vtu basename: " + basename)
nPieces = fluiditytools.FindMaxVtuId(basename) + 1
debug.dprint("Number of pieces: " + str(nPieces))

# Write to a temporary directory so that the first piece isn't overwritten
tempDir = tempfile.mkdtemp()

# Create the parallel writer
writer = vtk.vtkXMLPUnstructuredGridWriter()
writer.SetNumberOfPieces(nPieces)
writer.WriteSummaryFileOn()
pvtuName = basename + ".pvtu"
writer.SetFileName(os.path.join(tempDir, pvtuName))

# Load in the first piece, so that the parallel writer has something to do (and
# knows which fields we have)
pieceName = fluiditytools.VtuFilenames(basename, 0)[0]
pieceVtu = vtktools.vtu(pieceName)
if vtk.vtkVersion.GetVTKMajorVersion() <= 5:
    writer.SetInput(0, pieceVtu.ugrid)
else:
    writer.SetInputData(0, pieceVtu.ugrid)

# Write
Ejemplo n.º 11
0
import fluidity.diagnostics.fluiditytools as fluiditytools
import fluidity.diagnostics.vtutools as vtktools

if not len(sys.argv) == 2:
  print "Usage: genpvtu basename"
  sys.exit(1)
basename = sys.argv[1]
debug.dprint("vtu basename: " + basename)
nPieces = fluiditytools.FindMaxVtuId(basename) + 1
debug.dprint("Number of pieces: " + str(nPieces))

# Write to a temporary directory so that the first piece isn't overwritten
tempDir = tempfile.mkdtemp()

# Create the parallel writer
writer = vtk.vtkXMLPUnstructuredGridWriter()
writer.SetNumberOfPieces(nPieces)
writer.WriteSummaryFileOn()
pvtuName = basename + ".pvtu"
writer.SetFileName(os.path.join(tempDir, pvtuName))

# Load in the first piece, so that the parallel writer has something to do (and
# knows which fields we have)
pieceName = fluiditytools.VtuFilenames(basename, 0)[0]
pieceVtu = vtktools.vtu(pieceName)
if vtk.vtkVersion.GetVTKMajorVersion() <= 5:
  writer.SetInput(0, pieceVtu.ugrid)
else:
  writer.SetInputData(0, pieceVtu.ugrid)

# Write
Ejemplo n.º 12
0
def write_vtu(filename, fns, index=None, t=None):
    """
    Write the supplied Function or Function s to a vtu or pvtu file with the
    supplied filename base. If the Function s are defined on multiple function
    spaces then separate output files are written for each function space. The
    optional integer index can be used to add an index to the output filenames.
    If t is supplied then a scalar field equal to t and with name "time" is added
    to the output files.

    All Function s should be on the same mesh and have unique names. In 1D all
    Function s must have Lagrange basis functions (continuous or discontinous)
    with degree 0 to 3. In 2D and 3D all Function s must have Lagrange basis
    functions (continuous or discontinuous) with degree 0 to 2.
    """

    if isinstance(fns, dolfin.Function):
        return write_vtu(filename, [fns], index=index, t=t)
    if not isinstance(filename, str):
        raise InvalidArgumentException("filename must be a string")
    if not isinstance(fns, list):
        raise InvalidArgumentException(
            "fns must be a Function or a list of Function s")
    if len(fns) == 0:
        raise InvalidArgumentException(
            "fns must include at least one Function")
    for fn in fns:
        if not isinstance(fn, dolfin.Function):
            raise InvalidArgumentException(
                "fns must be a Function or a list of Function s")
    if not index is None and not isinstance(index, int):
        raise InvalidArgumentException("index must be an integer")
    if not t is None and not isinstance(t, (float, dolfin.Constant)):
        raise InvalidArgumentException("t must be a float or Constant")

    mesh = fns[0].function_space().mesh()
    dim = mesh.geometry().dim()
    if not dim in [1, 2, 3]:
        raise NotImplementedException(
            "Mesh dimension %i not supported by write_vtu" % dim)

    def expand_sub_fns(fn):
        n_sub_spaces = fn.function_space().num_sub_spaces()
        if n_sub_spaces > 1:
            fns = fn.split(deepcopy=True)
            for i, sfn in enumerate(copy.copy(fns)):
                sfn.rename("%s_%i" % (fn.name(), i + 1),
                           "%s_%i" % (fn.name(), i + 1))
                if sfn.function_space().num_sub_spaces() > 0:
                    fns.remove(sfn)
                    fns += expand_sub_fns(sfn)
            return fns
        elif n_sub_spaces == 1:
            e = fn.function_space().ufl_element().extract_component(0)[1]
            space = dolfin.FunctionSpace(mesh, e.family(), e.degree())
            sfn = dolfin.Function(space, name="%s_1" % fn.name())
            sfn.vector()[:] = fn.vector()
            return [sfn]
        else:
            return [fn]

    nfns = []
    for i, fn in enumerate(fns):
        space = fn.function_space()
        if not space.mesh().id() == mesh.id():
            raise InvalidArgumentException(
                "Require exactly one mesh in write_vtu")
        n_sub_spaces = space.num_sub_spaces()
        nfns += expand_sub_fns(fn)
    fns = nfns
    del (nfns)

    spaces = []
    lfns = OrderedDict()
    for fn in fns:
        space = fn.function_space()
        assert (space.mesh().id() == mesh.id())
        e = space.ufl_element()
        assert (e.cell().geometric_dimension() == dim)
        assert (e.cell().topological_dimension() == dim)
        if (not e.family() in ["Lagrange", "Discontinuous Lagrange"]
            or not dim in [1, 2, 3]
            or (dim == 1 and not e.degree() in [1, 2, 3])
            or (dim in [2, 3] and not e.degree() in [1, 2])) and \
          (not e.family() == "Discontinuous Lagrange"
            or not dim in [1, 2, 3]
            or not e.degree() == 0):
            raise NotImplementedException(
                'Element family "%s" with degree %i in %i dimension(s) not supported by write_vtu'
                % (e.family(), e.degree(), dim))
        if e in lfns:
            lfns[e].append(fn)
        else:
            spaces.append(space)
            lfns[e] = [fn]
    fns = lfns

    if len(spaces) == 1:
        filenames = [filename]
    else:
        filenames = []
        for space in spaces:
            e = space.ufl_element()
            lfilename = "%s_P%i" % (filename, e.degree())
            if e.family() == "Discontinuous Lagrange":
                lfilename = "%s_DG" % lfilename
            filenames.append(lfilename)

    if not t is None:
        for space in spaces:
            lt = dolfin.Function(space, name="time")
            if isinstance(t, float):
                lt.vector()[:] = t
            else:
                lt.assign(t)
            fns[space.ufl_element()].append(lt)

    names = {e: [] for e in fns}
    for e in fns:
        for fn in fns[e]:
            name = fn.name()
            if name in names[e]:
                raise InvalidArgumentException("Duplicate Function name: %s" %
                                               name)
            names[e].append(name)

    for filename, space in zip(filenames, spaces):
        e = space.ufl_element()
        degree = e.degree()

        vtu = vtk.vtkUnstructuredGrid()

        dof = space.dofmap()
        nodes = set()
        for i in range(mesh.num_cells()):
            cell = dof.cell_dofs(i)
            for node in cell:
                nodes.add(node)
        nodes = numpy.array(sorted(list(nodes)), dtype=numpy.intc)

        if degree == 0:
            xspace = dolfin.FunctionSpace(mesh, "CG", 1)
            xdof = xspace.dofmap()
            xnodes = set()
            for i in range(mesh.num_cells()):
                cell = xdof.cell_dofs(i)
                for node in cell:
                    xnodes.add(node)
            xnodes = numpy.array(sorted(list(xnodes)), dtype=numpy.intc)
        else:
            xspace = space
            xdof = dof
            xnodes = nodes
        xnode_map = {node: i for i, node in enumerate(xnodes)}

        x = dolfin.interpolate(dolfin.Expression("x[0]"),
                               xspace).vector().gather(xnodes)
        if dim > 1:
            y = dolfin.interpolate(dolfin.Expression("x[1]"),
                                   xspace).vector().gather(xnodes)
        if dim > 2:
            z = dolfin.interpolate(dolfin.Expression("x[2]"),
                                   xspace).vector().gather(xnodes)
        n = x.shape[0]

        points = vtk.vtkPoints()
        points.SetDataTypeToDouble()
        points.SetNumberOfPoints(n)
        if dim == 1:
            for i in range(n):
                points.SetPoint(i, x[i], 0.0, 0.0)
        elif dim == 2:
            for i in range(n):
                points.SetPoint(i, x[i], y[i], 0.0)
        else:
            for i in range(n):
                points.SetPoint(i, x[i], y[i], z[i])
        vtu.SetPoints(points)

        id_list = vtk.vtkIdList()
        if dim == 1:
            if degree in [0, 1]:
                cell_type = vtk.vtkLine().GetCellType()
                id_list.SetNumberOfIds(2)
                cell_map = None
            elif degree == 2:
                cell_type = vtk.vtkQuadraticEdge().GetCellType()
                id_list.SetNumberOfIds(3)
                cell_map = None
            else:
                cell_type = vtk.vtkCubicLine().GetCellType()
                id_list.SetNumberOfIds(4)
                cell_map = None
        elif dim == 2:
            if degree in [0, 1]:
                cell_type = vtk.vtkTriangle().GetCellType()
                id_list.SetNumberOfIds(3)
                cell_map = None
            else:
                cell_type = vtk.vtkQuadraticTriangle().GetCellType()
                id_list.SetNumberOfIds(6)
                cell_map = {0: 0, 1: 1, 2: 2, 3: 5, 4: 3, 5: 4}
        else:
            if degree in [0, 1]:
                cell_type = vtk.vtkTetra().GetCellType()
                id_list.SetNumberOfIds(4)
                cell_map = None
            else:
                cell_type = vtk.vtkQuadraticTetra().GetCellType()
                id_list.SetNumberOfIds(10)
                cell_map = {
                    0: 0,
                    1: 1,
                    2: 2,
                    3: 3,
                    4: 9,
                    5: 6,
                    6: 8,
                    7: 7,
                    8: 5,
                    9: 4
                }
        for i in range(mesh.num_cells()):
            cell = xdof.cell_dofs(i)
            assert (len(cell) == id_list.GetNumberOfIds())
            if not cell_map is None:
                cell = [cell[cell_map[j]] for j in range(len(cell))]
            for j in range(len(cell)):
                id_list.SetId(j, xnode_map[cell[j]])
            vtu.InsertNextCell(cell_type, id_list)

        if degree == 0:
            for fn in fns[e]:
                if not fn.value_rank() == 0:
                    raise NotImplementedException(
                        "Function rank %i not supported by write_vtu" %
                        fn.value_rank())
                data = fn.vector().gather(nodes)
                cell_data = vtk.vtkDoubleArray()
                cell_data.SetNumberOfComponents(1)
                cell_data.SetNumberOfValues(mesh.num_cells())
                cell_data.SetName(fn.name())
                for i, datum in enumerate(data):
                    cell_data.SetValue(i, datum)
                vtu.GetCellData().AddArray(cell_data)
            vtu.GetCellData().SetActiveScalars(names[e][0])
        else:
            for fn in fns[e]:
                if not fn.value_rank() == 0:
                    raise NotImplementedException(
                        "Function rank %i not supported by write_vtu" %
                        fn.value_rank())
                data = fn.vector().gather(nodes)
                point_data = vtk.vtkDoubleArray()
                point_data.SetNumberOfComponents(1)
                point_data.SetNumberOfValues(n)
                point_data.SetName(fn.name())
                for i, datum in enumerate(data):
                    point_data.SetValue(i, datum)
                vtu.GetPointData().AddArray(point_data)
            vtu.GetPointData().SetActiveScalars(names[e][0])

        if dolfin.MPI.size(dolfin.mpi_comm_world()) > 1:
            writer = vtk.vtkXMLPUnstructuredGridWriter()
            writer.SetNumberOfPieces(dolfin.MPI.size(dolfin.mpi_comm_world()))
            writer.SetStartPiece(dolfin.MPI.rank(dolfin.mpi_comm_world()))
            writer.SetEndPiece(dolfin.MPI.rank(dolfin.mpi_comm_world()))
            ext = ".pvtu"
        else:
            writer = vtk.vtkXMLUnstructuredGridWriter()
            ext = ".vtu"
        if index is None:
            filename = "%s%s" % (filename, ext)
        else:
            filename = "%s_%i%s" % (filename, index, ext)
        writer.SetFileName(filename)
        writer.SetDataModeToAppended()
        writer.EncodeAppendedDataOff()
        writer.SetCompressorTypeToZLib()
        writer.GetCompressor().SetCompressionLevel(9)
        writer.SetBlockSize(2**15)
        writer.SetInput(vtu)
        writer.Write()
        if not writer.GetProgress() == 1.0 or not writer.GetErrorCode() == 0:
            raise IOException("Failed to write vtu file: %s" % filename)

    return
Ejemplo n.º 13
0
    cf.SetValue(0, 130)
    cf.SetComputeNormals(0)
    cf.SetComputeGradients(0)
    cf.SetInputConnection(reader.GetOutputPort())
    cf.UpdateInformation()
    cf.GetOutputInformation(0).Set(vtk.vtkStreamingDemandDrivenPipeline.UPDATE_NUMBER_OF_PIECES(), nranks)
    cf.GetOutputInformation(0).Set(vtk.vtkStreamingDemandDrivenPipeline.UPDATE_PIECE_NUMBER(), rank)
    cf.Update()

    ntris = cf.GetOutput().GetNumberOfCells()
    da = vtk.vtkIntArray()
    da.InsertNextValue(ntris)

    da2 = vtk.vtkIntArray()
    da2.SetNumberOfTuples(1)
    contr.AllReduce(da, da2, vtk.vtkCommunicator.SUM_OP)

    if rank == 0:
        print(da2.GetValue(0))
        import os
        os.remove(filename)
        for i in range(npieces):
            os.remove(VTK_TEMP_DIR + "/%s_%d.%s" % (dataType, i, ext))

    assert da2.GetValue(0) == numTris

TestDataType('ImageData', vtk.vtkXMLPImageDataReader(), vtk.vtkXMLPImageDataWriter(), 'vti', 4924)
TestDataType('RectilinearGrid', vtk.vtkXMLPRectilinearGridReader(), vtk.vtkXMLPRectilinearGridWriter(), 'vtr', 4924)
TestDataType('StructuredGrid', vtk.vtkXMLPStructuredGridReader(), vtk.vtkXMLPStructuredGridWriter(), 'vts', 4924)
TestDataType('UnstructuredGrid', vtk.vtkXMLPUnstructuredGridReader(), vtk.vtkXMLPUnstructuredGridWriter(), 'vtu', 11856)