Exemple #1
0
def _write_vtu_series(grid, coordinates, connectivity, data, filename_base, last_step, is_cell_data):
    steps = last_step + 1 if last_step is not None else len(data)
    fn_tpl = "{}_{:08d}"

    npoints = len(coordinates[0])
    ncells = len(connectivity)

    ref = grid.reference_element
    if ref is ref is referenceelements.triangle:
        points_per_cell = 3
        vtk_el_type = VtkTriangle.tid
    elif ref is referenceelements.square:
        points_per_cell = 4
        vtk_el_type = VtkQuad.tid
    else:
        raise NotImplementedError("vtk output only available for grids with triangle or rectangle reference elments")

    connectivity = connectivity.reshape(-1)
    cell_types = np.empty(ncells, dtype='uint8')
    cell_types[:] = vtk_el_type
    offsets = np.arange(start=points_per_cell, stop=ncells*points_per_cell+1, step=points_per_cell, dtype='int32')

    group = VtkGroup(filename_base)
    for i in range(steps):
        fn = fn_tpl.format(filename_base, i)
        vtk_data = data[i, :]
        w = VtkFile(fn, VtkUnstructuredGrid)
        w.openGrid()
        w.openPiece(ncells=ncells, npoints=npoints)

        w.openElement("Points")
        w.addData("Coordinates", coordinates)
        w.closeElement("Points")
        w.openElement("Cells")
        w.addData("connectivity", connectivity)
        w.addData("offsets", offsets)
        w.addData("types", cell_types)
        w.closeElement("Cells")
        if is_cell_data:
            _addDataToFile(w, cellData={"Data": vtk_data}, pointData=None)
        else:
            _addDataToFile(w, cellData=None, pointData={"Data": vtk_data})

        w.closePiece()
        w.closeGrid()
        w.appendData(coordinates)
        w.appendData(connectivity).appendData(offsets).appendData(cell_types)
        if is_cell_data:
            _appendDataToFile(w, cellData={"Data": vtk_data}, pointData=None)
        else:
            _appendDataToFile(w, cellData=None, pointData={"Data": vtk_data})

        w.save()
        group.addFile(filepath=fn, sim_time=i)
    group.save()
Exemple #2
0
def _write_vtu_series(grid, coordinates, connectivity, data, filename_base, last_step, is_cell_data):
    steps = last_step + 1 if last_step is not None else len(data)
    fn_tpl = "{}_{:08d}"

    npoints = len(coordinates[0])
    ncells = len(connectivity)

    ref = grid.reference_element
    if ref is ref is referenceelements.triangle:
        points_per_cell = 3
        vtk_el_type = VtkTriangle.tid
    elif ref is referenceelements.square:
        points_per_cell = 4
        vtk_el_type = VtkQuad.tid
    else:
        raise NotImplementedError("vtk output only available for grids with triangle or rectangle reference elments")

    connectivity = connectivity.reshape(-1)
    cell_types = np.empty(ncells, dtype='uint8')
    cell_types[:] = vtk_el_type
    offsets = np.arange(start=points_per_cell, stop=ncells*points_per_cell+1, step=points_per_cell, dtype='int32')

    group = VtkGroup(filename_base)
    for i in range(steps):
        fn = fn_tpl.format(filename_base, i)
        vtk_data = data[i, :]
        w = VtkFile(fn, VtkUnstructuredGrid)
        w.openGrid()
        w.openPiece(ncells=ncells, npoints=npoints)

        w.openElement("Points")
        w.addData("Coordinates", coordinates)
        w.closeElement("Points")
        w.openElement("Cells")
        w.addData("connectivity", connectivity)
        w.addData("offsets", offsets)
        w.addData("types", cell_types)
        w.closeElement("Cells")
        if is_cell_data:
            _addDataToFile(w, cellData={"Data": vtk_data}, pointData=None)
        else:
            _addDataToFile(w, cellData=None, pointData={"Data": vtk_data})

        w.closePiece()
        w.closeGrid()
        w.appendData(coordinates)
        w.appendData(connectivity).appendData(offsets).appendData(cell_types)
        if is_cell_data:
            _appendDataToFile(w, cellData={"Data": vtk_data}, pointData=None)
        else:
            _appendDataToFile(w, cellData=None, pointData={"Data": vtk_data})

        w.save()
        group.addFile(filepath=fn + '.vtu', sim_time=i)
    group.save()
