def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(
         self, module_manager,
         vtk.vtkXMLRectilinearGridWriter(), 'Writing vtkXMLRectilinearGrid.',
         ('vtkXMLRectilinearGrid',), (),
         replaceDoc=True,
         inputFunctions=None, outputFunctions=None)
Beispiel #2
0
    def write(self, fname):
        """
        Write to file.

        Parameters
        ----------
        fname : str
            Filename for writing.

        """
        if isinstance(self.geom, vtk.vtkRectilinearGrid):
            writer = vtk.vtkXMLRectilinearGridWriter()
        elif isinstance(self.geom, vtk.vtkUnstructuredGrid):
            writer = vtk.vtkXMLUnstructuredGridWriter()
        elif isinstance(self.geom, vtk.vtkPolyData):
            writer = vtk.vtkXMLPolyDataWriter()

        default_ext = writer.GetDefaultFileExtension()
        name, ext = os.path.splitext(fname)
        if ext and ext != '.' + default_ext:
            raise ValueError('Given extension {} is not .{}'.format(
                ext, default_ext))
        writer.SetFileName('{}.{}'.format(name, default_ext))
        writer.SetCompressorTypeToZLib()
        writer.SetDataModeToBinary()
        writer.SetInputData(self.geom)

        writer.Write()
Beispiel #3
0
    def _save_rectilinear_grid(filename, vtkRectGrid, directory=''):
        """Saves a VTK rectilinear file (vtr) ffor an already generated
        :class:`pyvista.RectilinearGrid` object.

        Parameters
        ----------

        filename : str
            path to the output vtk file or just its name if directory is specified

        directory : str
            directory where the UBC GIF file lives

        """
        if not isinstance(vtkRectGrid, vtk.vtkRectilinearGrid):
            raise RuntimeError(
                '`_save_rectilinear_grid` can only handle `vtkRectilinearGrid` objects. `{}` is not supported.'
                .format(vtkRectGrid.__class__))
        # Check the extension of the filename
        fname = os.path.join(directory, filename)
        ext = os.path.splitext(fname)[1]
        if ext is '':
            fname = fname + '.vtr'
        elif ext not in '.vtr':
            raise IOError(
                '{:s} is an incorrect extension, has to be .vtr'.format(ext))
        # Write the file.
        vtrWriteFilter = vtkXMLRectilinearGridWriter()
        if float(VTK_VERSION.split('.')[0]) >= 6:
            vtrWriteFilter.SetInputDataObject(vtkRectGrid)
        else:
            vtuWriteFilter.SetInput(vtuObj)
        vtrWriteFilter.SetFileName(fname)
        vtrWriteFilter.Update()
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(self,
                                       module_manager,
                                       vtk.vtkXMLRectilinearGridWriter(),
                                       'Writing vtkXMLRectilinearGrid.',
                                       ('vtkXMLRectilinearGrid', ), (),
                                       replaceDoc=True,
                                       inputFunctions=None,
                                       outputFunctions=None)
Beispiel #5
0
def writeVTRFile(fileName,vtkRectilinearGrid):
    '''Function to write vtk rectilinear grid (vtr).'''
    Writer = vtk.vtkXMLRectilinearGridWriter()
    if float(vtk.VTK_VERSION.split('.')[0]) >=6:
        Writer.SetInputData(vtkRectilinearGrid)
    else:
        Writer.SetInput(vtkRectilinearGrid)
    Writer.SetFileName(fileName)
    Writer.Update()
Beispiel #6
0
def writeVTRFile(fileName, vtkRectilinearGrid):
    '''Function to write vtk rectilinear grid (vtr).'''
    Writer = vtk.vtkXMLRectilinearGridWriter()
    if float(vtk.VTK_VERSION.split('.')[0]) >= 6:
        Writer.SetInputData(vtkRectilinearGrid)
    else:
        Writer.SetInput(vtkRectilinearGrid)
    Writer.SetFileName(fileName)
    Writer.Update()
Beispiel #7
0
def writeVTR(vtr_name, scalar_fields, vector_fields, vtkX, vtkY, vtkZ,
             localZrange):
    """Writes a single VTR file per Python processor/variable

    Parameters:
     vtr_name - name of the VTR file
     scalar_fields - dictionary with scalar field arrays ordered [x, y, z], e.g. {'p': array[nx,ny,nz], 'rho0': array[nx,ny,nz]}
     vector_fields - dictionary with vector fields ordered [3, x, y, z], e.g. {'J': array[3,nx,ny,nz], 'B': array[3,nx,ny,nz]}
     vtkX, vtkY, vtkZ - VTR coordinates, see createVtrCoordinates()
     localZrange - local range for Z indices

    """
    Nx = vtkX.GetNumberOfTuples() - 1
    Ny = vtkY.GetNumberOfTuples() - 1
    Nz = vtkZ.GetNumberOfTuples() - 1
    numpoints = (Nx + 1) * (Ny + 1) * (Nz + 1)
    rtg = vtk.vtkRectilinearGrid()
    rtg.SetExtent(0, Nx, 0, Ny, localZrange[0], localZrange[1])
    rtg.SetXCoordinates(vtkX)
    rtg.SetYCoordinates(vtkY)
    rtg.SetZCoordinates(vtkZ)
    vtk_data = []
    array_list = []
    for f in scalar_fields:
        vtk_data.append(vtk.vtkFloatArray())
        vtk_data[-1].SetNumberOfTuples(numpoints)
        vtk_data[-1].SetNumberOfComponents(1)
        array_list.append(scalar_fields[f].swapaxes(
            0, 2).flatten().astype("float32"))
        vtk_data[-1].SetVoidArray(array_list[-1], numpoints, 1)
        vtk_data[-1].SetName(f)
        if f == scalar_fields.keys()[0]:
            rtg.GetPointData().SetScalars(vtk_data[-1])
        else:
            rtg.GetPointData().AddArray(vtk_data[-1])
    #end for
    for f in vector_fields:
        vtk_data.append(vtk.vtkFloatArray())
        vtk_data[-1].SetNumberOfTuples(numpoints * 3)
        vtk_data[-1].SetNumberOfComponents(3)
        array_list.append(vector_fields[f].swapaxes(0, 3).swapaxes(
            1, 2).flatten().astype("float32"))
        vtk_data[-1].SetVoidArray(array_list[-1], numpoints * 3, 1)
        vtk_data[-1].SetName(f)
        if f == vector_fields.keys()[0]:
            rtg.GetPointData().SetVectors(vtk_data[-1])
        else:
            rtg.GetPointData().AddArray(vtk_data[-1])
    #end for
    try:
        writer = vtk.vtkXMLRectilinearGridWriter()
        writer.SetFileName(vtr_name)
        writer.SetInput(rtg)
        writer.Write()
    except:
        print 'Error writing VTR file: ', vtr_name