Exemple #3
0
def writeVTK(filename,xdim, ydim, pointData=None, cellData=None):
    """
        Writes data values as a rectilinear or rectangular grid.

        PARAMETERS:
            path: name of the file without extension where data should be saved.
            cellData: dictionary containing arrays with cell centered data.
                      Keys should be the names of the data arrays.
                      Arrays must have the same dimensions in all directions and must contain
                      only scalar data.
            nodeData: dictionary containing arrays with node centered data.
                      Keys should be the names of the data arrays.
                      Arrays must have same dimension in each direction and
                      they should be equal to the dimensions of the cell data plus one and
                      must contain only scalar data.

        RETURNS:
            Full path to saved file.

    """
    nx, ny, nz = xdim, ydim, 0
    lx, ly, lz = xdim/10.0, ydim/10.0, 0
    dx, dy, dz = lx/nx, ly/ny, 0
    ncells = nx * ny
    npoints = (nx + 1) * (ny + 1) * (nz + 1)
    x = np.arange(0, lx + 0.1*dx, dx, dtype='float64')
    y = np.arange(0, ly + 0.1*dy, dy, dtype='float64')
    z = np.arange(0,0, dtype='float64')
    start, end = (0,0,0), (nx, ny, nz)
# Set up object
    w = VtkFile(filename, VtkRectilinearGrid)
#Open XML tags
    w.openGrid(start = start, end = end)
    w.openPiece( start = start, end = end)

# Coordinates of cell vertices
    w.openElement("Coordinates")
    w.addData("x_coordinates", x);
    w.addData("y_coordinates", y);
    w.addData("z_coordinates", z);
    w.closeElement("Coordinates");

# Add data from the dictionary
    #temp = np.random.rand(npoints)
    __addDataToFile(w, cellData, pointData)

#Close XML tags
    w.closePiece()
    w.closeGrid()
#Append Coordinate Data to file in binary form
    w.appendData(x).appendData(y).appendData(z)
#Append Cell and Point Data to file in binary form
    __appendDataToFile(w, cellData, pointData)
    w.save()
    return w.getFileName()
Exemple #4
0
def run():
    print("Running lowlevel...")

    nx, ny, nz = 6, 6, 2
    lx, ly, lz = 1.0, 1.0, 1.0
    dx, dy, dz = lx / nx, ly / ny, lz / nz
    ncells = nx * ny * nz
    npoints = (nx + 1) * (ny + 1) * (nz + 1)
    x = np.arange(0, lx + 0.1 * dx, dx, dtype='float64')
    y = np.arange(0, ly + 0.1 * dy, dy, dtype='float64')
    z = np.arange(0, lz + 0.1 * dz, dz, dtype='float64')
    start, end = (0, 0, 0), (nx, ny, nz)

    w = VtkFile(FILE_PATH, VtkRectilinearGrid)
    w.openGrid(start=start, end=end)
    w.openPiece(start=start, end=end)

    # Point data
    temp = np.random.rand(npoints)
    vx = vy = vz = np.zeros([nx + 1, ny + 1, nz + 1],
                            dtype="float64",
                            order='F')
    w.openData("Point", scalars="Temperature", vectors="Velocity")
    w.addData("Temperature", temp)
    w.addData("Velocity", (vx, vy, vz))
    w.closeData("Point")

    # Cell data
    pressure = np.ones([nx, ny, nz], dtype="float64", order='F')
    w.openData("Cell", scalars="Pressure")
    w.addData("Pressure", pressure)
    w.closeData("Cell")

    # Coordinates of cell vertices
    w.openElement("Coordinates")
    w.addData("x_coordinates", x)
    w.addData("y_coordinates", y)
    w.addData("z_coordinates", z)
    w.closeElement("Coordinates")

    w.closePiece()
    w.closeGrid()

    w.appendData(data=temp)
    w.appendData(data=(vx, vy, vz))
    w.appendData(data=pressure)
    w.appendData(x).appendData(y).appendData(z)
    w.save()