Beispiel #8
0
def writeVTR(vtr_name, scalar_fields, vector_fields, vtkX, vtkY, vtkZ, localZrange):
    """Writes a single VTR file per Python processor/variable

    Parameters:
     vtr_name - name of the VTR file
     scalar_fields - dictionary with scalar field arrays ordered [x, y, z], e.g. {'p': array[nx,ny,nz], 'rho0': array[nx,ny,nz]}
     vector_fields - dictionary with vector fields ordered [3, x, y, z], e.g. {'J': array[3,nx,ny,nz], 'B': array[3,nx,ny,nz]}
     vtkX, vtkY, vtkZ - VTR coordinates, see createVtrCoordinates()
     localZrange - local range for Z indices

    """

    Nx = vtkX.GetNumberOfTuples() - 1
    Ny = vtkY.GetNumberOfTuples() - 1
    Nz=0 #2D
    numpoints = (Nx+1)*(Ny+1)*(Nz+1)
    rtg = vtk.vtkRectilinearGrid()
    rtg.SetExtent(0, Nx, 0, Ny, localZrange[0], localZrange[1]) 
    rtg.SetXCoordinates(vtkX)
    rtg.SetYCoordinates(vtkY)
    vtk_data = []
    array_list = []
    for f in scalar_fields:
        vtk_data.append(vtk.vtkFloatArray())
        vtk_data[-1].SetNumberOfTuples(numpoints)
        vtk_data[-1].SetNumberOfComponents(1)
        array_list.append(scalar_fields[f].swapaxes(0,2).flatten().astype("float32"))
        vtk_data[-1].SetVoidArray(array_list[-1], numpoints, 1)
        vtk_data[-1].SetName(f)
        if f == scalar_fields.keys()[0]:
            rtg.GetPointData().SetScalars(vtk_data[-1])
        else:
            rtg.GetPointData().AddArray(vtk_data[-1])
    #end for
    for f in vector_fields:
        vtk_data.append(vtk.vtkFloatArray())
        vtk_data[-1].SetNumberOfTuples(numpoints*3)
        vtk_data[-1].SetNumberOfComponents(3)
        array_list.append(vector_fields[f].swapaxes(0,3).swapaxes(1,2).flatten().astype("float32"))
        vtk_data[-1].SetVoidArray(array_list[-1], numpoints*3, 1)
        vtk_data[-1].SetName(f)
        if f == vector_fields.keys()[0]:
            rtg.GetPointData().SetVectors(vtk_data[-1])
        else:
            rtg.GetPointData().AddArray(vtk_data[-1])
    #end for
    try:
        writer = vtk.vtkXMLRectilinearGridWriter()                                                                                              
        writer.SetFileName(vtr_name)
        writer.SetInput(rtg)
        writer.Write()
    except:
        print 'Error writing VTR file: ', vtr_name
Beispiel #9
0
 def writeVTKrg(self, ofn):
     # Escritura en disco
     off = vtk.vtkXMLRectilinearGridWriter()
     off.SetFileName(ofn)
     off.SetDataModeToAscii()
     # Esto cambia con la version de VTK
     t = self.getVTKrg()
     self.meshtal.setVTKparams(t)
     if vtk.vtkVersion().GetVTKMajorVersion() >= 6:
         off.SetInputData(t)
     else:
         off.SetInput(t)
     off.Write()
     return
def WriteVtkFile(grid, filename, time=None, xml=False, binary=False):
    """Writes a vtk Grid object to a file.
    
    Parameters:
        grid -- vtk Grid Object
        filename -- the filename for the vtk file
        xml -- write the vtk in xml format
        binary -- writes in binary format; xml should be True
    """
    if binary: xml=True
    
    if not xml:
        #write to .vtk file
        writer = vtkRectilinearGridWriter();
        writer.SetFileName(filename)
        if binary:
            print 
        writer.SetInputData(grid)
        writer.Write()
        
        if time:
            #manually add the time data
            vtk_file = open(filename, 'r+').read().split('\n')
            line_index = 0
            line = ''
            _pos = []
            while 'CELL_DATA' not in line:
                line = vtk_file[line_index]
                line_index += 1
            vtk_file.insert(line_index-1,'FIELD FieldData 1\nTime 1 1 double\n' + str(time))
            with open(filename, 'w+') as fo:
                fo.writelines('\n'.join(vtk_file))
    
    else:
        if time:
            #insert time data; this has a bug on the vtk legacy writer, manually insert time field instead for vtk legacy files.
            timeArray = vtkDoubleArray()
            timeArray.SetName('Time')
#            print time, type(time)
            timeArray.InsertNextValue(time)
            grid.GetFieldData().AddArray(timeArray)
    
        writer = vtkXMLRectilinearGridWriter();   
        if binary:
            writer.SetDataModeToBinary()
        else: writer.SetDataModeToAscii()
        print filename
        writer.SetFileName(filename)
        writer.SetInputData(grid)
        writer.Write()
Beispiel #11
0
def writeVTR(vtr_name, scalar_fields, vector_fields, Nxc, Nyc, Nzlocal,
             vtkXcoordinates, vtkYcoordinates, vtkZcoordinates, rankproc,
             numproc):
    """Writes a single VTR file per Python processor/variable

    """
    rtg = vtk.vtkRectilinearGrid()
    rtg.SetDimensions(Nxc + 1, Nyc + 1, Nzlocal)
    rtg.SetExtent(0, Nxc, 0, Nyc, rankproc * Nzc / numproc,
                  (rankproc + 1) * Nzc / numproc)
    rtg.SetXCoordinates(vtkXcoordinates)
    rtg.SetYCoordinates(vtkYcoordinates)
    rtg.SetZCoordinates(vtkZcoordinates)
    vtk_data = []
    array_list = []
    for f in scalar_fields:
        vtk_data.append(vtk.vtkFloatArray())
        vtk_data[-1].SetNumberOfTuples(numpoints)
        vtk_data[-1].SetNumberOfComponents(1)
        array_list.append(scalar_fields[f].swapaxes(
            0, 2).flatten().astype("float32"))
        vtk_data[-1].SetVoidArray(array_list[-1], numpoints, 1)
        vtk_data[-1].SetName(f)
        if f == scalar_fields.keys()[0]:
            rtg.GetPointData().SetScalars(vtk_data[-1])
        else:
            rtg.GetPointData().AddArray(vtk_data[-1])
    #end for
    for f in vector_fields:
        vtk_data.append(vtk.vtkFloatArray())
        vtk_data[-1].SetNumberOfTuples(numpoints * 3)
        vtk_data[-1].SetNumberOfComponents(3)
        array_list.append(vector_fields[f].swapaxes(0, 3).swapaxes(
            1, 2).flatten().astype("float32"))
        vtk_data[-1].SetVoidArray(array_list[-1], numpoints * 3, 1)
        vtk_data[-1].SetName(f)
        if f == vector_fields.keys()[0]:
            rtg.GetPointData().SetVectors(vtk_data[-1])
        else:
            rtg.GetPointData().AddArray(vtk_data[-1])
    #end for
    try:
        writer = vtk.vtkXMLRectilinearGridWriter()
        writer.SetFileName(vtr_name)
        writer.SetInput(rtg)
        writer.Write()
    except:
        print 'Error writing VTR file: ', vtr_name
Beispiel #12
0
    def save(self,
             fname: Union[str, Path],
             parallel: bool = True,
             compress: bool = True):
        """
        Save as VTK file.

        Parameters
        ----------
        fname : str or pathlib.Path
            Filename for writing.
        parallel : bool, optional
            Write data in parallel background process. Defaults to True.
        compress : bool, optional
            Compress with zlib algorithm. Defaults to True.

        """
        if isinstance(self.vtk_data, vtk.vtkImageData):
            writer = vtk.vtkXMLImageDataWriter()
        elif isinstance(self.vtk_data, vtk.vtkRectilinearGrid):
            writer = vtk.vtkXMLRectilinearGridWriter()
        elif isinstance(self.vtk_data, vtk.vtkUnstructuredGrid):
            writer = vtk.vtkXMLUnstructuredGridWriter()
        elif isinstance(self.vtk_data, vtk.vtkPolyData):
            writer = vtk.vtkXMLPolyDataWriter()

        default_ext = '.' + writer.GetDefaultFileExtension()
        ext = Path(fname).suffix
        writer.SetFileName(
            str(fname) + (default_ext if default_ext != ext else ''))

        if compress:
            writer.SetCompressorTypeToZLib()
        else:
            writer.SetCompressorTypeToNone()
        writer.SetDataModeToBinary()
        writer.SetInputData(self.vtk_data)

        if parallel:
            try:
                mp_writer = mp.Process(target=self._write, args=(writer, ))
                mp_writer.start()
            except TypeError:
                writer.Write()
        else:
            writer.Write()
Beispiel #13
0
def write_polydata(input_data, filename, datatype=None):
    """
    Write the given input data based on the file name extension.
    Args:
        input_data (vtkSTL/vtkPolyData/vtkXMLStructured/
                    vtkXMLRectilinear/vtkXMLPolydata/vtkXMLUnstructured/
                    vtkXMLImage/Tecplot): Input data.
        filename (str): Save path location.
        datatype (str): Additional parameter for vtkIdList objects.
    """
    # Check filename format
    fileType = filename.split(".")[-1]
    if fileType == '':
        raise RuntimeError('The file does not have an extension')

    # Get writer
    if fileType == 'stl':
        writer = vtk.vtkSTLWriter()
    elif fileType == 'vtk':
        writer = vtk.vtkPolyDataWriter()
    elif fileType == 'vts':
        writer = vtk.vtkXMLStructuredGridWriter()
    elif fileType == 'vtr':
        writer = vtk.vtkXMLRectilinearGridWriter()
    elif fileType == 'vtp':
        writer = vtk.vtkXMLPolyDataWriter()
    elif fileType == 'vtu':
        writer = vtk.vtkXMLUnstructuredGridWriter()
    elif fileType == "vti":
        writer = vtk.vtkXMLImageDataWriter()
    elif fileType == "np" and datatype == "vtkIdList":
        output_data = np.zeros(input_data.GetNumberOfIds())
        for i in range(input_data.GetNumberOfIds()):
            output_data[i] = input_data.GetId(i)
        output_data.dump(filename)
        return
    else:
        raise RuntimeError('Unknown file type %s' % fileType)

    # Set filename and input
    writer.SetFileName(filename)
    writer.SetInputData(input_data)
    writer.Update()

    # Write
    writer.Write()
Beispiel #14
0
def writeVTR(vtr_name, scalar_fields, vector_fields, Nxc, Nyc, Nzlocal, 
            vtkXcoordinates, vtkYcoordinates, vtkZcoordinates, rankproc, numproc):
    """Writes a single VTR file per Python processor/variable

    """
    rtg = vtk.vtkRectilinearGrid()
    rtg.SetDimensions(Nxc+1, Nyc+1, Nzlocal)
    rtg.SetExtent(0, Nxc, 0, Nyc, rankproc*Nzc/numproc, (rankproc+1)*Nzc/numproc)
    rtg.SetXCoordinates(vtkXcoordinates)
    rtg.SetYCoordinates(vtkYcoordinates)
    rtg.SetZCoordinates(vtkZcoordinates)
    vtk_data = []
    array_list = []
    for f in scalar_fields:
        vtk_data.append(vtk.vtkFloatArray())
        vtk_data[-1].SetNumberOfTuples(numpoints)
        vtk_data[-1].SetNumberOfComponents(1)
        array_list.append(scalar_fields[f].swapaxes(0,2).flatten().astype("float32"))
        vtk_data[-1].SetVoidArray(array_list[-1], numpoints, 1)
        vtk_data[-1].SetName(f)
        if f == scalar_fields.keys()[0]:
            rtg.GetPointData().SetScalars(vtk_data[-1])
        else:
            rtg.GetPointData().AddArray(vtk_data[-1])
    #end for
    for f in vector_fields:
        vtk_data.append(vtk.vtkFloatArray())
        vtk_data[-1].SetNumberOfTuples(numpoints*3)
        vtk_data[-1].SetNumberOfComponents(3)
        array_list.append(vector_fields[f].swapaxes(0,3).swapaxes(1,2).flatten().astype("float32"))
        vtk_data[-1].SetVoidArray(array_list[-1], numpoints*3, 1)
        vtk_data[-1].SetName(f)
        if f == vector_fields.keys()[0]:
            rtg.GetPointData().SetVectors(vtk_data[-1])
        else:
            rtg.GetPointData().AddArray(vtk_data[-1])
    #end for
    try:
        writer = vtk.vtkXMLRectilinearGridWriter()                                                                                              
        writer.SetFileName(vtr_name)
        writer.SetInput(rtg)
        writer.Write()
    except:
        print 'Error writing VTR file: ', vtr_name
Beispiel #15
0
def savePolydata(polydata, file_name, binary=False, color_array_name=None):
    """ Save a vtk polydata to a supported format file

    Parameters
    ----------
        polydata : vtkPolyData
        file_name : string
    """
    # get file extension (type)
    file_extension = file_name.split(".")[-1].lower()

    if file_extension == "vtk":
        writer = vtk.vtkPolyDataWriter()
    elif file_extension == "fib":
        writer = vtk.vtkPolyDataWriter()
    elif file_extension == "ply":
        writer = vtk.vtkPLYWriter()
    elif file_extension == "stl":
        writer = vtk.vtkSTLWriter()
    elif file_extension == "xml":
        writer = vtk.vtkXMLPolyDataWriter()
    elif file_extension == "vtp":
        writer = vtk.vtkXMLPolyDataWriter()
    elif file_extension == "vti":
        writer = vtk.vtkXMLImageDataWriter()
    elif file_extension == "vts":
        writer = vtk.vtkXMLStructuredGridWriter()
    elif file_extension == "vtu":
        writer = vtk.vtkXMLUnstructuredGridWriter()
    elif file_extension == "vtr":
        writer = vtk.vtkXMLRectilinearGridWriter()
    elif file_extension == "obj":
        raise Exception("mni obj or Wavefront obj ?")

    writer.SetFileName(file_name)
    writer.SetInputData(polydata)
    if color_array_name is not None:
        writer.SetArrayName(color_array_name)

    if binary:
        writer.SetFileTypeToBinary()
    writer.Update()
    writer.Write()
Beispiel #16
0
    def save(self, filename, binary=True):
        """
        Writes a rectilinear grid to disk.

        Parameters
        ----------
        filename : str
            Filename of grid to be written.  The file extension will select the
            type of writer to use.  ".vtk" will use the legacy writer, while
            ".vtr" will select the VTK XML writer.

        binary : bool, optional
            Writes as a binary file by default.  Set to False to write ASCII.


        Notes
        -----
        Binary files write much faster than ASCII, but binary files written on
        one system may not be readable on other systems.  Binary can be used
        only with the legacy writer.

        """
        filename = os.path.abspath(os.path.expanduser(filename))
        # Use legacy writer if vtk is in filename
        if '.vtk' in filename:
            writer = vtk.vtkRectilinearGridWriter()
            legacy = True
        elif '.vtr' in filename:
            writer = vtk.vtkXMLRectilinearGridWriter()
            legacy = False
        else:
            raise Exception('Extension should be either ".vtr" (xml) or' +
                            '".vtk" (legacy)')
        # Write
        writer.SetFileName(filename)
        writer.SetInputData(self)
        if binary and legacy:
            writer.SetFileTypeToBinary()
        writer.Write()