Exemple #5
0
def triangle_faces_to_VTK(filename, x, y, z, faces, point_data, cell_data):
    vertices = (x, y, z)
    x2 = x * 1.
    y2 = y * 1.
    z2 = z * 1.
    vert2 = (x2, y2, z2)
    w = VtkFile(filename, VtkUnstructuredGrid)
    w.openGrid()
    w.openPiece(npoints=len(x), ncells=len(faces))
    w.openElement("Points")
    w.addData("Points", vertices)
    w.closeElement("Points")

    # Create some temporary arrays to write grid topology.
    ncells = len(faces)
    # Index of last node in each cell.
    offsets = np.arange(start=3, stop=3 * (ncells + 1), step=3, dtype='uint32')
    # Connectivity as unrolled array.
    connectivity = faces.reshape(ncells * 3).astype('int32')
    cell_types = np.ones(ncells, dtype='uint8') * VtkTriangle.tid

    w.openElement("Cells")
    w.addData("connectivity", connectivity)
    w.addData("offsets", offsets)
    w.addData("types", cell_types)
    w.closeElement("Cells")

    _addDataToFile(w, cellData=cell_data, pointData=point_data)

    w.closePiece()
    w.closeGrid()

    w.appendData(vert2)
    w.appendData(connectivity).appendData(offsets).appendData(cell_types)

    _appendDataToFile(w, cellData=cell_data, pointData=point_data)

    w.save()
    return w.getFileName()
def export_to_vtk(xgrid, ygrid, data, data_name):
	""" Export the specified 2D structured grid to file """
	from evtk.vtk import VtkFile, VtkStructuredGrid
	
	
	#stupid reshape data
	oldshape = data.shape
	newshape = oldshape + (1,)
	data = data.reshape(newshape)
	xgrid = xgrid.reshape(newshape)
	ygrid = ygrid.reshape(newshape)
	
	
	path = './{}'.format(data_name)
	w = VtkFile(path, VtkStructuredGrid)
	
	#Header stuff?
	nx, ny = oldshape[0] - 1, oldshape[1] - 1
	w.openGrid(start = (0, 0, 0), end = (nx, ny, 0))
	w.openPiece(start = (0, 0, 0), end = (nx, ny, 0))
	
	w.openElement("Points")
	w.addData("points", (xgrid, ygrid, data))
	w.closeElement("Points")
	
	w.openData("Point", scalars = data_name)
	w.addData(data_name, data)
	w.closeData("Point")
	
	w.closePiece()
	w.closeGrid()
	
	#Now add the actual data?
	w.appendData((xgrid, ygrid, data))
	w.appendData(data)
	
	#finished
	w.save()
Exemple #7
0
def write_vtp_header(path,
                     prefix,
                     active_var_index,
                     var_indices,
                     variable_list,
                     all_dim_vals,
                     vertices,
                     connectivity,
                     offsets,
                     nPoints,
                     nPolygons,
                     outType,
                     cellData=True,
                     pointData=False,
                     xtime=None):  # {{{
    vtkFile = VtkFile("{}/{}".format(path, prefix), VtkPolyData)

    if xtime is not None:
        vtkFile.openElement(str("metadata"))
        vtkFile.openElement(str("xtime"))
        vtkFile.xml.addText(str(xtime))
        vtkFile.closeElement(str("xtime"))
        vtkFile.closeElement(str("metadata"))

    vtkFile.openElement(vtkFile.ftype.name)
    vtkFile.openPiece(npoints=nPoints, npolys=nPolygons)

    vtkFile.openElement(str("Points"))
    vtkFile.addData(str("points"), vertices)
    vtkFile.closeElement(str("Points"))

    vtkFile.openElement(str("Polys"))
    vtkFile.addData(str("connectivity"), connectivity)
    vtkFile.addData(str("offsets"), offsets)
    vtkFile.closeElement(str("Polys"))

    if (cellData):
        vtkFile.openData(
            str("Cell"),
            scalars=[str(var) for var in variable_list[active_var_index]])
        for iVar in var_indices:
            var_name = variable_list[iVar]
            (out_var_names, dim_list) = \
                get_hyperslab_name_and_dims(var_name, all_dim_vals[var_name])
            for out_var_name in out_var_names:
                vtkFile.addHeader(str(out_var_name), outType, nPolygons, 1)
        vtkFile.closeData(str("Cell"))
    if (pointData):
        vtkFile.openData(
            str("Point"),
            scalars=[str(var) for var in variable_list[active_var_index]])
        for iVar in var_indices:
            var_name = variable_list[iVar]
            (out_var_names, dim_list) = \
                get_hyperslab_name_and_dims(var_name, all_dim_vals[var_name])
            for out_var_name in out_var_names:
                vtkFile.addHeader(str(out_var_name), outType, nPoints, 1)
        vtkFile.closeData(str("Point"))

    vtkFile.closePiece()
    vtkFile.closeElement(vtkFile.ftype.name)

    vtkFile.appendData(vertices)
    vtkFile.appendData(connectivity)
    vtkFile.appendData(offsets)

    return vtkFile  # }}}