Beispiel #17
0
	def writeVTRFile(fileName,vtkRectilinearGrid):
	    '''Function to write vtk rectilinear grid (vtr).'''
	    Writer = vtk.vtkXMLRectilinearGridWriter()
	    Writer.SetInput(vtkRectilinearGrid)
	    Writer.SetFileName(fileName)
	    Writer.Update()
Beispiel #18
0
        vtk.vtkDoubleArray(),
    ]

    rGrid.SetDimensions(*grid)
    for i, points in enumerate(coords):
        for point in points:
            coordArray[i].InsertNextValue(point)

    rGrid.SetXCoordinates(coordArray[0])
    rGrid.SetYCoordinates(coordArray[1])
    rGrid.SetZCoordinates(coordArray[2])

    # ------------------------------------------ output result ---------------------------------------

    if name:
        writer = vtk.vtkXMLRectilinearGridWriter()
        writer.SetCompressorTypeToZLib()
        writer.SetDataModeToBinary()
        writer.SetFileName(
            os.path.join(
                os.path.split(name)[0],
                os.path.splitext(os.path.split(name)[1])[0] +
                '_{}({})'.format(options.pos, options.mode) + '.' +
                writer.GetDefaultFileExtension()))
    else:
        writer = vtk.vtkDataSetWriter()
        writer.SetHeader('# powered by ' + scriptID)
        writer.WriteToOutputStringOn()

    if vtk.VTK_MAJOR_VERSION <= 5: writer.SetInput(rGrid)
    else: writer.SetInputData(rGrid)
Beispiel #19
0
def getcutout(request, webargs):
    params = "parameters=%s" % webargs
    w = webargs.split("/")
    ts = int(w[3].split(',')[0])
    te = int(w[3].split(',')[1])
    #o = odbccutout.OdbcCutout()
    if ((len(w) >= 8) and (w[7] == 'vtk')):    
        #Setup temporary file (would prefer an in-memory buffer, but this will have to do for now)
        if (len(w) >= 10):
            tspacing = int(w[8].split(",")[0])
        else:
            tspacing = 1
        cfieldlist = w[2].split(",")
        firstval = cfieldlist[0]
        if ((firstval == 'cvo') or (firstval == 'qcc')): #we may need to return a vtp file
            tmp = NamedTemporaryFile(suffix='.vtp')
            suffix = 'vtp'
            writer = vtk.vtkXMLPolyDataWriter()                         
            outfile = w[7] + '-contour'
        elif (w[1] == "channel"):
	    tmp = NamedTemporaryFile(suffix='.vtr')
	    suffix = 'vtr'
	    writer = vtk.vtkXMLRectilinearGridWriter()
	    outfile = 'cutout' + w[7]
        else:
            tmp = NamedTemporaryFile(suffix='.vti')
            suffix = 'vti'
            writer = vtk.vtkXMLImageDataWriter()                        
            outfile = 'cutout' + w[7]        
        writer.SetFileName(tmp.name)
        writer.SetCompressorTypeToZLib()
        writer.SetDataModeToBinary()
        #if multiple timesteps, zip the file.
        if ((te-ts) > 1):
            #Write each timestep to file and read it back in.  Seems to be the only way I know how to put all timesteps in one file for now
            #Create a timestep for each file and then send the user a zip file
            ziptmp = NamedTemporaryFile(suffix='.zip')
            z = zipfile.ZipFile(ziptmp.name, 'w')
            for timestep in range (ts,te, tspacing ):            
                image = odbccutout.OdbcCutout().getvtkimage(webargs, timestep)
                writer.SetInputData(image)
                writer.SetFileName(tmp.name)                        
                writer.Write()
                #Now add this file to the zipfile
                z.write(tmp.name, 'cutout' + str(timestep) + '.' + suffix)
            z.close()
            ct = 'application/zip'
            suffix = 'zip'
            response = HttpResponse(ziptmp, content_type=ct)

        else:
            image = odbccutout.OdbcCutout().getvtkimage(webargs, ts)
            writer.SetInputData(image)
            writer.SetFileName(tmp.name)                        
            writer.Write()
            ct = 'data/vtk'
            response = HttpResponse(tmp, content_type=ct)
        response['Content-Disposition'] = 'attachment;filename=' +  outfile +'.' + suffix
    else: #for backward compatibility, we serve hdf5 if not specified
        #Create an HDF5 file here
        h5file = odbccutout.OdbcCutout().gethdf(webargs)
        response = HttpResponse(h5file, content_type='data/hdf5')
        attach = 'attachment;filename=' + w[1] + '.h5'
        response['Content-Disposition'] = attach

    return response
Beispiel #20
0
def write_vtr(data, fname='tmp/data.vtr', down_sampling=(5, 5, 5)):
    """
    Write the reconstructed data (img stackes) to vtr file (retangular grid)

    Parameters
    ----------
    data          :  np.3darray
        reconstructed 3D image stacks with axis=0 as the omega
    fname         :  str
        file name of the output vtr file
    down_sampling :  tuple 
        down sampling steps along three axes

    Returns
    -------
    None
    """
    # vtk is only used here, therefore doing an in module import
    import vtk
    from vtk.util import numpy_support
    
    # convert to unit8 can significantly reduce the output vtr file
    # size, or just do a severe down-sampling
    data = _normalize_imgstacks(data[::down_sampling[0], 
                                     ::down_sampling[1], 
                                     ::down_sampling[2],]) * 255
    
    # --init rectangular grid
    rGrid = vtk.vtkRectilinearGrid()
    coordArray = [vtk.vtkDoubleArray(),
                  vtk.vtkDoubleArray(),
                  vtk.vtkDoubleArray(),
                 ]
    coords = np.array([np.arange(data.shape[i]) for i in range(3)])
    coords = [0.5 * np.array([3.0 * coords[i][0] - coords[i][0 + int(len(coords[i]) > 1)]] + \
                             [coords[i][j-1] + coords[i][j] for j in range(1,len(coords[i]))] + \
                             [3.0 * coords[i][-1] - coords[i][-1 - int(len(coords[i]) > 1)]]
                            ) 
              for i in range(3)
             ]
    grid = np.array(list(map(len,coords)),'i')
    rGrid.SetDimensions(*grid)
    for i,points in enumerate(coords):
        for point in points:
            coordArray[i].InsertNextValue(point)

    rGrid.SetXCoordinates(coordArray[0])
    rGrid.SetYCoordinates(coordArray[1])
    rGrid.SetZCoordinates(coordArray[2])
    
    # vtk requires x to be the fast axis
    # NOTE:
    #    Proper coordinate transformation is required to connect the 
    #    tomography data with other down-stream analysis (such as FF-HEDM
    #    and NF-HEDM).
    imgstacks = np.swapaxes(data, 0, 2)
    
    VTKarray = numpy_support.numpy_to_vtk(num_array=imgstacks.flatten().astype(np.uint8),
                                          deep=True,
                                          array_type=vtk.VTK_UNSIGNED_CHAR,
                                         )
    VTKarray.SetName('img')
    rGrid.GetCellData().AddArray(VTKarray)
    
    rGrid.Modified()
    if vtk.VTK_MAJOR_VERSION <= 5: 
        rGrid.Update()

    # output to file
    writer = vtk.vtkXMLRectilinearGridWriter()
    writer.SetFileName(fname)
    writer.SetDataModeToBinary()
    writer.SetCompressorTypeToZLib()
    if vtk.VTK_MAJOR_VERSION <= 5: 
        writer.SetInput(rGrid)
    else:                          
        writer.SetInputData(rGrid)
    writer.Write()