Exemple #8
0
        # Write DATA to FILE (binary)
        # ******************************************

        # create a VTK unstructured grid (.vtu) file
        vtufile = fileprefix+'_'+str(timestep)
        vtufile = os.path.join(outputdir,vtufile)
        w = VtkFile(vtufile, VtkUnstructuredGrid)
        vtufile += '.vtu'

        w.openGrid()
        w.openPiece(npoints=npoints, ncells=nconnex)

        # Set up Points (x,y,z) data XML
        w.openElement("Points")
        w.addData("points", (x,y,z) )
        w.closeElement("Points")

        # Set up Cell data
        w.openElement("Cells")
        w.addData("connectivity", connections )
        w.addData("offsets", offset)
        w.addData("types", celltype)
        w.closeElement("Cells")

        # Set up force data
        w.openData("Cell")
        w.addData("force", forceClean)
        # w.addData("area", area)
        # w.addData("heatflux", heatflux)
#        w.closeData("Cell")
Exemple #9
0
        # Write DATA to FILE (binary)
        # ******************************************

        # create a VTK unstructured grid (.vtu) file
        vtufile = fileprefix + '_' + str(timestep)
        vtufile = os.path.join(outputdir, vtufile)
        w = VtkFile(vtufile, VtkUnstructuredGrid)
        vtufile += '.vtu'

        w.openGrid()
        w.openPiece(npoints=npoints, ncells=nconnex)

        # Set up Points (x,y,z) data XML
        w.openElement("Points")
        w.addData("points", (x, y, z))
        w.closeElement("Points")

        # Set up Cell data
        w.openElement("Cells")
        w.addData("connectivity", connections)
        w.addData("offsets", offset)
        w.addData("types", celltype)
        w.closeElement("Cells")

        # Set up force data
        w.openData("Cell")
        w.addData("force", forceClean)
        # w.addData("area", area)
        # w.addData("heatflux", heatflux)
        #        w.closeData("Cell")