Beispiel #21
0
def write_polydata(input_data, filename, datatype=None, file_type="ascii"):
    """
    Write the given input data based on the file name extension.

    Args:
        file_type (string): Filetype of output
        input_data (vtkSTL/vtkPolyData/vtkXMLStructured/
                    vtkXMLRectilinear/vtkXMLPolydata/vtkXMLUnstructured/
                    vtkXMLImage/Tecplot): Input data.
        filename (str): Save path location.
        datatype (str): Additional parameter for vtkIdList objects.
    """
    # Check filename format
    fileType = filename.split(".")[-1]
    if fileType == '':
        raise RuntimeError('The file does not have an extension')

    # Get writer
    if fileType == 'stl':
        writer = vtk.vtkSTLWriter()

    elif fileType == 'vtk':
        # Set reader based on data type
        if isinstance(input_data, vtk.vtkUnstructuredGrid):
            writer = vtk.vtkUnstructuredGridWriter()
        elif isinstance(input_data, vtk.vtkStructuredGrid):
            writer = vtk.vtkStructuredGridWriter()
        elif isinstance(input_data, vtk.vtkRectilinearGrid):
            writer = vtk.vtkRectilinearGridWriter()
        elif isinstance(input_data, vtk.vtkStructuredPoints) or \
                isinstance(input_data, vtk.vtkImageData):
            writer = vtk.vtkStructuredPointsWriter()
        elif isinstance(input_data, vtk.vtkPolyData):
            writer = vtk.vtkPolyDataWriter()

        if file_type.lower() == "ascii":
            writer.SetFileType(1)
        elif file_type.lower() == "binary":
            writer.SetFileType(0)
        else:
            raise ValueError("Invalid file type, can only be ascii or binary")

    elif fileType == 'vts':
        writer = vtk.vtkXMLStructuredGridWriter()
    elif fileType == 'vtr':
        writer = vtk.vtkXMLRectilinearGridWriter()
    elif fileType == 'vtp':
        writer = vtk.vtkXMLPolyDataWriter()
    elif fileType == 'vtu':
        writer = vtk.vtkXMLUnstructuredGridWriter()
    elif fileType == "vti":
        writer = vtk.vtkXMLImageDataWriter()
    elif fileType == "np" and datatype == "vtkIdList":
        output_data = np.zeros(input_data.GetNumberOfIds())
        for i in range(input_data.GetNumberOfIds()):
            output_data[i] = input_data.GetId(i)
        output_data.dump(filename)
        return
    else:
        raise RuntimeError('Unknown file type %s' % fileType)

    # Set filename and input
    writer.SetFileName(filename)
    writer.SetInputData(input_data)
    writer.Update()

    # Write
    writer.Write()
Beispiel #22
0
def BFDTD_h5_to_vts(h5file, basepath, total_lattice_size=None, requested_dataset=[], verbosity=0, x_relative_range=[0,1], y_relative_range=[0,1], z_relative_range=[0,1], real_units=False, dry_run=False):
  '''
    Converts BFDTD h5 files to VTS files.
    .. todo:: need py2-compatible bfdtd-parser for direct creation
    .. todo:: when selecting a smaller mesh region for speed, we also need to change the size of the VTS grid (but keep coords correct)...
  '''
  
  requested_arrays = ['material', 'E', 'electric_energy_density']
  #requested_arrays = []
  #x_relative_range = [1/3, 2/3]
  #y_relative_range = [1/3, 2/3]
  #z_relative_range = [1/3, 2/3]
  print('x_relative_range: {}'.format(x_relative_range))
  print('y_relative_range: {}'.format(y_relative_range))
  print('z_relative_range: {}'.format(z_relative_range))
  
  print('{} -> {}.vts'.format(h5file, basepath))
  
  # read in .h5 file
  with h5py.File(h5file, "r") as HDF5_file_object:
    print('Reading from ' + h5file)
    
    (mylattice, complete_dataset_list) = h5_setupLattice(HDF5_file_object, total_lattice_size, requested_dataset)
    (Nx, Ny, Nz) = mylattice.getResolution()
    (a1, a2, a3) = mylattice.getLatticeVectors()
    (xmesh, ymesh, zmesh) = mylattice.getMesh()
    Npoints = Nx*Ny*Nz
    
    # create the vtkPoints structure for the coordinates
    #points = vtk.vtkPoints()
    #points.SetNumberOfPoints(Npoints)

    if requested_dataset:
      dataset_list = requested_dataset
    else:
      dataset_list = complete_dataset_list

    material_data = None
    for dataset_name in dataset_list:
      current_data = HDF5_file_object[dataset_name]
      if 'material' in current_data.dtype.names:
        material_data = current_data
        break
        
    if material_data:
      print('Found material data in: {}'.format(material_data.name))
    else:
      print('Warning: No material data found. No electric energy density data can be calculated.')

    for dataset_name in dataset_list:
      data = HDF5_file_object[dataset_name]

      # create VTK data arrays
      print('Creating VTK data arrays...')
      available_arrays = []
      
      if data.dtype.names == ('E', 'H', 'Pow', 'material'):
        print('time snapshot mode')
        if 'E' in requested_arrays:
          E_array = createvtkArray('E', Npoints, ('x', 'y', 'z'))
          available_arrays.append(E_array)
        if 'H' in requested_arrays:
          H_array = createvtkArray('H', Npoints, ('x', 'y', 'z'))
          available_arrays.append(H_array)
        if 'Pow' in requested_arrays:
          Pow_array = createvtkArray('Pow', Npoints, ('Pow',))
          available_arrays.append(Pow_array)
        if 'material' in requested_arrays:
          material_array = createvtkArray('material', Npoints, ('material',))
          available_arrays.append(material_array)
        #available_arrays = (E_array, H_array, Pow_array, material_array)
      
      elif data.dtype.names == ('E', 'H'):
        print('frequency snapshot mode')
        if 'E' in requested_arrays:
          (E_re_array, E_im_array, E_mod_array, E_phase_array) = createComplexArrays('E', Npoints)
          available_arrays.extend([E_re_array, E_im_array, E_mod_array, E_phase_array])
        if 'H' in requested_arrays:
          (H_re_array, H_im_array, H_mod_array, H_phase_array) = createComplexArrays('H', Npoints)
          available_arrays.extend([H_re_array, H_im_array, H_mod_array, H_phase_array])
        if 'S' in requested_arrays:
          (S_re_array, S_im_array, S_mod_array, S_phase_array) = createComplexArrays('S', Npoints)
          available_arrays.extend([S_re_array, S_im_array, S_mod_array, S_phase_array])
        #available_arrays = [E_re_array, E_im_array, E_mod_array, E_phase_array,
                            #H_re_array, H_im_array, H_mod_array, H_phase_array,
                            #S_re_array, S_im_array, S_mod_array, S_phase_array]
        if material_data:
          if 'electric_energy_density' in requested_arrays:
            electric_energy_density_array = createvtkArray('electric_energy_density', Npoints, ('electric_energy_density',))
            available_arrays.append(electric_energy_density_array)
          if 'magnetic_energy_density' in requested_arrays:
            magnetic_energy_density_array = createvtkArray('magnetic_energy_density', Npoints, ('magnetic_energy_density',))
            available_arrays.append(magnetic_energy_density_array)

      else:
        raise Exception('Unsupported data type.')

      print('...done')
            
      last_info_time = time.time()
      
      x_range = range( int(round(x_relative_range[0]*Nx)), int(round(x_relative_range[1]*Nx)) )
      y_range = range( int(round(y_relative_range[0]*Ny)), int(round(y_relative_range[1]*Ny)) )
      z_range = range( int(round(z_relative_range[0]*Nz)), int(round(z_relative_range[1]*Nz)) )
      Nx_partial = len(x_range)
      Ny_partial = len(y_range)
      Nz_partial = len(z_range)
      Npoints_partial = Nx_partial*Ny_partial*Nz_partial
      
      print( 'Range to fill:' )
      print( 'x: {} -> size={}/{}'.format((x_range[0], x_range[-1]), Nx_partial, Nx) )
      print( 'y: {} -> size={}/{}'.format((y_range[0], y_range[-1]), Ny_partial, Ny) )
      print( 'z: {} -> size={}/{}'.format((z_range[0], z_range[-1]), Nz_partial, Nz) )
      print( 'total points to fill: {}/{}'.format(Npoints_partial, Npoints) )
      
      if dry_run:
        return
      
      print('Starting loops')
      # fill the vtkPoints and vtkScalarArray
      for k in z_range: #range(Nz):
        for j in y_range: #range(Ny):
          for i in x_range: #range(Nx):
      #for k in range(Nz):
        #for j in range(Ny):
          #for i in range(Nx):
            
            offset = i + j*Nx + k*Nx*Ny
            #coord = xmesh[i]*a1 + ymesh[j]*a2 + zmesh[k]*a3
            #points.SetPoint(offset, coord)

            if 'E' in data.dtype.names:
              E = data[i, j, k]['E']
            if 'H' in data.dtype.names:
              H = data[i, j, k]['H']
            if 'Pow' in data.dtype.names:
              if 'Pow' in requested_arrays:
                Pow_array.SetTuple1(offset, data[i, j, k]['Pow'])
            if 'material' in data.dtype.names:
              if 'material' in requested_arrays:
                material_array.SetTuple1(offset, data[i, j, k]['material'])

            if data.dtype.names == ('E', 'H', 'Pow', 'material'):
              if 'E' in requested_arrays:
                E_array.SetTuple3(offset, *E)
              if 'H' in requested_arrays:
                H_array.SetTuple3(offset, *H)
            
            elif data.dtype.names == ('E', 'H'):
              S = numpy.cross(E, numpy.conj(H))
              
              if 'E' in requested_arrays:
                E_mod = setTupleComplex(offset, E, E_re_array, E_im_array, E_mod_array, E_phase_array)
              if 'H' in requested_arrays:
                H_mod = setTupleComplex(offset, H, H_re_array, H_im_array, H_mod_array, H_phase_array)
              if 'S' in requested_arrays:
                S_mod = setTupleComplex(offset, S, S_re_array, S_im_array, S_mod_array, S_phase_array)

              if material_data:
                # We could use numpy.vdot(a,a) for the conjugate dot product with real/absolute, but since we use absolute() before anyway, we may as well use the resulting |Ei| values.
                if 'electric_energy_density' in requested_arrays:
                  if real_units:
                    epsilon = material_data[i, j, k]['material']*constants.physcon.value('elec-const')
                  else:
                    epsilon = material_data[i, j, k]['material']
                  electric_energy_density = epsilon*numpy.dot(E_mod, E_mod)
                  electric_energy_density_array.SetTuple1(offset, electric_energy_density)
                if 'magnetic_energy_density' in requested_arrays:
                  if real_units:
                    mu = constants.physcon.value('magn-const')
                  else:
                    mu = 1
                  magnetic_energy_density = mu*numpy.dot(H_mod, H_mod)
                  magnetic_energy_density_array.SetTuple1(offset, magnetic_energy_density)

            else:
              raise Exception('Unsupported data type.')
            
            if time.time() - last_info_time > 5 or verbosity > 1:
              #print('Progress: {}/{} = {} %'.format(offset+1, Npoints, 100*(offset+1)/Npoints))
              offset_partial = (i-x_range[0]) + (j-y_range[0])*Nx_partial + (k-z_range[0])*Nx_partial*Ny_partial
              print('Progress: {}/{} = {} %'.format(offset_partial+1, Npoints_partial, 100*(offset_partial+1)/Npoints_partial))
              last_info_time = time.time()
      
      print('Loops done.')
      
      # create structured grid
      #dataset_vts = vtk.vtkStructuredGrid()
      #dataset_vts.SetDimensions(Nx, Ny, Nz)
      #dataset_vts.SetPoints(points)

      # create rectilinear grid
      xCoords = vtkScalarArray()
      for i in range(len(xmesh)):
        xCoords.InsertNextValue(xmesh[i])
      
      yCoords = vtkScalarArray()
      for i in range(len(ymesh)):
        yCoords.InsertNextValue(ymesh[i])
      
      zCoords = vtkScalarArray()
      for i in range(len(zmesh)):
        zCoords.InsertNextValue(zmesh[i])

      dataset_vtr = vtk.vtkRectilinearGrid()
      dataset_vtr.SetDimensions(len(xmesh),len(ymesh),len(zmesh))
      dataset_vtr.SetXCoordinates(xCoords)
      dataset_vtr.SetYCoordinates(yCoords)
      dataset_vtr.SetZCoordinates(zCoords)
      
      for A in available_arrays:
        dataset_vtr.GetPointData().AddArray(A)
      
      # write out VTK file(s)
      basepath_snapshot = basepath + data.name.replace('/','_')

      #writer_vts = vtk.vtkXMLStructuredGridWriter()
      #writer_vts.SetFileName(basepath_snapshot + '.' + writer_vts.GetDefaultFileExtension())
      #writer_vts.SetInputData(dataset_vts)
      #writer_vts.Write()
      
      writer_vtr = vtk.vtkXMLRectilinearGridWriter()
      writer_vtr.SetFileName(basepath_snapshot + '.' + writer_vtr.GetDefaultFileExtension())
      writer_vtr.SetInputData(dataset_vtr)
      writer_vtr.Write()

      print('{} -> {}'.format(data.name, writer_vtr.GetFileName()))

    return