Exemple #10
0
def pc2vtkxml(varfile = 'var.dat', datadir = 'data/', proc = -1,
           variables = ['rho','uu','bb'], magic = [],
           destination = 'work', quiet = True):
    """
    Convert data from PencilCode format to XML vtk.
    Write .vts Structured Grid, not Rectilinear Grid as VisIt screws up reading Rectilinear Grid.
    However, this is set to write large grids in VTK XML, which is not yet suported by VisIt anyways. Use ParaView.

    call signature::
    
      pc2xmlvtk(varfile = 'var.dat', datadir = 'data/', proc = -1,
           variables = ['rho','uu','bb'], magic = [],
           destination = 'work.vtk')
    
    Read *varfile* and convert its content into vtk format. Write the result
    in *destination*.
    
    Keyword arguments:
    
      *varfile*:
        The original varfile.
        
      *datadir*:
        Directory where the data is stored.
       
      *proc*:
        Processor which should be read. Set to -1 for all processors.
      
      *variables* = [ 'rho' , 'lnrho' , 'uu' , 'bb', 'b_mag', 'jj', 'j_mag', 'aa', 'tt', 'lnTT', 'cc', 'lncc', 'ss', 'vort', 'eth' ]
        Variables which should be written.
        
      *magic*: [ 'vort' , 'bb' ]
        Additional variables which should be written.
       
      *destination*:
        Destination file.
    """

    # this should correct for the case the user type only one variable
    if (len(magic) > 0):
        if (len(magic[0]) == 1):
            magic = [magic]

    # make sure magic is set when writing 'vort' or 'bb'
    try:
        index = variables.index('vort')
        magic.append('vort')
    except:
        pass      
    try:
        index = variables.index('bb')
        magic.append('bb')
    except:
        pass
    try:
        index = variables.index('b_mag')
        magic.append('bb')
    except:
        pass
    try:
        index = variables.index('tt')
        magic.append('tt')
    except:
        pass

    # get endian format of the data 
    format = pc.get_format(datadir = datadir)

    # reading pc variables and setting dimensions
    var = pc.read_var(varfile = varfile, datadir = datadir, proc = proc,
                    magic = magic, trimall = True, quiet = quiet, format = format)
                    
    grid = pc.read_grid(datadir = datadir, proc = proc, trim = True, quiet = True, format = format)

    
    dimx = len(grid.x)
    dimy = len(grid.y)
    dimz = len(grid.z)
    dim = dimx * dimy * dimz

    scalardata = {}
    if ('rho' in variables) :
      rho = np.transpose(var.rho.copy()) 
      scalardata['rho'] = rho
    if ('lnrho' in variables) :
      lnrho = np.transpose(var.lnrho.copy()) 
      scalardata['lnrho'] = lnrho
    if ('tt' in variables) :
      tt = np.transpose(var.tt.copy()) 
      scalardata['tt'] = tt
    if ('lntt' in variables) :
      lntt = np.transpose(var.lntt.copy()) 
      scalardata['lntt'] = lntt
    if ('cc' in variables) :
      cc = np.transpose(var.cc.copy()) 
      scalardata['cc'] = cc
    if ('lncc' in variables) :
      lncc = np.transpose(var.lncc.copy()) 
      scalardata['lncc'] = lncc
    if ('ss' in variables) :
      ss = np.transpose(var.ss.copy()) 
      scalardata['ss'] = ss
    if ('eth' in variables) :
      eth = np.transpose(var.eth.copy()) 
      scalardata['eth'] = eth

    vectordata = {}
    if ('uu' in variables) :
      uu1 = np.transpose(var.uu[0,:,:,:].copy()) 
      uu2 = np.transpose(var.uu[1,:,:,:].copy()) 
      uu3 = np.transpose(var.uu[2,:,:,:].copy()) 
      vectordata['uu'] = (uu1,uu2,uu3)
    if ('bb' in variables) :
      bb1 = np.transpose(var.bb[0,:,:,:].copy()) 
      bb2 = np.transpose(var.bb[1,:,:,:].copy()) 
      bb3 = np.transpose(var.bb[2,:,:,:].copy()) 
      vectordata['bb'] = (bb1,bb2,bb3)
    if ('jj' in variables) :
      jj1 = np.transpose(var.jj[0,:,:,:].copy()) 
      jj2 = np.transpose(var.jj[1,:,:,:].copy()) 
      jj3 = np.transpose(var.jj[2,:,:,:].copy()) 
      vectordata['jj'] = (jj1,jj2,jj3)
    if ('aa' in variables) :
      aa1 = np.transpose(var.aa[0,:,:,:].copy()) 
      aa2 = np.transpose(var.aa[1,:,:,:].copy()) 
      aa3 = np.transpose(var.aa[2,:,:,:].copy()) 
      vectordata['aa'] = (aa1,aa2,aa3)
    if ('vort' in variables) :
      vort1 = np.transpose(var.vort[0,:,:,:].copy()) 
      vort2 = np.transpose(var.vort[1,:,:,:].copy()) 
      vort3 = np.transpose(var.vort[2,:,:,:].copy()) 
      vectordata['vort'] = (vort1,vort2,vort3)



    X = np.zeros([dimx,dimy,dimz])
    Y = np.zeros([dimx,dimy,dimz])
    Z = np.zeros([dimx,dimy,dimz])
    for k in range(dimz):
      for j in range(dimy):
        for i in range(dimx):
          X[i,j,k] = grid.x[i] 
          Y[i,j,k] = grid.y[j]
          Z[i,j,k] = grid.z[k] 

    start = (0,0,0)
    end  = (dimx-1, dimy-1, dimz-1)

    time = np.array([var.t])

    w = VtkFile(destination, VtkStructuredGrid,largeFile=True)


    w.openGrid(start = start, end = end)

    #this s for wirting Time in VisIt files. However, when usign large grid Visit does not work anyways.
    #w.openFieldData()
    #w.addTuple('TIME', time.dtype.name,len(time))
    #w.closeFieldData()

    w.openPiece(start = start, end = end)
    w.openElement("Points")
    w.addData("points", (X,Y,Z))
    w.closeElement("Points")

    w.openData("Point", scalars = scalardata.keys(), vectors = vectordata.keys())
    for key in scalardata:
      w.addData(key,scalardata[key])
    for key in vectordata:
      w.addData(key,vectordata[key])
    w.closeData("Point")

    w.closePiece()
    w.closeGrid()

    #w.appendData( time )
    w.appendData( (X,Y,Z) )
    for key in scalardata:
      w.appendData(data = scalardata[key])
    for key in vectordata:
      w.appendData(data = vectordata[key])
    w.save()
Exemple #11
0
# Point data
temp = np.random.rand(npoints)
vx = vy = vz = np.zeros([nx + 1, ny + 1, nz + 1], dtype="float64", order='F')
w.openData("Point", scalars="Temperature", vectors="Velocity")
w.addData("Temperature", temp)
w.addData("Velocity", (vx, vy, vz))
w.closeData("Point")

# Cell data
pressure = np.zeros([nx, ny, nz], dtype="float64", order='F')
w.openData("Cell", scalars="Pressure")
w.addData("Pressure", pressure)
w.closeData("Cell")

# Coordinates of cell vertices
w.openElement("Coordinates")
w.addData("x_coordinates", x)
w.addData("y_coordinates", y)
w.addData("z_coordinates", z)
w.closeElement("Coordinates")

w.closePiece()
w.closeGrid()

w.appendData(data=temp)
w.appendData(data=(vx, vy, vz))
w.appendData(data=pressure)
w.appendData(x).appendData(y).appendData(z)
w.save()
Exemple #12
0
class VTKFile(object):
    def __init__(self,
                 filename,
                 path='',
                 timestep=0,
                 npx=1,
                 npy=1,
                 npz=1,
                 init_pvd=False):
        self.timestep = timestep
        prefix = '_{0}_{1}'.format(timestep, mpi.COMM_WORLD.Get_rank())

        if not os.path.exists(path) and mpi.COMM_WORLD.Get_rank() == 0:
            os.mkdir(path)
        # All the processes wait for the creation of the output directory
        mpi.COMM_WORLD.Barrier()

        self.path = path
        self.filename = filename
        self.vtkfile = VtkFile(path + '/' + filename + prefix,
                               VtkRectilinearGrid)
        self.end = np.zeros(3, dtype=np.int)
        self.x = None
        self.y = None
        self.z = None
        self.scalars = {}
        self.vectors = {}
        self._init_grid = True
        self._init_pvd = init_pvd
        self.npx = npx
        self.npy = npy
        self.npz = npz

        self.log = setLogger(__name__)

    def set_grid(self, x, y=None, z=None):
        if not self._init_grid:
            self.log.warning("vtk grid redefined.")

        self.x = x
        self.y = y
        self.z = z
        self.dim = 1
        self.end[0] = x.size - 1
        if y is not None:
            self.dim = 2
            self.end[1] = y.size - 1
        if z is not None:
            self.dim = 3
            self.end[2] = z.size - 1

        self.vtkfile.openGrid(start=(0, ) * 3, end=self.end.tolist())
        self.vtkfile.openPiece(start=(0, ) * 3, end=self.end.tolist())
        self._init_grid = False

    def add_scalar(self, name, f, *fargs):
        if self._init_grid:
            self.log.error("""You must define the grid before to add scalar
                            (see set_grid method)""")

        if isinstance(f, np.ndarray):
            data = f
        else:
            data = f(*fargs)

        if np.all(np.asarray(data.shape) != (self.end + 1)[:self.dim]):
            self.log.error("""The shape of the scalar data {0} ({1})
                            must have the shape of the grid ({2})""".format(
                name, data.shape, self.end + 1))
        self.scalars[name] = data.ravel(order='F')

    def add_vector(self, name, f, *fargs):
        if self._init_grid:
            self.log.error("""You must define the grid before to add scalar
                            (see set_grid method)""")

        if isinstance(f, list):
            data = f
        else:
            data = f(*fargs)

        for d in data:
            if np.all(np.asarray(d.shape) != (self.end + 1)[:self.dim]):
                self.log.error("""The shape of each component
                            of the vector data {0}
                            must have the shape of the grid ({1})""".format(
                    name, self.end + 1))
        tdata = ()
        for d in data:
            tdata += (d.ravel(order='F'), )

        if self.dim == 2:
            tdata += (np.zeros(tdata[0].shape), )
        self.vectors[name] = tdata

    def save(self):
        if self._init_grid:
            self.log.error("""You must define the grid before save data
                            (see set_grid method)""")

        if len(self.scalars) == 0 and len(self.vectors) == 0:
            self.log.error("""You must provide scalar or vector data
                            to save the vtkfile""")

        # Point data
        self.vtkfile.openData("Point",
                              scalars=list(self.scalars.keys()),
                              vectors=list(self.vectors.keys()))

        for k, v in list(self.scalars.items()):
            self.vtkfile.addData(k, v)
        for k, v in list(self.vectors.items()):
            self.vtkfile.addData(k, v)

        self.vtkfile.closeData("Point")

        # Coordinates of cell vertices
        self.vtkfile.openElement("Coordinates")
        self.vtkfile.addData("x_coordinates", self.x)
        if self.y is not None:
            self.vtkfile.addData("y_coordinates", self.y)
        if self.z is not None:
            self.vtkfile.addData("z_coordinates", self.z)
        else:
            self.vtkfile.addData("z_coordinates", np.zeros(self.x.shape))
        self.vtkfile.closeElement("Coordinates")

        self.vtkfile.closePiece()
        self.vtkfile.closeGrid()

        for k, v in list(self.scalars.items()):
            self.vtkfile.appendData(data=v)
        for k, v in list(self.vectors.items()):
            self.vtkfile.appendData(data=v)
        if self.y is not None and self.z is not None:
            self.vtkfile.appendData(self.x).appendData(self.y).appendData(
                self.z)
        elif self.y is not None:
            self.vtkfile.appendData(self.x).appendData(self.y)
        else:
            self.vtkfile.appendData(self.x)

        if mpi.COMM_WORLD.Get_rank() == 0:
            self._write_pvd()

        self.vtkfile.save()

    def _write_pvd(self):
        size = mpi.COMM_WORLD.Get_size()

        if self._init_pvd:
            pvd = """<VTKFile type="Collection" version="0.1" byte_order="LittleEndian">
<Collection>
"""
            for i in range(size):
                pvd += "<DataSet timestep=\"{2}\" part=\"{0}\" file=\"./{1}_{2}_{0}.vtr\"/>\n".format(
                    i, self.filename, self.timestep)
            pvd += """</Collection>
</VTKFile>
"""
            f = open(self.path + '/' + self.filename + '.pvd', 'w')
            self._init_pvd = False
            f.write(pvd)
            f.close()
        else:
            oldlines = open(self.path + '/' + self.filename +
                            '.pvd').readlines()

            pvd = ''
            for i in range(size):
                pvd += "<DataSet timestep=\"{2}\" part=\"{0}\" file=\"./{1}_{2}_{0}.vtr\"/>\n".format(
                    i, self.filename, self.timestep)
            pvd += """</Collection>
</VTKFile>
"""
            f = open(self.path + '/' + self.filename + '.pvd', 'w')

            f.writelines(oldlines[:-2])
            f.write(pvd)
            f.close()