Beispiel #23
0
def main():

    if len(argv) == 1:
        print help_note
        return
    else:
        mfiles = argv[1:]

    # normalize to 400 W
    # c1 = 3.1567674e6 # W/MeV
    c1 = (
        400e6  # Kinetic neutron power, W
        * (40.0 / 360.0)  # 40 grad sector
        / 14.0791)  # mean neutron energy, MeV
    c2 = c1 / 1.60218e-13  # Conversion factor, J/MeV

    print normalization_note.format(c1, c2)

    # mb = vtk.vtkMultiBlockDataSet()
    # af = vtk.vtkAppendFilter()
    #
    # nblocks = 0
    for meshtal in mfiles:
        print 'Reading ', meshtal,

        title, nps, td = read_meshtal(meshtal, use_uncertainties=False)
        print 'complete'

        for tn, t in td.items():
            if t.geom.lower() not in ('xyz', 'rect'):
                continue

            vals = array(t.values)
            errs = array(t.errors)

            # reshape arrays, to account for energy bins:
            sh = (len(t.emesh), len(t.imesh), len(t.jmesh), len(t.kmesh))

            if sh[0] > 1:
                print 'Meshtally {} contains {} energy bins. Only "total" is written to vtk file'.format(
                    tn, sh[0])

            rvals = reshape(vals, sh)
            rerrs = reshape(errs, sh)

            # prepare grid boundaries
            x = vtk.vtkDoubleArray()
            y = vtk.vtkDoubleArray()
            z = vtk.vtkDoubleArray()
            x.SetName('x')
            y.SetName('y')
            z.SetName('z')
            for a, i0, l in ((x, t.origin.x, t.imesh),
                             (y, t.origin.y, t.jmesh), (z, t.origin.z,
                                                        t.kmesh)):
                for v in [i0] + l:
                    a.InsertNextValue(v)

            # put boundaries and data into VTK rectilinear grid
            grid = vtk.vtkRectilinearGrid()
            grid.SetDimensions(x.GetNumberOfTuples(), y.GetNumberOfTuples(),
                               z.GetNumberOfTuples())
            grid.SetXCoordinates(x)
            grid.SetYCoordinates(y)
            grid.SetZCoordinates(z)

            # prepare array for tally values and errors
            # Value and error will be rwitten as separate scalar arrays. In this form the threshold
            # filter can be applied in paraview. This filter cannot be applied to an array of vectors.
            val = vtk.vtkDoubleArray()

            # Data arrays containing values and errors should heve the same name
            # for all datasets. In this case it is more simple to replace one data
            # set with another one in the paraview state. WHen datasets have
            # different names, one needs to change data arrays to be displayed
            # manually for all views.

            # val.SetName('{} t{} val'.format(meshtal, tn))
            # val.SetName('t{} val'.format(tn))
            val.SetName('val')
            val.SetNumberOfComponents(1)
            val.SetNumberOfTuples(grid.GetNumberOfCells())

            err = vtk.vtkDoubleArray()
            # err.SetName('{} t{} err'.format(meshtal, tn))
            # err.SetName('t{} err'.format(tn))
            err.SetName('err')
            err.SetNumberOfComponents(1)  # value and rel.err.
            err.SetNumberOfTuples(grid.GetNumberOfCells())

            # Put tally results to values array in particular order
            xlen = x.GetNumberOfTuples() - 1
            ylen = y.GetNumberOfTuples() - 1
            zlen = z.GetNumberOfTuples() - 1
            ival = 0  # index for meshtal
            vmax = max(t.values)
            vmin = vmax
            for i in range(xlen):
                for j in range(ylen):
                    for k in range(zlen):
                        idx = grid.ComputeCellId((i, j, k))
                        # hn = t.values[ival]
                        # en = t.errors[ival]
                        hn = rvals[-1, i, j, k]
                        en = rerrs[-1, i, j, k]

                        # Replace zero values and zero errors with NaN:
                        if en > 0:
                            # compute non-negative min
                            if hn < vmin:
                                vmin = hn
                        # else:
                        #     # Replace zero values
                        #     hn = -1.0
                        #     en = -1.0

                        val.SetTuple(idx, (hn, ))
                        err.SetTuple(idx, (en, ))
                        ival += 1

            # Field data to store meshtal metadata
            df = vtk.vtkStringArray()
            df.SetName('Meshtal description')
            df.SetNumberOfTuples(4)
            df.SetValue(0, 'Meshtal file {}, tally {}'.format(meshtal, tn))
            df.SetValue(1, title)
            df.SetValue(2, str(nps))
            df.SetValue(3, 'min: {}, max: {}'.format(vmin, vmax))

            # Attach values to the grid
            grid.GetCellData().AddArray(val)
            grid.GetCellData().AddArray(err)
            grid.GetFieldData().AddArray(df)

            # # Attach current grid to multigrid
            # mb.SetBlock(nblocks, grid)
            # af.AddInputData(grid)
            # nblocks += 1

            # write to file:
            writer = vtk.vtkXMLRectilinearGridWriter()
            if _vtkVersion[0] == '6':
                writer.SetInputData(grid)
            else:
                # _vtkVersion[0] == '5':
                writer.SetInput(grid)
            writer.SetFileName('{}_t{}.vtr'.format(meshtal, tn))
            ws = writer.Write()
            if ws == 1:
                print 'Tally {} from {}: non-negative range from {:12.5e} to {:12.5e}'.format(
                    tn, writer.GetFileName(), vmin, vmax)
            else:
                print 'Failed to write meshtally {} from {}'.format(
                    tn, writer.GetFileName())
Beispiel #24
0
def rectangular(fname, xbounds, ybounds, zbounds, vals, errs=None, descr=[]):
    """
    Write rectangular data to file `fname`.

    Arrays xbounds, ybounds and zbounds are boundary coordinates.  Array `vals`
    is a 3-dimentional array of the shape (len(x)-1, len(y)-1, len(z)-1).

    Put strings from `descr` as description of the data.
    """
    # prepare grid boundaries
    x = vtk.vtkDoubleArray()
    y = vtk.vtkDoubleArray()
    z = vtk.vtkDoubleArray()
    x.SetName('x')
    y.SetName('y')
    z.SetName('z')
    for v in xbounds:
        x.InsertNextValue(v)
    for v in ybounds:
        y.InsertNextValue(v)
    for v in zbounds:
        z.InsertNextValue(v)

    # put boundaries and data into VTK rectilinear grid
    grid = vtk.vtkRectilinearGrid()
    grid.SetDimensions(x.GetNumberOfTuples(),
                       y.GetNumberOfTuples(),
                       z.GetNumberOfTuples())
    grid.SetXCoordinates(x)
    grid.SetYCoordinates(y)
    grid.SetZCoordinates(z)

    # prepare array for tally values and errors
    # Value and error will be rwitten as separate scalar arrays. In this form
    # the threshold filter can be applied in paraview. This filter cannot be
    # applied to an array of vectors.
    val = vtk.vtkDoubleArray()

    # Data arrays containing values and errors should heve the same name
    # for all datasets. In this case it is more simple to replace one data
    # set with another one in the paraview state. WHen datasets have
    # different names, one needs to change data arrays to be displayed
    # manually for all views.
    val.SetName('val')
    val.SetNumberOfComponents(1)
    val.SetNumberOfTuples(grid.GetNumberOfCells())

    if errs is not None:
        err = vtk.vtkDoubleArray()
        err.SetName('err')
        err.SetNumberOfComponents(1)
        err.SetNumberOfTuples(grid.GetNumberOfCells())

    # Put tally results to values array in particular order
    xlen = x.GetNumberOfTuples() - 1
    ylen = y.GetNumberOfTuples() - 1
    zlen = z.GetNumberOfTuples() - 1
    vmax = amax(vals[vals > 0.0])
    vmin = amin(vals[vals > 0.0])
    for i in range(xlen):
        for j in range(ylen):
            for k in range(zlen):
                idx = grid.ComputeCellId((i, j, k))
                hn = vals[i, j, k]
                if errs is not None:
                    en = errs[i, j, k]

                val.SetTuple(idx, (hn, ))
                if errs is not None:
                    err.SetTuple(idx, (en, ))

    # Field data to store metadata
    df = vtk.vtkStringArray()
    df.SetName('Description')
    df.SetNumberOfTuples(len(descr) + 2)
    df.SetValue(0, 'positive min: {}'.format(vmin))
    df.SetValue(1, 'positive max: {}'.format(vmax))
    for i, s in enumerate(descr):
        df.SetValue(i + 2, s)

    # Attach values to the grid
    grid.GetCellData().AddArray(val)
    if errs is not None:
        grid.GetCellData().AddArray(err)
    grid.GetFieldData().AddArray(df)

    # write to file:
    writer = vtk.vtkXMLRectilinearGridWriter()
    if _vtkVersion[0] in '68':
        writer.SetInputData(grid)
    else:
        # _vtkVersion[0] == '5':
        writer.SetInput(grid)
    writer.SetFileName(fname)
    ws = writer.Write()
    return ws
Beispiel #25
0
def write_vtr(data, fname='tmp/data.vtr', down_sampling=(5, 5, 5)):
    """
    Write the reconstructed data (img stackes) to vtr file (retangular grid)

    Parameters
    ----------
    data          :  np.3darray
        reconstructed 3D image stacks with axis=0 as the omega
    fname         :  str
        file name of the output vtr file
    down_sampling :  tuple 
        down sampling steps along three axes

    Returns
    -------
    None
    """
    # vtk is only used here, therefore doing an in module import
    import vtk
    from vtk.util import numpy_support
    
    # convert to unit8 can significantly reduce the output vtr file
    # size, or just do a severe down-sampling
    data = _normalize_imgstacks(data[::down_sampling[0], 
                                     ::down_sampling[1], 
                                     ::down_sampling[2],]) * 255
    
    # --init rectangular grid
    rGrid = vtk.vtkRectilinearGrid()
    coordArray = [vtk.vtkDoubleArray(),
                  vtk.vtkDoubleArray(),
                  vtk.vtkDoubleArray(),
                 ]
    coords = np.array([np.arange(data.shape[i]) for i in range(3)])
    coords = [0.5 * np.array([3.0 * coords[i][0] - coords[i][0 + int(len(coords[i]) > 1)]] + \
                             [coords[i][j-1] + coords[i][j] for j in range(1,len(coords[i]))] + \
                             [3.0 * coords[i][-1] - coords[i][-1 - int(len(coords[i]) > 1)]]
                            ) 
              for i in range(3)
             ]
    grid = np.array(list(map(len,coords)),'i')
    rGrid.SetDimensions(*grid)
    for i,points in enumerate(coords):
        for point in points:
            coordArray[i].InsertNextValue(point)

    rGrid.SetXCoordinates(coordArray[0])
    rGrid.SetYCoordinates(coordArray[1])
    rGrid.SetZCoordinates(coordArray[2])
    
    # vtk requires x to be the fast axis
    # NOTE:
    #    Proper coordinate transformation is required to connect the 
    #    tomography data with other down-stream analysis (such as FF-HEDM
    #    and NF-HEDM).
    imgstacks = np.swapaxes(data, 0, 2)
    
    VTKarray = numpy_support.numpy_to_vtk(num_array=imgstacks.flatten().astype(np.uint8),
                                          deep=True,
                                          array_type=vtk.VTK_UNSIGNED_CHAR,
                                         )
    VTKarray.SetName('img')
    rGrid.GetCellData().AddArray(VTKarray)
    
    rGrid.Modified()
    if vtk.VTK_MAJOR_VERSION <= 5: 
        rGrid.Update()

    # output to file
    writer = vtk.vtkXMLRectilinearGridWriter()
    writer.SetFileName(fname)
    writer.SetDataModeToBinary()
    writer.SetCompressorTypeToZLib()
    if vtk.VTK_MAJOR_VERSION <= 5: 
        writer.SetInput(rGrid)
    else:                          
        writer.SetInputData(rGrid)
    writer.Write()
Beispiel #26
0
f_vals = vtk.vtkDoubleArray()
f_vals.SetName("function_vals")
f_vals.SetNumberOfValues(grid.GetNumberOfPoints())

# prepare the grid_time FieldData
grid_time = vtk.vtkDoubleArray()
grid_time.SetName("grid_time")
grid_time.InsertNextValue(0)



for i in range(len(t)):
    fname = vtr_base + str(i).zfill(int(math.log10(len(t)+1))) + ".vtr"
    if opts.verbose:
        sys.stdout.write("Outputting to " + fname + "\n");
    writer = vtk.vtkXMLRectilinearGridWriter()
    writer.SetFileName(fname)

    # insert the grid_time field data
    grid_time.InsertValue(0, t[i])
    grid.GetFieldData().AddArray(grid_time)

    # construct the function_vals and insert it
    for ptid in range(grid.GetNumberOfPoints()):
        xyz = grid.GetPoint(ptid)
        f_vals.InsertValue(ptid, fcn[grid_index[xyz] + i*nx*ny*nz])
    grid.GetPointData().AddArray(f_vals)

    # update and write the file
    grid.Update()
    writer.SetInputConnection(grid.GetProducerPort())
Beispiel #27
0
 def getvtk(self, ci):
     contour = False
     firstval = ci.datafields.split(',')[0]
     if ((firstval == 'cvo') or (firstval == 'qcc') or (firstval == 'pcvo')): #we may need to return a vtp file
         tmp = NamedTemporaryFile(suffix='.vtp')
         suffix = 'vtp'
         writer = vtk.vtkXMLPolyDataWriter()
         outfile = ci.dataset + '-contour'
         contour = True
     elif (ci.dataset == "channel"):
         tmp = NamedTemporaryFile(suffix='.vtr')
         suffix = 'vtr'
         writer = vtk.vtkXMLRectilinearGridWriter()
         outfile = ci.dataset
     else:
         tmp = NamedTemporaryFile(suffix='.vti')
         suffix = 'vti'
         writer = vtk.vtkXMLImageDataWriter()                        
         outfile = ci.dataset        
     writer.SetFileName(tmp.name)
     writer.SetCompressorTypeToZLib()
     writer.SetDataModeToBinary()
     #If a preview, change the writer to write an ascii oldschool vtk format
     if (firstval == 'pcvo'):
         suffix = 'vtk'
         writer = vtk.vtkPolyDataWriter()
         writer.SetFileTypeToASCII()
     #if multiple timesteps, zip the file.
     if (ci.tlen > 1):
         #Write each timestep to file and read it back in.  Seems to be the only way I know how to put all timesteps in one file for now
         #Create a timestep for each file and then send the user a zip file
         ziptmp = NamedTemporaryFile(suffix='.zip')
         z = zipfile.ZipFile(ziptmp.name, 'w') #, 'allowZip64' this should be added to get zipfiles > 2gb.  Should we allow this?
         for timestep in range (ci.tstart,ci.tstart+ci.tlen, ci.tstep ):
             if (contour == True): #If we have a contour, call the cache version.
                 image = self.getcachedcontour(ci, timestep)
             else:     
                 image = self.getvtkdata(ci, timestep)
             writer.SetInputData(image)
             writer.SetFileName(tmp.name)                        
             writer.Write()
             #Now add this file to the zipfile
             z.write(tmp.name, 'cutout' + str(timestep) + '.' + suffix)
             image = None
             
         z.close()
         #Try to clean up here
         writer = None
         ct = 'application/zip'
         suffix = 'zip'
         response = HttpResponse(ziptmp, content_type=ct)            
     else:
         #print("Single Timestep")
         if (contour == True): #If we have a contour, call the cache version.
             image = self.getcachedcontour(ci, ci.tstart)
         else:     
             image = self.getvtkdata(ci, ci.tstart)            
         writer.SetInputData(image)
         writer.SetFileName(tmp.name)
         writer.EncodeAppendedDataOff()
         writer.Write()
         ct = 'applicaton/' + suffix
         response = HttpResponse(tmp, content_type=ct)
     response['Content-Disposition'] = 'attachment;filename=' +  outfile +'.' + suffix
     return response