Пример #1
0
def write_unstructured_grid(filename,
                            mesh,
                            cdata,
                            nEle,
                            EFs,
                            time,
                            verbose,
                            outline=False,
                            cut=[]):
    writer = vtk.vtkXMLUnstructuredGridWriter()
    ##    writer.SetDataModeToBinary()
    writer.SetDataModeToAscii()
    writer.SetFileName(filename + '.vtu')
    extract = vtk.vtkExtractCells()
    extract.SetInputData(mesh)
    eleList = vtk.vtkIdList()
    EF = cdata.GetArray('EF')
    for k in range(nEle):
        if (EFs[EF.GetValue(k)][0] < time and
                EFs[EF.GetValue(k)][1] >= time) or (EFs[EF.GetValue(k)][0] == 0
                                                    and time == 0):
            a = eleList.InsertNextId(k)
    extract.SetCellList(eleList)
    grid = extract.GetOutputPort()

    if outline:
        gf = vtk.vtkGeometryFilter()
        gf.SetInputConnection(grid)
        cpd = vtk.vtkCleanPolyData()
        cpd.SetInputConnection(gf.GetOutputPort())
        cpd.Update()
        af = vtk.vtkAppendFilter()
        af.AddInputData(cpd.GetOutput())
        grid = af.GetOutputPort()
    elif len(cut):
        plane = vtk.vtkPlane()
        plane.SetOrigin(cut[0])
        plane.SetNormal(cut[1])
        cutter = vtk.vtkCutter()
        cutter.SetInputConnection(grid)
        cutter.SetCutFunction(plane)
        cutter.Update()
        cpd = vtk.vtkCleanPolyData()
        cpd.SetInputConnection(cutter.GetOutputPort())
        cpd.Update()
        af = vtk.vtkAppendFilter()
        af.AddInputData(cpd.GetOutput())
        grid = af.GetOutputPort()
        writer.SetFileName(filename + '_cut.vtu')

    writer.SetInputConnection(grid)
    writer.Write()
    if not verbose:
        print('%i elements written to %s' %
              (eleList.GetNumberOfIds(), filename))
Пример #2
0
def HDF5toVTKLumen():

    cellType = "ec"     # Both ATP and WSS maps use EC mesh    
    input_meshes = []

    # Read input EC meshes.
    for in_file in input_mesh_files[cellType]:
        reader = vtk.vtkXMLPolyDataReader()
        reader.SetFileName(in_file)
        reader.Update()

        input_meshes += [reader.GetOutput()]
                
        # Only add parent mesh for a tube (non-bifurcation)
        if branches == 1:
            break   
    
    append_filter = vtk.vtkAppendFilter()
        
    for branch in range(branches):
        
        species_array = []
        
        mesh = vtk.vtkPolyData()
        mesh.DeepCopy(input_meshes[branch])

        # The base input h5 filename given the branch and from which writer it came on said branch.
        h5_file_base = base_names[output] + '_b_' + str(branch + 1) + '_' + 'x' + '.h5'
        print "Processing file", h5_file_base
        for writer in range(writers):
            h5_file_name = h5_file_base[:-4] + str(writer) + h5_file_base[-3:]
            
            fid = h5py.h5f.open(h5_file_name)
        
            dset = h5py.h5d.open(fid, "data")
            shape = dset.shape
            rdata = numpy.zeros(shape[0], dtype=numpy.float64)
            dset.read(h5py.h5s.ALL, h5py.h5s.ALL, rdata)
            
            species_array += list(rdata.ravel())[:]
        
        
        reordered_array = vtk.vtkDoubleArray()
        reordered_array.SetName(output)
        reordered_array.SetNumberOfValues(numCells[cellType][0] * numCells[cellType][1] * circQuads * axialQuads)
        reorder_species(species_array, reordered_array, cellType)
        mesh.GetCellData().AddArray(reordered_array)

        append_filter.AddInputData(mesh)
        
    append_filter.Update()

    # Write the result.
    vtu_file = base_names[output] + '.vtu'
    print 'Writing file', os.path.abspath(vtu_file)

    writer = vtk.vtkXMLUnstructuredGridWriter()
    writer.SetFileName(vtu_file)
    writer.SetInputData(append_filter.GetOutput())
    writer.Update()
Пример #3
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(
         self, module_manager,
         vtk.vtkAppendFilter(), 'Processing.',
         ('vtkDataSet',), ('vtkUnstructuredGrid',),
         replaceDoc=True,
         inputFunctions=None, outputFunctions=None)
Пример #4
0
def vtp2vtuPolyhedron(vtpObject):
    """
    Convert a Polydata to individual polyhedron cells in a vtu grid
    """
    # Find individual
    conFilt = vtk.vtkPolyDataConnectivityFilter()
    conFilt.SetInputData(vtpObject)
    conFilt.SetExtractionMode(5)
    conFilt.SetColorRegions(1)
    conFilt.Update()
    #
    phAppFilt = vtk.vtkAppendFilter()
    # phAppFilt.MergePointsOn()
    for nr in np.arange(conFilt.GetNumberOfExtractedRegions()):
        thresh = vtk.vtkThreshold()
        thresh.SetInputConnection(conFilt.GetOutputPort())
        thresh.ThresholdBetween(nr - .1, nr + .1)
        thresh.SetInputArrayToProcess(1, 0, 0, 0, "Regionid")
        thresh.Update()
        # Convert to a Polyhedron and add to the append filter
        phAppFilt.AddInputData(
            makePolyhedronCell(vtu2vtp(thresh.GetOutput()), returnGrid=True))
    phAppFilt.Update()
    # Return the grid
    return phAppFilt.GetOutput()
Пример #5
0
    def __init__(self, *args, **kwargs):
        """Initialize the unstructured grid."""
        super(UnstructuredGrid, self).__init__()
        deep = kwargs.pop('deep', False)

        if len(args) == 1:
            if isinstance(args[0], vtk.vtkUnstructuredGrid):
                if deep:
                    self.deep_copy(args[0])
                else:
                    self.shallow_copy(args[0])

            elif isinstance(args[0], str):
                self._load_file(args[0])

            elif isinstance(args[0], vtk.vtkStructuredGrid):
                vtkappend = vtk.vtkAppendFilter()
                vtkappend.AddInputData(args[0])
                vtkappend.Update()
                self.shallow_copy(vtkappend.GetOutput())

            else:
                itype = type(args[0])
                raise Exception('Cannot work with input type %s' % itype)

        elif len(args) == 4:
            arg0_is_arr = isinstance(args[0], np.ndarray)
            arg1_is_arr = isinstance(args[1], np.ndarray)
            arg2_is_arr = isinstance(args[2], np.ndarray)
            arg3_is_arr = isinstance(args[3], np.ndarray)

            if all([arg0_is_arr, arg1_is_arr, arg2_is_arr, arg3_is_arr]):
                self._from_arrays(args[0], args[1], args[2], args[3], deep)
            else:
                raise Exception('All input types must be np.ndarray')
Пример #6
0
    def __init__(self, comm, particle_vtu_file):
        self.comm = comm
        self.rank = comm.Get_rank()
        self.numberOfProcessors = self.comm.Get_size()
        '''
        ***************** PARTICLES INJECTION PREPARATION ********************
        '''
        self.domain_particles = vtk.vtkXMLUnstructuredGridReader()
        self.domain_particles.SetFileName(particle_vtu_file)
        self.domain_particles.Update()
        '''
        We push the domain_particles through an append_filter (as the only
        input) This will become useful later when we start reinjecting
        particles - the new particles will be added as inputs to the
        vtkAppendFilter.
        '''
        original_particle_mesh_data = self.domain_particles.GetOutput()
        self.append_filter = vtk.vtkAppendFilter()
        if vtk.VTK_MAJOR_VERSION <= 5:
            self.append_filter.AddInput(original_particle_mesh_data)
        else:
            self.append_filter.AddInputData(original_particle_mesh_data)
        self.append_filter.Update()

        self.alive_particles_coordinates = np.copy(
            numpy_support.vtk_to_numpy(
                self.append_filter.GetOutput().GetPoints().GetData()))
        # self.particles_vtk_pts = vtk.vtkPoints().SetData(
        # numpy_support.numpy_to_vtk(self.alive_particles_coordinates))
        self.nparticles = self.append_filter.GetOutput().GetNumberOfPoints()

        # initially particles are 'tidy'
        self.particles_indices = np.arange(self.nparticles, dtype=np.int64)
        self.particles_offsets = np.zeros((self.numberOfProcessors + 1, ),
                                          dtype=np.int64)
Пример #7
0
def create_planes(func: vtk.vtkSampleFunction,
                  number_of_planes: int) -> vtk.vtkActor:
    """
    Creates a number of planes that show a slice of the data at that slice.
    Adapted from
    https://lorensen.github.io/VTKExamples/site/Python/Visualization/QuadricVisualization/
    
    :param func: a vtkSampleFunction
    :param number_of_planes: the number of planes to add to the actor.
    :return: the actor to which the planes will be added.
    """
    actor = vtk.vtkActor()
    append = vtk.vtkAppendFilter()

    dimensions = func.GetSampleDimensions()
    slice_increment = (dimensions[2] - 1) // (number_of_planes + 1)
    slice_num = -4
    for i in range(0, number_of_planes):
        extract = vtk.vtkExtractVOI()
        extract.SetInputConnection(func.GetOutputPort())
        extract.SetVOI(0, dimensions[0] - 1, 0, dimensions[1] - 1,
                       slice_num + slice_increment,
                       slice_num + slice_increment)
        append.AddInputConnection(extract.GetOutputPort())
        slice_num += slice_increment
    append.Update()

    planes_mapper = vtk.vtkDataSetMapper()
    planes_mapper.SetInputConnection(append.GetOutputPort())
    planes_mapper.SetScalarRange(0, 7)

    actor.SetMapper(planes_mapper)
    actor.GetProperty().SetAmbient(1.)

    return actor
Пример #8
0
def split_chambers(_model, return_as_surface=False, return_elements=True):
    # _model.translate_to_center()

    surfaces = []
    for i in range(1, int(_model.scalar_range[1]) + 1):

        x = _model.threshold(i, i)
        surfaces.append(x)

    full_model_appended = vtk.vtkAppendFilter()
    _model.filename = os.path.join(_model.filename)
    for surf, elem in zip(surfaces, _model.list_of_elements):
        print(elem)
        if return_elements:
            _model.mesh = surf
            _model.extract_surface()
            _model.write_vtk(postscript='_' + elem)

        full_model_appended.AddInputConnection(surf.GetOutputPort())

    full_model_appended.Update()
    _model.mesh = full_model_appended
    if return_as_surface:
        # _model.translate_to_center()
        _model.extract_surface()
        _model.write_vtk(postscript='surf')
    else:
        _model.write_vtk(postscript='tetra')
    return _model
Пример #9
0
def CreatePlanes(func, actor, numberOfPlanes):
    #
    # Extract planes from implicit function.
    #

    append = vtk.vtkAppendFilter()

    dims = func.GetSampleDimensions()
    sliceIncr = (dims[2] - 1) // (numberOfPlanes + 1)
    sliceNum = -4
    for i in range(0, numberOfPlanes):
        extract = vtk.vtkExtractVOI()
        extract.SetInputConnection(func.GetOutputPort())
        extract.SetVOI(0, dims[0] - 1,
                       0, dims[1] - 1,
                       sliceNum + sliceIncr, sliceNum + sliceIncr)
        append.AddInputConnection(extract.GetOutputPort())
        sliceNum += sliceIncr
    append.Update()

    # Map planes
    planesMapper = vtk.vtkDataSetMapper()
    planesMapper.SetInputConnection(append.GetOutputPort())
    planesMapper.SetScalarRange(0, 7)

    actor.SetMapper(planesMapper)
    actor.GetProperty().SetAmbient(1.)
    return
Пример #10
0
    def _gen_full_rotor(self):
        """ Create full rotor vtk unstructured grid """
        grid = self.mas_grid.copy()
        # transform to standard coordinate system
        cs_cord = self.resultheader['csCord']
        if cs_cord > 1:
            matrix = self.cs_4x4(cs_cord, as_vtk_matrix=True)
            grid.transform(matrix)

        vtkappend = vtk.vtkAppendFilter()
        rang = 360.0 / self.n_sector
        for i in range(self.n_sector):
            # Transform mesh
            sector = grid.copy()
            sector.rotate_z(rang * i)
            vtkappend.AddInputData(sector)

        vtkappend.Update()
        full_rotor = pv.wrap(vtkappend.GetOutput())

        if cs_cord > 1:
            matrix.Invert()
            full_rotor.transform(matrix)

        return full_rotor
Пример #11
0
    def __init__(self, *args, **kwargs):
        super(UnstructuredGrid, self).__init__()

        if len(args) == 1:
            if isinstance(args[0], vtk.vtkUnstructuredGrid):
                self.ShallowCopy(args[0])

            elif isinstance(args[0], str):
                self.LoadFile(args[0])

            elif isinstance(args[0], vtk.vtkStructuredGrid):
                vtkappend = vtk.vtkAppendFilter()
                vtkappend.AddInputData(args[0])
                vtkappend.Update()
                self.ShallowCopy(vtkappend.GetOutput())

            else:
                itype = type(args[0])
                raise Exception('Cannot work with input type %s' % itype)

        elif len(args) == 4:
            arg0_is_arr = isinstance(args[0], np.ndarray)
            arg1_is_arr = isinstance(args[1], np.ndarray)
            arg2_is_arr = isinstance(args[2], np.ndarray)
            arg3_is_arr = isinstance(args[3], np.ndarray)

            if all([arg0_is_arr, arg1_is_arr, arg2_is_arr, arg3_is_arr]):
                if 'deep' in kwargs:
                    deep = kwargs['deep']
                else:
                    deep = True
                self.MakeFromArrays(args[0], args[1], args[2], args[3], deep)
            else:
                raise Exception('All input types must be np.ndarray')
Пример #12
0
 def set_block(self, idx=0):
     self.BLOCKid = idx
     Vtu = self.eg.GetOutput().GetBlock(self.BLOCKid)
     vtu = vtk.vtkAppendFilter()
     vtu.SetInput(Vtu)
     vtu.Update()
     self.vtu = vtu
Пример #13
0
    def _ManySlicesAlongPoints(self, pdipts, pdidata, pdo):
        """Internal helper to perfrom the filter
        """
        # Get the Points over the NumPy interface
        wpdi = dsa.WrapDataObject(pdipts) # NumPy wrapped points
        points = np.array(wpdi.Points) # New NumPy array of points so we dont destroy input
        numPoints = pdipts.GetNumberOfPoints()
        if self.__useNearestNbr:
            from scipy.spatial import cKDTree # NOTE: Must have SciPy in ParaView
            tree = cKDTree(points)
            ptsi = tree.query(points[0], k=numPoints)[1]
        else:
            ptsi = [i for i in range(numPoints)]

        # iterate of points in order (skips last point):
        app = vtk.vtkAppendFilter()
        for i in range(0, numPoints - 1, numPoints/self.GetNumberOfSlices()):
            # get normal
            pts1 = points[ptsi[i]]
            pts2 = points[ptsi[i+1]]
            x1, y1, z1 = pts1[0], pts1[1], pts1[2]
            x2, y2, z2 = pts2[0], pts2[1], pts2[2]
            normal = [x2-x1,y2-y1,z2-z1]

            # create slice
            plane = self._GeneratePlane([x1,y1,z1], normal)
            temp = vtk.vtkPolyData()
            self._Slice(pdidata, temp, plane)
            app.AddInputData(temp)
        app.Update()
        pdo.ShallowCopy(app.GetOutput())
        return pdo
Пример #14
0
    def __init__(self, slice3dVWRThingy, sliceGrid):
        self.slice3dVWR = slice3dVWRThingy
        self._grid = sliceGrid
        self._sliceDirectionsDict = {}

        # this same picker is used on all new IPWS of all sliceDirections
        self.ipwPicker = vtk.vtkCellPicker()

        self.currentCursor = None

        # configure the grid from scratch
        self._initialiseGrid()

        self._initUI()

        # bind all events
        self._bindEvents()

        # fill out our drop-down menu
        self._disableMenuItems = self._appendGridCommandsToMenu(
            self.slice3dVWR.controlFrame.slicesMenu,
            self.slice3dVWR.controlFrame, disable=True)

        self.overlayMode = 'greenOpacityRange'
        self.fusionAlpha = 0.4

        # this will make all ipw slice polydata available at the output
        self.ipwAppendPolyData = vtk.vtkAppendPolyData()

        # this append filter will make all slice data available at the output
        self.ipwAppendFilter = vtk.vtkAppendFilter()

        # create the first slice
        self._createSlice('Axial')
Пример #15
0
    def update(self):
        """

        """

        appendFilter = vtkAppendFilter()
        appendFilter.AddInput(self.input_)
        appendFilter.Update()

        extractGrid = vtkExtractUnstructuredGrid()
        extractGrid.SetInput(appendFilter.GetOutput())
        extractGrid.SetExtent(self.extent[0], self.extent[1], self.extent[2],
                              self.extent[3], self.extent[4], self.extent[5])

        geom = vtkGeometryFilter()
        geom.SetInputConnection(extractGrid.GetOutputPort())
        geom.Update()

        clean = vtkCleanPolyData()
        clean.PointMergingOn()
        clean.SetTolerance(0.01)
        clean.SetInput(geom.GetOutput())
        clean.Update()

        self.output_ = clean.GetOutput()
Пример #16
0
 def cast_to_unstructured_grid(self):
     """Get a new representation of this object as an
     :class:`pyvista.UnstructuredGrid`
     """
     alg = vtk.vtkAppendFilter()
     alg.AddInputData(self)
     alg.Update()
     return pyvista.filters._get_output(alg)
Пример #17
0
def main():
    colors = vtk.vtkNamedColors()

    sphereSource1 = vtk.vtkSphereSource()
    sphereSource1.Update()

    delaunay1 = vtk.vtkDelaunay3D()
    delaunay1.SetInputConnection(sphereSource1.GetOutputPort())
    delaunay1.Update()

    sphereSource2 = vtk.vtkSphereSource()
    sphereSource2.SetCenter(5, 0, 0)
    sphereSource2.Update()

    delaunay2 = vtk.vtkDelaunay3D()
    delaunay2.SetInputConnection(sphereSource2.GetOutputPort())
    delaunay2.Update()

    appendFilter = vtk.vtkAppendFilter()
    appendFilter.AddInputConnection(delaunay1.GetOutputPort())
    appendFilter.AddInputConnection(delaunay2.GetOutputPort())
    appendFilter.Update()

    connectivityFilter = vtk.vtkConnectivityFilter()
    connectivityFilter.SetInputConnection(appendFilter.GetOutputPort())
    connectivityFilter.SetExtractionModeToAllRegions()
    connectivityFilter.ColorRegionsOn()
    connectivityFilter.Update()

    # Visualize
    mapper = vtk.vtkDataSetMapper()
    mapper.SetInputConnection(connectivityFilter.GetOutputPort())
    mapper.Update()

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)

    renderer = vtk.vtkRenderer()
    renderer.AddActor(actor)

    # renWindow = vtk.vtkRenderWindow()
    # renWindow.AddRenderer(renderer)
    # iren = vtk.vtkRenderWindowInteractor()
    # iren.SetRenderWindow(renWindow)
    # iren.Initialize()
    # iren.Start()
    renWindow = vtk.vtkRenderWindow()
    renWindow.AddRenderer(renderer)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWindow)

    iren.Initialize()
    renWindow.Render()
    renWindow.SetWindowName('ConnectivityFilter')
    renderer.SetBackground(colors.GetColor3d('deep_ochre'))
    renderer.GetActiveCamera().Zoom(0.9)
    renWindow.Render()
    iren.Start()
Пример #18
0
    def __getAliveParticlesInSpatialBin(self, bin_name, local_particle_coordinates):
      probe = vtk.vtkProbeFilter()
      probe.SetValidPointMaskArrayName("lies_within_spatial_bin")

      # todo cache this if there are performance issues
      # (or evaluate alternative methods of working with the vtkProbeFilter)
      nlocalparticles = local_particle_coordinates.shape[0]
      local_particles_topology = np.zeros((nlocalparticles, 2),
                                          dtype=np.int64)
      local_particles_topology[:, 0] = 1
      local_particles_topology[:, 1] = np.arange(nlocalparticles,
                                                 dtype=np.int64)
      local_particles_topology = np.reshape(local_particles_topology,
                                            (nlocalparticles * 2, 1))

      local_particles = vtk.vtkPolyData()
      local_particles_pts = vtk.vtkPoints()
      local_particles_pts.SetData(numpy_support.numpy_to_vtk(local_particle_coordinates))
      local_particles_cells = vtk.vtkCellArray()
      local_particles_cells.SetCells(nlocalparticles,
                                     numpy_support.numpy_to_vtkIdTypeArray(local_particles_topology))
      local_particles.SetPoints(local_particles_pts)
      local_particles.SetVerts(local_particles_cells)

      if vtk.VTK_MAJOR_VERSION >= 6:
        probe.SetInputData(local_particles)
      else:
        probe.SetInput(local_particles)

      # Gather together the multiple spatial regions which comprise the spatial extent of
      # this bin.
      #
      # todo cache this if it is found to impact performance.
      append_filter = vtk.vtkAppendFilter()
      for spatialSubregionBinIndex in range(
        self.particleDataTimeBinsSpecifiers.getNumberOfSpatialRegionsComprisingBin(bin_name)
        ):

        if vtk.VTK_MAJOR_VERSION >= 6:
          append_filter.AddInputData(
          self.particleDataTimeBinsSpecifiers.getBinSpatialLimits(bin_name)[spatialSubregionBinIndex]
          )
        else:
          append_filter.AddInput(
          self.particleDataTimeBinsSpecifiers.getBinSpatialLimits(bin_name)[spatialSubregionBinIndex]
          )

      append_filter.Update()

      if vtk.VTK_MAJOR_VERSION >= 6:
        probe.SetSourceData(append_filter.GetOutput())
      else:
        probe.SetSource(append_filter.GetOutput())
      probe.Update()

      numpy_data = numpy_support.vtk_to_numpy(probe.GetValidPoints())
  
      return numpy_data
Пример #19
0
def run_pvbatch_output(params_dict):
  rank =  params_dict["rank"]
  size =  params_dict["size"]
  chunking =  params_dict["chunking"]
  grid_desc = params_dict["grid_desc"]
  time_steps_dict = params_dict["time_steps_dict"]
  paraview_output_file = params_dict["paraview_output_file"]
  catalystscript = params_dict["catalystscript"]

  if rank == 0:
    print "Processing grid chunk(s) on " + str(size) + " MPI ranks"

  c = len(chunking)/size
  r = len(chunking) % size
  if rank < r:
    start = rank * (c + 1)
    stop = start + c
  else:
    start = rank * c + r
    stop = start + (c - 1)

  append = vtk.vtkAppendFilter()
  append.MergePointsOn()
  for idx, chunk in enumerate(chunking[start:stop+1]):
    g = process_grid_chunk(idx, chunk, len(chunking), \
      grid_desc, time_steps_dict, paraview_output_file)
    if g:
      append.AddInputData(g)
  ug = None
  if append.GetInputList().GetNumberOfItems():
    append.Update()
    ug = append.GetOutput()

  if ug is None:
    ug = vtk.vtkUnstructuredGrid()

  report_collective_grid_sizes(ug)

  if catalystscript is not None:
    if rank == 0:
      print "Calling Catalyst over " + str(len(time_steps_dict)) + " time step(s) ..."
    import coprocessor
    coprocessor.initialize()
    coprocessor.addscript(catalystscript)
    id_map = create_cell_global_id_to_local_id_map(ug)
    for idx, time in enumerate(sorted(time_steps_dict.keys())):
      pt = ParallelTimer()
      read_time_step_data(time_steps_dict[time], ug, id_map)
      coprocessor.coprocess(time, idx, ug, paraview_output_file + '.pvd')
      pt.report_collective_time("catalyst output time %s (wall clock time) for step "\
        + str(idx))
    coprocessor.finalize()
  else:
    if rank == 0:
      print "Writing grid files over " + str(len(time_steps_dict)) + " time step(s) ..."
    write_grid_chunk(ug, rank, size, grid_desc, time_steps_dict, \
      paraview_output_file)
Пример #20
0
    def __init__(self, *args, **kwargs):
        """Initialize the unstructured grid."""
        super().__init__()
        deep = kwargs.pop('deep', False)

        if not len(args):
            return
        if len(args) == 1:
            if isinstance(args[0], vtk.vtkUnstructuredGrid):
                if deep:
                    self.deep_copy(args[0])
                else:
                    self.shallow_copy(args[0])

            elif isinstance(args[0], (str, pathlib.Path)):
                self._load_file(args[0])

            elif isinstance(args[0], vtk.vtkStructuredGrid):
                vtkappend = vtk.vtkAppendFilter()
                vtkappend.AddInputData(args[0])
                vtkappend.Update()
                self.shallow_copy(vtkappend.GetOutput())

            else:
                itype = type(args[0])
                raise TypeError(f'Cannot work with input type {itype}')

        elif len(args) == 3 and VTK9:
            arg0_is_arr = isinstance(args[0], np.ndarray)
            arg1_is_arr = isinstance(args[1], np.ndarray)
            arg2_is_arr = isinstance(args[2], np.ndarray)

            if all([arg0_is_arr, arg1_is_arr, arg2_is_arr]):
                self._from_arrays(None, args[0], args[1], args[2], deep)
                self._check_for_consistency()
            else:
                raise TypeError('All input types must be np.ndarray')

        elif len(args) == 4:
            arg0_is_arr = isinstance(args[0], np.ndarray)
            arg1_is_arr = isinstance(args[1], np.ndarray)
            arg2_is_arr = isinstance(args[2], np.ndarray)
            arg3_is_arr = isinstance(args[3], np.ndarray)

            if all([arg0_is_arr, arg1_is_arr, arg2_is_arr, arg3_is_arr]):
                self._from_arrays(args[0], args[1], args[2], args[3], deep)
                self._check_for_consistency()
            else:
                raise TypeError('All input types must be np.ndarray')

        else:
            err_msg = 'Invalid parameters.  Initialization with arrays ' +\
                      'requires the following arrays:\n'
            if VTK9:
                raise TypeError(err_msg + '`cells`, `cell_type`, `points`')
            else:
                raise TypeError(err_msg + '`offset`, `cells`, `cell_type`, `points`')
Пример #21
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(self,
                                       module_manager,
                                       vtk.vtkAppendFilter(),
                                       'Processing.', ('vtkDataSet', ),
                                       ('vtkUnstructuredGrid', ),
                                       replaceDoc=True,
                                       inputFunctions=None,
                                       outputFunctions=None)
Пример #22
0
    def __init__(self, numLats, numLons, radius=1.0, coords='cartesian'):

        # this is to convert from structured to unstructured grid
        self.appendGrids = vtk.vtkAppendFilter()

        # create grid
        numLats1, numLons1 = numLats + 1, numLons + 1
        lats = numpy.linspace(-numpy.pi / 2., numpy.pi / 2., numLats1)
        lons = numpy.linspace(0., 2 * numpy.pi, numLons1)
        llons, llats = numpy.meshgrid(lons, lats)

        llats = llats.flat
        llons = llons.flat

        # vertices in Cartesian space
        self.xyz = numpy.zeros((numLats1 * numLons1, 3), numpy.float64)
        rrho = radius * numpy.cos(llats)
        self.xyz[:, 0] = rrho * numpy.cos(llons)
        self.xyz[:, 1] = rrho * numpy.sin(llons)
        self.xyz[:, 2] = radius * numpy.sin(llats)

        # coordinates
        self.pointArray = self.xyz
        if coords == 'spherical':
            self.pointArray[:, 0] = llons
            self.pointArray[:, 1] = llats
            self.pointArray[:, 2] = 0.0

        # compute the cell areas, enforce positiveness (not sure why all the areas are negative)
        self.areas = -igAreas.getCellAreas(self.xyz, n0=numLats1, n1=numLons1)
        self.vareas = vtk.vtkDoubleArray()
        self.vareas.SetName('cell_areas')
        self.vareas.SetNumberOfComponents(1)
        self.vareas.SetNumberOfTuples(numLats * numLons)
        self.vareas.SetVoidArray(self.areas, numLats * numLons, 1)

        # create the VTK unstructured grid
        self.vxyz = vtk.vtkDoubleArray()
        self.vxyz.SetNumberOfComponents(3)
        ntot = numLats1 * numLons1
        self.vxyz.SetNumberOfTuples(ntot)
        self.vxyz.SetVoidArray(self.pointArray, 3 * ntot, 1)

        self.pts = vtk.vtkPoints()
        self.pts.SetNumberOfPoints(ntot)
        self.pts.SetData(self.vxyz)

        self.sgrid = vtk.vtkStructuredGrid()
        self.sgrid.SetDimensions(numLons1, numLats1, 1)
        self.sgrid.SetPoints(self.pts)

        self.sgrid.GetCellData().SetScalars(self.vareas)

        self.appendGrids.AddInputData(self.sgrid)
        self.appendGrids.Update()
        self.grid = self.appendGrids.GetOutput()
Пример #23
0
def HDF5toVTKCells():

    input_meshes = []

    # Read input meshes.
    for in_file in input_mesh_files[output]:
        reader = vtk.vtkXMLPolyDataReader()
        reader.SetFileName(in_file)
        reader.Update()

        input_meshes += [reader.GetOutput()]
        
        # Only add parent mesh for a tube (non-bifurcation)
        if branches == 1:
            break   

    for time_step in range(args.start, args.end + 1):
        print("Time:", time_step)
        
        append_filter = vtk.vtkAppendFilter()
        
        for branch in range(branches):
            mesh = vtk.vtkPolyData()
            mesh.DeepCopy(input_meshes[branch])

            # The base input h5 filename given the branch and from which writer it came on said branch.
            h5_file_base = base_names[output] + str(time_step) + '_b_' + str(branch + 1) + '_' + 'x' + '.h5'
            print("Processing file", h5_file_base)
            
            # Group all datasets of a branch at a specific time point given
            # the number of writers the data was split into.
            species_array = append_datasets(writers, h5_file_base, "data")

            # Loop through all attirbutes and append them to a new array in the 
            # correct order given the quad to task ratio.            
            for attribute in attributes[output]:
                reordered_array = vtk.vtkDoubleArray()
                reordered_array.SetName(attribute)
                reordered_array.SetNumberOfValues(numCells[output][0] * numCells[output][1] * circQuads * axialQuads)
                
                reorder_species(species_array[attribute], reordered_array, output)
                mesh.GetCellData().AddArray(reordered_array)
               
            append_filter.AddInputData(mesh)
            
        append_filter.Update()

        # Write the result.
        vtu_file = base_names[output] + str(time_step) + '.vtu'
        print("Writing file", os.path.abspath(vtu_file))

        writer = vtk.vtkXMLUnstructuredGridWriter()
        writer.SetFileName(vtu_file)
        writer.SetInputData(append_filter.GetOutput())
        writer.Update()
Пример #24
0
    def __init__(self, radius=1.0):
        """
        Constructor
        @param radius earth's radius
        """

        self.sf = shapefile.Reader('ne_10m_coastline')

        self.pts = []
        self.lines = []
        self.ugrids = []

        self.appendFilter = vtk.vtkAppendFilter()

        for s in self.sf.shapes():

            numPoints = len(s.points)

            # skip some smaller features
            if numPoints < 100:
                # skip
                continue

            vpts = vtk.vtkPoints()
            line = vtk.vtkPolyLine()
            ug = vtk.vtkUnstructuredGrid()

            vpts.SetNumberOfPoints(numPoints)

            ptIds = line.GetPointIds()
            ptIds.SetNumberOfIds(numPoints)
            index = 0
            for p in s.points:
                lam, the = p[0] * np.pi / 180., p[1] * np.pi / 180.
                x = radius * np.cos(the) * np.cos(lam)
                y = radius * np.cos(the) * np.sin(lam)
                z = radius * np.sin(the)
                vpts.InsertPoint(index, x, y, z)
                ptIds.SetId(index, index)
                index += 1

            # one cell
            ug.InsertNextCell(line.GetCellType(), ptIds)
            ug.SetPoints(vpts)

            # append to list to prevent Python from delete referenced objects
            self.pts.append(vpts)
            self.lines.append(line)
            self.ugrids.append(ug)

            self.appendFilter.AddInputData(ug)

        self.appendFilter.Update()
        self.ugrid = self.appendFilter.GetOutput()
Пример #25
0
def main():
    # Create 5 points (vtkPolyData)
    pointSource = vtk.vtkPointSource()
    pointSource.SetNumberOfPoints(5)
    pointSource.Update()

    polydata = pointSource.GetOutput()

    print "points in polydata are", polydata.GetNumberOfPoints()

    # Create 2 points in a vtkUnstructuredGrid
    points = vtk.vtkPoints()
    points.InsertNextPoint(0, 0, 0)
    points.InsertNextPoint(0, 0, 1)

    ug = vtk.vtkUnstructuredGrid()
    ug.SetPoints(points)
    print "points in unstructured grid are", ug.GetNumberOfPoints()

    # Combine the two data sets
    appendFilter = vtk.vtkAppendFilter()
    appendFilter.AddInputData(polydata)
    appendFilter.AddInputData(ug)
    appendFilter.Update()

    combined = vtk.vtkUnstructuredGrid()

    combined = appendFilter.GetOutput()
    print "Combined points are", combined.GetNumberOfPoints()

    # Create a mapper and actor
    colors = vtk.vtkNamedColors()

    mapper = vtk.vtkDataSetMapper()
    mapper.SetInputConnection(appendFilter.GetOutputPort())

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetPointSize(5)

    # Create a renderer, render window, and interactor
    renderer = vtk.vtkRenderer()
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.AddRenderer(renderer)
    renderWindowInteractor = vtk.vtkRenderWindowInteractor()
    renderWindowInteractor.SetRenderWindow(renderWindow)

    # Add the actor to the scene
    renderer.AddActor(actor)
    renderer.SetBackground(colors.GetColor3d("SlateGray"))

    # Render and interact
    renderWindow.Render()
    renderWindowInteractor.Start()
Пример #26
0
    def __init__(self):
        """
        Constructor
        """
        self.appendFilter = vtk.vtkAppendFilter()

        self.vpts = vtk.vtkPoints()
        self.ugrid = vtk.vtkUnstructuredGrid()

        self.numPoints = 0
        self.lines = []
def to_vtk_files():
    writer = vtk.vtkXMLUnstructuredGridWriter()

    reader = vtk.vtkXMLUnstructuredGridReader()

    for i in range(77):
        reader.SetFileName('proteus_vtu/proteus_{}.vtu'.format(i))
        reader.Update()

        unstructured_grid = reader.GetOutput()

        contour_filter = vtk.vtkContourFilter()
        contour_filter.SetInputData(unstructured_grid)

        contour_filter.ComputeNormalsOff()
        contour_filter.ComputeGradientsOff()
        contour_filter.ComputeScalarsOff()
        contour_filter.GenerateTrianglesOn()

        # Disable binary tree search, it might not be useful as
        # we compute only one contour
        contour_filter.UseScalarTreeOff()

        contour_filter.SetInputArrayToProcess(0, 0, 0, vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS, 'phi')

        contour_filter.SetValue(0, 0.)

        contour_filter.Update()

        contour = contour_filter.GetOutput()

        def reverse_normals(grid):
            polydata_filter = vtk.vtkGeometryFilter()
            polydata_filter.SetInputData(grid)
            polydata_filter.Update()
            polydata = polydata_filter.GetOutput()

            reverse = vtk.vtkReverseSense()
            reverse.ReverseCellsOn()
            reverse.SetInputData(polydata)
            reverse.Update()
            return reverse.GetOutput()

        contour = reverse_normals(contour)

        ugrid_filter = vtk.vtkAppendFilter()
        ugrid_filter.SetInputData(contour)
        ugrid_filter.Update()
        unstructured_grid = ugrid_filter.GetOutput()

        writer.SetInputData(unstructured_grid)
        writer.SetFileName('proteus_vtu/proteus_contour_{}.vtu'.format(i))

        writer.Write()
Пример #28
0
def pdata2ugrid(pdata, verbose=0):

    mypy.my_print(verbose, "*** pdata2ugrid ***")

    filter_append = vtk.vtkAppendFilter()
    if vtk.vtkVersion.GetVTKMajorVersion() >= 6:
        filter_append.SetInputData(pdata)
    else:
        filter_append.SetInput(pdata)
    filter_append.Update()
    ugrid = filter_append.GetOutput()

    return ugrid
Пример #29
0
def pdata2ugrid(pdata, verbose=0):

    mypy.my_print(verbose, "*** pdata2ugrid ***")

    filter_append = vtk.vtkAppendFilter()
    if (vtk.vtkVersion.GetVTKMajorVersion() >= 6):
        filter_append.SetInputData(pdata)
    else:
        filter_append.SetInput(pdata)
    filter_append.Update()
    ugrid = filter_append.GetOutput()

    return ugrid
Пример #30
0
def merge_elements(elem1, elem2):
    """
    Appends elements and returns the single connected mesh. The points in the same position in 3D are merged into one.
    :param elem1: Single element. The order of the elements pays no role.
    :param elem2: Single element.
    :return: Merged element as filter.
    """
    merger = vtk.vtkAppendFilter()
    merger.MergePointsOn()
    merger.AddInputConnection(elem1.GetOutputPort())
    merger.AddInputConnection(elem2.GetOutputPort())
    merger.Update()
    return merger
Пример #31
0
    def AddCyclicProperties(self):
        """ Adds cyclic properties to result object """
        # ansys's duplicate sector contains nodes from the second half of the node
        # numbering
        #
        # ansys node numbering for the duplicate sector is
        # nnum.min() + nnum.max()
        # where nnum is the node numbering for the master sector

#        if not vtkloaded:
#            raise Exception('Unable to add ')

        # master sector max node number
        num_master_max = self.nnum[int(self.nnum.size / 2) - 1]

        # identify master and duplicate cyclic sectors
        cells = np.arange(self.enum.size)
        dup_cells = np.where(
            np.any(
                self.geometry['elem'] > num_master_max,
                1))[0]
        mas_cells = np.setdiff1d(cells, dup_cells)
        self.sector = self.grid.ExtractSelectionCells(mas_cells)
        dup_sector = self.grid.ExtractSelectionCells(dup_cells)

        # Store the indices of the master and duplicate nodes
        self.mas_ind = self.sector.GetPointScalars('vtkOriginalPointIds')
        self.dup_ind = dup_sector.GetPointScalars('vtkOriginalPointIds')

        # store cyclic node numbers
        self.cyc_nnum = self.nnum[self.mas_ind]

        # create full rotor
        nSector = self.resultheader['nSector']

        # Copy and translate mesh
        vtkappend = vtk.vtkAppendFilter()
        rang = 360.0 / nSector
        for i in range(nSector):

            # Transform mesh
            sector = self.sector.Copy()
            sector.RotateZ(rang * i)

            vtkappend.AddInputData(sector)

        # Combine meshes and add VTK_Utilities functions
        # vtkappend.MergePointsOn()
        vtkappend.Update()
        self.rotor = vtkInterface.UnstructuredGrid(vtkappend.GetOutput())
Пример #32
0
def filterPDataIntoUGrid(
        pdata,
        verbose=0):

    myVTK.myPrint(verbose, "*** filterPDataIntoUGrid ***")

    filter_append = vtk.vtkAppendFilter()
    if (vtk.vtkVersion.GetVTKMajorVersion() >= 6):
        filter_append.SetInputData(pdata)
    else:
        filter_append.SetInput(pdata)
    filter_append.Update()

    return filter_append.GetOutput()
Пример #33
0
def createDEM_v1():

    ds = xr.open_dataset('../data/output/Peru_20160601-20180530_comp4.nc')

    points = vtk.vtkPoints()

    numPoints = ds.south_north.size * ds.west_east.size

    print('Write points \n')
    for i, j in product(ds.south_north.values, ds.west_east.values):
        points.InsertNextPoint(
            ds.lat.isel(south_north=i, west_east=j),
            ds.lon.isel(south_north=i, west_east=j),
            ds.HGT.isel(south_north=i, west_east=j).values / 6370000.0)

    print('Create unstructured grid \n')
    polydata = vtk.vtkPolyData()
    polydata.SetPoints(points)

    delaunay = vtk.vtkDelaunay2D()
    delaunay.SetInputData(polydata)
    delaunay.Update()

    #    subdivision = vtk.vtkButterflySubdivisionFilter()
    #    subdivision.SetInputConnection(delaunay.GetOutputPort())
    #    subdivision.Update()

    #smoother = vtk.vtkWindowedSincPolyDataFilter()
    #smoother.SetInputConnection(delaunay.GetOutputPort())
    #smoother.SetNumberOfIterations(5)
    #smoother.BoundarySmoothingOff()
    #smoother.FeatureEdgeSmoothingOff()
    #smoother.SetFeatureAngle(120.0)
    #smoother.SetPassBand(.001)
    #smoother.NonManifoldSmoothingOff()
    #smoother.NormalizeCoordinatesOff()
    #smoother.Update()

    appendFilter = vtk.vtkAppendFilter()
    appendFilter.AddInputData(delaunay.GetOutput())
    appendFilter.Update()

    unstructuredGrid = vtk.vtkUnstructuredGrid()
    unstructuredGrid.ShallowCopy(appendFilter.GetOutput())

    writer = vtk.vtkXMLUnstructuredGridWriter()
    writer.SetFileName('cosipy.vtu')
    writer.SetInputData(unstructuredGrid)
    writer.Write()
Пример #34
0
    def __init__(self, numLons, numLats, numElvs, radius=1.0, maxRelElv=0.1):

        # this is tp convert from structured to unstructured grid
        self.appendGrids = vtk.vtkAppendFilter()

        # create grid
        numLons1, numLats1, numElvs1 = numLons + 1, numLats + 1, numElvs + 1
        lats = numpy.linspace(-numpy.pi / 2., numpy.pi / 2., numLats1)
        lons = numpy.linspace(0., 2 * numpy.pi, numLons1)
        elvs = numpy.linspace(0., maxRelElv, numElvs1)
        llons, llats, eelvs = numpy.meshgrid(lons,
                                             lats,
                                             elvs,
                                             sparse=False,
                                             indexing='ij')

        llats = llats.flat
        llons = llons.flat
        eelvs = eelvs.flat

        # coordinates
        ntot = numLons1 * numLats1 * numElvs1
        self.xyz = numpy.zeros((ntot, 3), numpy.float64)
        rr = eelvs.copy()
        rr += 1.0
        rr *= radius
        rrho = rr * numpy.cos(llats)
        self.xyz[:, 0] = rrho * numpy.cos(llons)
        self.xyz[:, 1] = rrho * numpy.sin(llons)
        self.xyz[:, 2] = rr * numpy.sin(llats)

        # create the VTK unstructured grid
        self.vxyz = vtk.vtkDoubleArray()
        self.vxyz.SetNumberOfComponents(3)
        self.vxyz.SetNumberOfTuples(ntot)
        self.vxyz.SetVoidArray(self.xyz, 3 * ntot, 1)

        self.pts = vtk.vtkPoints()
        self.pts.SetNumberOfPoints(ntot)
        self.pts.SetData(self.vxyz)

        self.sgrid = vtk.vtkStructuredGrid()
        # inverse order that's how VTK expects it!
        self.sgrid.SetDimensions(numElvs1, numLats1, numLons1)
        self.sgrid.SetPoints(self.pts)

        self.appendGrids.AddInputData(self.sgrid)
        self.appendGrids.Update()
        self.grid = self.appendGrids.GetOutput()
Пример #35
0
def mergeFiles(fileList):
    """Use vtkAppendPolyData filter to join data as read from the fileList.

    :param fileList: list of files to process.
"""
    appender = vtk.vtkAppendFilter()

    for file in fileList:
        reader = vtk.vtkXMLPolyDataReader()
        reader.SetFileName(file)
        reader.Update()

        appender.AddInputData(reader.GetOutput())

    appender.Update()
   
    return appender.GetOutput()
    def GetOpenningLine(self):
        m_polyline = vtk.vtkPolyData()
        m_appendfilter = vtk.vtkAppendFilter()
        for i in xrange(len(self._openingList) - 1):
            l_linesource = vtk.vtkLineSource()
            l_linesource.SetPoint1(self._openingList[i])
            l_linesource.SetPoint2(self._openingList[i + 1])
            l_linesource.Update()
            m_appendfilter.AddInputData(m_polyline)
            m_appendfilter.AddInputData(l_linesource.GetOutput())
            m_appendfilter.Update()
            m_polyline.DeepCopy(m_appendfilter.GetOutput())

        m_geomfilter = vtk.vtkGeometryFilter()
        m_geomfilter.SetInputConnection(m_appendfilter.GetOutputPort())
        m_cleanfilter = vtk.vtkCleanPolyData()
        m_cleanfilter.SetInputConnection(m_geomfilter.GetOutputPort())
        m_cleanfilter.Update()
        m_polylineOut = m_cleanfilter.GetOutput()
        return m_polylineOut
Пример #37
0
    def readEnsightFile(self, fileName):
        """
        Read Ensight file. Writes a VTK file with fileName+'.vtk'.
        :param str filename: Input filename
        """
        #read the ensight file
        reader = vtk.vtkGenericEnSightReader()
        reader.SetCaseFileName(fileName)
        reader.Update()

        output = reader.GetOutput()
        num_blocks =  output.GetNumberOfBlocks()  

        #blocks_unstructured is a list of objects of vtkUnstructuredGrid
        blocks_unstructured = []
        for i in range(num_blocks):
            blocks_unstructured.append(output.GetBlock(i))

        appendFilter = vtk.vtkAppendFilter()
        i = 0
        while i < len(blocks_unstructured):
            if(vtk.VTK_MAJOR_VERSION <= 5):
                appendFilter.AddInput(blocks_unstructured[i])
            else:
                appendFilter.AddInputData(blocks_unstructured[i])
            i=i+1
        appendFilter.Update();

        unstructuredGrid=vtk.vtkUnstructuredGrid()
        unstructuredGrid.ShallowCopy(appendFilter.GetOutput());
        w = vtk.vtkUnstructuredGridWriter()
        if(vtk.VTK_MAJOR_VERSION <= 5):
            w.SetInput(unstructuredGrid)
        else:
            w.SetInputData(unstructuredGrid)
        w.SetFileName(fileName+'.vtk')
        w.Write()
        self.readVtkFile(fileName+'.vtk')
Пример #38
0
    def update(self):
        """

        """

        appendFilter = vtkAppendFilter()
        appendFilter.AddInput(self.input_)
        appendFilter.Update()

        extractGrid = vtkExtractUnstructuredGrid()
        extractGrid.SetInput(appendFilter.GetOutput())
        extractGrid.SetExtent(self.extent[0], self.extent[1], self.extent[2],  self.extent[3],  self.extent[4], self.extent[5])

        geom = vtkGeometryFilter()
        geom.SetInputConnection(extractGrid.GetOutputPort() )
        geom.Update()

        clean = vtkCleanPolyData()
        clean.PointMergingOn()
        clean.SetTolerance(0.01)
        clean.SetInput(geom.GetOutput())
        clean.Update()

        self.output_ = clean.GetOutput()
Пример #39
0
def ProjectImagingMesh(work_dir,data_set):
  import vtk
  import vtk.util.numpy_support as vtkNumPy 
  import numpy
  import scipy.io as scipyio
  # echo vtk version info
  print "using vtk version", vtk.vtkVersion.GetVTKVersion()
  # FIXME  notice that order of operations is IMPORTANT
  # FIXME   translation followed by rotation will give different results
  # FIXME   than rotation followed by translation
  # FIXME  Translate -> RotateZ -> RotateY -> RotateX -> Scale seems to be the order of paraview
  vtkReader = vtk.vtkDataSetReader() 
  # offset averaging +/- in both directions about center
  listoffset = [-2,-1,0,1,2]
  if   (data_set == "dog1"):
    # should be in meters
    #AffineTransform.Translate(0.206,0.289,-0.0215)
    #AffineTransform.RotateZ( 0.0 )
    #AffineTransform.RotateY( 0.0 )
    #AffineTransform.RotateX( 90.0 )
    Translate = (0.293,0.0634,0.12345)
    RotateZ   =  -90.0 
    RotateY   =  0.0 
    RotateX   =  90.0 
    Scale     = [1.,1.,1.]
    ImageFileTemplate  = '/FUS4/data2/BioTex/Brain_PhaseII/060626_BrainDog1_Treat/ProcessedTMAPData/BioTexCanines/dog1dtmap.0000.vtk'
  elif (data_set == "dog2"):
    # should be in meters
    Translate = (0.2335,0.235,-0.0335)
    RotateZ   =  6.0  
    RotateY   =  0.0  
    RotateX   =  90.0 
    Scale     = [1.,1.,1.]
    ImageFileTemplate  = '/data/sjfahrenholtz/mdacc/Dog/dog2_98000/mrivis/temperature.0000.vtk' 
    ImageFileTemplate  = '/FUS4/data2/BioTex/Brain_PhaseII/060626_BrainDog1_Treat/ProcessedTMAPData/BioTexCanines/dog2dtmap.0000.vtk'
  elif (data_set == "dog3"):
    # should be in meters
    Translate  = (0.209,0.2625,-0.0247)
    RotateZ    =  -8.0 
    RotateY    =  0.0 
    RotateX    =  90.0 
    Scale      =  [1.,1.,1.]
    ImageFileTemplate  = '/data/sjfahrenholtz/mdacc/Dog/dog3_98000/mrivis/temperature.0000.vtk' 
    ImageFileTemplate  = '/FUS4/data2/BioTex/Brain_PhaseII/060626_BrainDog1_Treat/ProcessedTMAPData/BioTexCanines/dog3dtmap.0000.vtk'
  elif (data_set == "dog4"):
    # should be in meters
    Translate = (0.195,0.245,-0.0715)
    RotateZ   =  -15.0 
    RotateY   =  0.0 
    RotateX   =  90.0 
    Scale     = [1.,1.,1.]
    ImageFileTemplate  = '/FUS4/data2/BioTex/Brain_PhaseII/060626_BrainDog1_Treat/ProcessedTMAPData/BioTexCanines/dog4dtmap.0000.vtk'
  elif (data_set == "human0"):
    # should be in meters
    vtkReader = vtk.vtkXMLImageDataReader() 
    Translate = (0.051,0.080,0.0509)
    RotateZ   =  29.0 
    RotateY   =  86.0 
    RotateX   =  0.0 
    Scale     = [1.,1.,1.]
    ImageFileTemplate  = '/data/fuentes/biotex/090318_751642_treat/Processed/imaging/temperature.0000.vti' 
  elif (data_set == "agar0"):
    # should be in meters
    Translate = (0.0,0.13,-0.095)
    RotateZ   =  0.0 
    RotateY   =  180.0 
    RotateX   =  0.0 
    Scale     = [1.,1.,1.]
    ImageFileTemplate  = '/data/jyung/MotionCorrection/motion_phantom_sept11/tmap.0000.vtk' 
  else:
    raise RuntimeError("\n\n unknown case... ")
  
  # read imaging data geometry that will be used to project FEM data onto
  vtkReader.SetFileName( ImageFileTemplate ) 
  vtkReader.Update()
  templateImage = vtkReader.GetOutput()
  dimensions = templateImage.GetDimensions()
  spacing = templateImage.GetSpacing()
  origin  = templateImage.GetOrigin()
  print spacing, origin, dimensions
  #fem.SetImagingDimensions( dimensions ,origin,spacing) 

  #setup to interpolate at 5 points across axial dimension 
  TransformList = []
  naverage = len(listoffset)
  subdistance = spacing[2] / (naverage-1)
  print "subspacing distance = ", subdistance
  for idtransform in listoffset: 
    AffineTransform = vtk.vtkTransform()
    AffineTransform.Translate( Translate[0],Translate[1],
                               Translate[2] + subdistance*idtransform )
    AffineTransform.RotateZ( RotateZ )
    AffineTransform.RotateY( RotateY )
    AffineTransform.RotateX( RotateX )
    AffineTransform.Scale(   Scale   )
    TransformList.append( AffineTransform )
    #laserTip         =  AffineTransform.TransformPoint(  laserTip )
    #laserOrientation =  AffineTransform.TransformVector( laserOrientation )

  # Interpolate FEM onto imaging data structures
  vtkExodusIIReader = vtk.vtkExodusIIReader()
  #vtkExodusIIReader.SetFileName( "%s/fem_stats.e" % work_dir )
  #vtkExodusIIReader.SetPointResultArrayStatus("Mean0",1)
  #vtkExodusIIReader.SetPointResultArrayStatus("StdDev0",1)
  #Timesteps  = 120
  for ii in range(0,120):
	  vtkExodusIIReader.SetFileName( "%s/fem_stats.%04d.e" % (work_dir,ii) )
	  #vtkExodusIIReader.SetPointResultArrayStatus("Vard0Mean",1)
	  #vtkExodusIIReader.SetPointResultArrayStatus("Vard0Kurt",1)
	  vtkExodusIIReader.Update()	  
	  numberofresultarrays = vtkExodusIIReader.GetNumberOfPointResultArrays()
	  print numberofresultarrays
	  for resultarrayindex in range(numberofresultarrays):
		resultarrayname = vtkExodusIIReader.GetPointResultArrayName(resultarrayindex)
		vtkExodusIIReader.SetPointResultArrayStatus( "%s" % (resultarrayname),1)
		print resultarrayname
	  vtkExodusIIReader.Update()
	  ntime  = vtkExodusIIReader.GetNumberOfTimeSteps()
	  #for timeID in range(69,70):
	  for timeID in range(ntime):
	    vtkExodusIIReader.SetTimeStep(timeID) 
	    vtkExodusIIReader.Update()
	    
	    # reflect
	    vtkReflectX = vtk.vtkReflectionFilter()
	    vtkReflectX.SetPlaneToXMin()
	    vtkReflectX.SetInput( vtkExodusIIReader.GetOutput() )
	    vtkReflectX.Update()

	    # reflect
	    vtkReflectY = vtk.vtkReflectionFilter()
	    vtkReflectY.SetPlaneToYMax()
	    vtkReflectY.SetInput( vtkReflectX.GetOutput() )
	    vtkReflectY.Update()

	    # apply the average of the transform
	    mean_array = numpy.zeros(dimensions[0]*dimensions[1]*dimensions[2])
	    std_array  = numpy.zeros(dimensions[0]*dimensions[1]*dimensions[2])
	    for affineFEMTranform in TransformList:
	      # get homogenius 4x4 matrix  of the form
	      #               A | b
	      #    matrix =   -----
	      #               0 | 1
	      #   
	      matrix = affineFEMTranform.GetConcatenatedTransform(0).GetMatrix()
	      #print matrix 
	      RotationMatrix = [[matrix.GetElement(0,0),matrix.GetElement(0,1),matrix.GetElement(0,2)],
				[matrix.GetElement(1,0),matrix.GetElement(1,1),matrix.GetElement(1,2)],
				[matrix.GetElement(2,0),matrix.GetElement(2,1),matrix.GetElement(2,2)]]
	      Translation =     [matrix.GetElement(0,3),matrix.GetElement(1,3),matrix.GetElement(2,3)] 
	      #print RotationMatrix 
	      print Translation 
	      TransformedFEMMesh = None
	      if vtkReflectY.GetOutput().IsA("vtkMultiBlockDataSet"):
		AppendBlocks = vtk.vtkAppendFilter()
		iter = vtkReflectY.GetOutput().NewIterator()
		iter.UnRegister(None)
		iter.InitTraversal()
		# loop over blocks...
		while not iter.IsDoneWithTraversal():
		    curInput = iter.GetCurrentDataObject()
		    vtkTransformFEMMesh = vtk.vtkTransformFilter()
		    vtkTransformFEMMesh.SetTransform( affineFEMTranform )
		    vtkTransformFEMMesh.SetInput( curInput )
		    vtkTransformFEMMesh.Update()
		    AppendBlocks.AddInput( vtkTransformFEMMesh.GetOutput() ) 
		    AppendBlocks.Update( ) 
		    iter.GoToNextItem();
		TransformedFEMMesh = AppendBlocks.GetOutput() 
	      else: 
		vtkTransformFEMMesh = vtk.vtkTransformFilter()
		vtkTransformFEMMesh.SetTransform( affineFEMTranform )
		vtkTransformFEMMesh.SetInput( vtkReflectY.GetOutput() )
		vtkTransformFEMMesh.Update()
		TransformedFEMMesh = vtkTransformFEMMesh.GetOutput() 

	      # reuse ShiftScale Geometry
	      vtkResample = vtk.vtkCompositeDataProbeFilter()
	      vtkResample.SetInput( templateImage )
	      vtkResample.SetSource( TransformedFEMMesh ) 
	      vtkResample.Update()
	      fem_point_data= vtkResample.GetOutput().GetPointData() 
	      #meantmp =  vtkNumPy.vtk_to_numpy(fem_point_data.GetArray('Vard0Mean')) 
	      #print meantmp.max()
	      #mean_array = mean_array + vtkNumPy.vtk_to_numpy(fem_point_data.GetArray('Vard0Mean')) 
	      #std_array  = std_array  + vtkNumPy.vtk_to_numpy(fem_point_data.GetArray('Vard0Kurt')) 
	      #print fem_array 
	      #print type(fem_array )

	    # average
	    #mean_array = mean_array/naverage
	    #print mean_array.max()
	    #std_array  = std_array /naverage 

	    # write numpy to disk in matlab
	    #scipyio.savemat("%s/modelstats.navg%d.%04d.mat" % (work_dir,naverage,timeID), {'spacing':spacing, 'origin':origin,'Vard0Mean':mean_array,'Vard0Kurt':std_array })

	  
	    # write output
	    print "writing ", timeID, ii, work_dir
	    vtkStatsWriter = vtk.vtkDataSetWriter()
	    vtkStatsWriter.SetFileTypeToBinary()
	    vtkStatsWriter.SetFileName("%s/modelstats.navg%d.%04d.vtk" % ( work_dir,naverage,ii ))
	    vtkStatsWriter.SetInput(vtkResample.GetOutput())
	    vtkStatsWriter.Update()
def ProjectImagingMesh(ini_file):
  import vtk.util.numpy_support as vtkNumPy 
  import ConfigParser
  import scipy.io as scipyio
  # echo vtk version info
  print "using vtk version", vtk.vtkVersion.GetVTKVersion()
  # read config file
  config = ConfigParser.ConfigParser()
  config.add_section("imaging") 
  config.add_section("fem") 
  config.set("imaging","listoffset","[0]") 
  config.read(ini_file)
 
  # get work directory
  work_dir = config.get('fem','work_dir')

  # FIXME  notice that order of operations is IMPORTANT
  # FIXME   translation followed by rotation will give different results
  # FIXME   than rotation followed by translation
  # FIXME  Translate -> RotateZ -> RotateY -> RotateX -> Scale seems to be the order of paraview
  RotateX    = float(config.get('fem','rotatex'))
  RotateY    = float(config.get('fem','rotatey'))
  RotateZ    = float(config.get('fem','rotatez'))
  Translate  = eval(config.get('fem','translate'))
  Scale      = eval(config.get('fem','scale'))
  print "rotate", RotateX , RotateY , RotateZ ,"translate", Translate, "scale", Scale 
  
  # read imaging data geometry that will be used to project FEM data onto
  dimensions = eval(config.get('imaging','dimensions'))
  spacing    = eval(config.get('imaging','spacing'))
  origin     = eval(config.get('imaging','origin'))
  print spacing, origin, dimensions
  templateImage = CreateVTKImage(dimensions,spacing,origin)
  # write template image for position verification
  vtkTemplateWriter = vtk.vtkDataSetWriter()
  vtkTemplateWriter.SetFileName( "%s/imageTemplate.vtk" % work_dir )
  vtkTemplateWriter.SetInput( templateImage )
  vtkTemplateWriter.Update()

  #setup to interpolate at 5 points across axial dimension 
  TransformList = []
  listoffset = eval(config.get('imaging','listoffset'))
  naverage   = len(listoffset)
  try:
    subdistance = spacing[2] / (naverage-1)
  except ZeroDivisionError: 
    subdistance = 0.0 # default is not to offset
  print "listoffset",listoffset, "subspacing distance = ", subdistance
  for idtransform in listoffset: 
    AffineTransform = vtk.vtkTransform()
    AffineTransform.Translate( Translate[0],Translate[1],
                               Translate[2] + subdistance*idtransform )
    AffineTransform.RotateZ( RotateZ )
    AffineTransform.RotateY( RotateY )
    AffineTransform.RotateX( RotateX )
    AffineTransform.Scale(   Scale   )
    TransformList.append( AffineTransform )
    #laserTip         =  AffineTransform.TransformPoint(  laserTip )
    #laserOrientation =  AffineTransform.TransformVector( laserOrientation )

  # Interpolate FEM onto imaging data structures
  vtkExodusIIReader = vtk.vtkExodusIIReader()
  #vtkExodusIIReader.SetFileName( "%s/fem_stats.e" % work_dir )
  #vtkExodusIIReader.SetPointResultArrayStatus("Mean0",1)
  #vtkExodusIIReader.SetPointResultArrayStatus("StdDev0",1)
  #Timesteps  = 120
  meshFileList = eval(config.get('fem','mesh_files'))
  print meshFileList 
  for mesh_filename in meshFileList:
	  vtkExodusIIReader.SetFileName( "%s/%s" % (work_dir,mesh_filename) )
	  #vtkExodusIIReader.SetPointResultArrayStatus("Vard0Mean",1)
	  #vtkExodusIIReader.SetPointResultArrayStatus("Vard0Kurt",1)
	  vtkExodusIIReader.Update()	  
	  numberofresultarrays = vtkExodusIIReader.GetNumberOfPointResultArrays()
	  print numberofresultarrays
	  for resultarrayindex in range(numberofresultarrays):
		resultarrayname = vtkExodusIIReader.GetPointResultArrayName(resultarrayindex)
		vtkExodusIIReader.SetPointResultArrayStatus( "%s" % (resultarrayname),1)
		print resultarrayname
	  vtkExodusIIReader.Update()
	  ntime  = vtkExodusIIReader.GetNumberOfTimeSteps()
	  #print ntime
          #for timeID in range(69,70):
	  for timeID in range(ntime):
	    vtkExodusIIReader.SetTimeStep(timeID) 
	    vtkExodusIIReader.Update()
	    
	    # reflect
	    vtkReflectX = vtk.vtkReflectionFilter()
	    vtkReflectX.SetPlaneToXMin()
	    vtkReflectX.SetInput( vtkExodusIIReader.GetOutput() )
	    vtkReflectX.Update()

	    # reflect
	    vtkReflectY = vtk.vtkReflectionFilter()
	    vtkReflectY.SetPlaneToYMax()
	    vtkReflectY.SetInput( vtkReflectX.GetOutput() )
	    vtkReflectY.Update()

	    # apply the average of the transform
	    mean_array = numpy.zeros(dimensions[0]*dimensions[1]*dimensions[2])
	    std_array  = numpy.zeros(dimensions[0]*dimensions[1]*dimensions[2])
	    for affineFEMTranform in TransformList:
	      # get homogenius 4x4 matrix  of the form
	      #               A | b
	      #    matrix =   -----
	      #               0 | 1
	      #   
	      matrix = affineFEMTranform.GetConcatenatedTransform(0).GetMatrix()
	      #print matrix 
	      RotationMatrix = [[matrix.GetElement(0,0),matrix.GetElement(0,1),matrix.GetElement(0,2)],
				[matrix.GetElement(1,0),matrix.GetElement(1,1),matrix.GetElement(1,2)],
				[matrix.GetElement(2,0),matrix.GetElement(2,1),matrix.GetElement(2,2)]]
	      Translation =     [matrix.GetElement(0,3),matrix.GetElement(1,3),matrix.GetElement(2,3)] 
	      #print RotationMatrix 
	      print Translation 
	      TransformedFEMMesh = None
	      if vtkReflectY.GetOutput().IsA("vtkMultiBlockDataSet"):
		AppendBlocks = vtk.vtkAppendFilter()
		iter = vtkReflectY.GetOutput().NewIterator()
		iter.UnRegister(None)
		iter.InitTraversal()
		# loop over blocks...
		while not iter.IsDoneWithTraversal():
		    curInput = iter.GetCurrentDataObject()
		    vtkTransformFEMMesh = vtk.vtkTransformFilter()
		    vtkTransformFEMMesh.SetTransform( affineFEMTranform )
		    vtkTransformFEMMesh.SetInput( curInput )
		    vtkTransformFEMMesh.Update()
		    AppendBlocks.AddInput( vtkTransformFEMMesh.GetOutput() ) 
		    AppendBlocks.Update( ) 
		    iter.GoToNextItem();
		TransformedFEMMesh = AppendBlocks.GetOutput() 
	      else: 
		vtkTransformFEMMesh = vtk.vtkTransformFilter()
		vtkTransformFEMMesh.SetTransform( affineFEMTranform )
		vtkTransformFEMMesh.SetInput( vtkReflectY.GetOutput() )
		vtkTransformFEMMesh.Update()
		TransformedFEMMesh = vtkTransformFEMMesh.GetOutput() 

	      # reuse ShiftScale Geometry
	      vtkResample = vtk.vtkCompositeDataProbeFilter()
	      vtkResample.SetInput( templateImage )
	      vtkResample.SetSource( TransformedFEMMesh ) 
	      vtkResample.Update()
	      fem_point_data= vtkResample.GetOutput().GetPointData() 
	      #meantmp =  vtkNumPy.vtk_to_numpy(fem_point_data.GetArray('Vard0Mean')) 
	      #print meantmp.max()
	      #mean_array = mean_array + vtkNumPy.vtk_to_numpy(fem_point_data.GetArray('Vard0Mean')) 
	      #std_array  = std_array  + vtkNumPy.vtk_to_numpy(fem_point_data.GetArray('Vard0Kurt')) 
	      #print fem_array 
	      #print type(fem_array )

	    # average
	    #mean_array = mean_array/naverage
	    #print mean_array.max()
	    #std_array  = std_array /naverage 

	    # write numpy to disk in matlab
	    #scipyio.savemat("%s/modelstats.navg%d.%04d.mat" % (work_dir,naverage,timeID), {'spacing':spacing, 'origin':origin,'Vard0Mean':mean_array,'Vard0Kurt':std_array })

	  
	    # write output
	    print "writing ", timeID, mesh_filename, work_dir
	    vtkStatsWriter = vtk.vtkDataSetWriter()
	    vtkStatsWriter.SetFileTypeToBinary()
	    vtkStatsWriter.SetFileName("%s/modelstats.navg%d.%s.%04d.vtk"%(work_dir,naverage,mesh_filename,timeID))
	    vtkStatsWriter.SetInput(vtkResample.GetOutput())
	    vtkStatsWriter.Update()
def ProjectImagingMesh(fem_mesh_file): 
  import vtk
  import vtk.util.numpy_support as vtkNumPy
  import scipy.io as scipyio
  # echo vtk version info
  print "using vtk version", vtk.vtkVersion.GetVTKVersion()
  # FIXME notice that order of operations is IMPORTANT
  # FIXME translation followed by rotation will give different results
  # FIXME than rotation followed by translation
  # FIXME Translate -> RotateZ -> RotateY -> RotateX -> Scale seems to be the order of paraview
  AffineTransform = vtk.vtkTransform()
  # should be in meters
  AffineTransform.Translate(.0000001,.0000001,.0000001)
  AffineTransform.RotateZ( 0 )
  AffineTransform.RotateY( 0 )
  AffineTransform.RotateX( 0 )
  AffineTransform.Scale([1.,1.,1.])
  # get homogenius 4x4 matrix of the form
  # A | b
  # matrix = -----
  # 0 | 1
  #
  matrix = AffineTransform.GetConcatenatedTransform(0).GetMatrix()
  #print matrix
  RotationMatrix = [[matrix.GetElement(0,0),matrix.GetElement(0,1),matrix.GetElement(0,2)],
                    [matrix.GetElement(1,0),matrix.GetElement(1,1),matrix.GetElement(1,2)],
                    [matrix.GetElement(2,0),matrix.GetElement(2,1),matrix.GetElement(2,2)]]
  Translation = [matrix.GetElement(0,3),matrix.GetElement(1,3),matrix.GetElement(2,3)]
  #print RotationMatrix ,Translation
  

  #laserTip = AffineTransform.TransformPoint( laserTip )
  #laserOrientation = AffineTransform.TransformVector( laserOrientation )

  # read imaging data geometry that will be used to project FEM data onto
  #vtkReader = vtk.vtkXMLImageDataReader()
  vtkReader = vtk.vtkDataSetReader()
  #vtkReader.SetFileName('/data/cjmaclellan/mdacc/nano/spio/spioVTK/67_11/tmap_67_11.0000.vtk' )
  vtkReader.SetFileName('/data/cjmaclellan/mdacc/deltap_phantom_oct10/VTKtmaps/S695/S695.0000.vtk' )
  #vtkReader.SetFileName('/data/cjmaclellan/mdacc/nano/nrtmapsVTK/R695/R695.0000.vtk' ) 
  vtkReader.Update()
  templateImage = vtkReader.GetOutput()
  dimensions = templateImage.GetDimensions()
  spacing = templateImage.GetSpacing()
  origin = templateImage.GetOrigin()
  print spacing, origin, dimensions 
  #fem.SetImagingDimensions( dimensions ,origin,spacing)

  ## project imaging onto fem mesh
  #if (vtk != None):
  # vtkImageReader = vtk.vtkDataSetReader()
  # vtkImageReader.SetFileName('/data/fuentes/mdacc/uqModelStudy/dog1_980/temperature.%04d.vtk' % timeID )
  # vtkImageReader.Update()
  # image_cells = vtkImageReader.GetOutput().GetPointData()
  # data_array = vtkNumPy.vtk_to_numpy(image_cells.GetArray('scalars'))
  # v1 = PETSc.Vec().createWithArray(data_array, comm=PETSc.COMM_SELF)
  # fem.ProjectImagingToFEMMesh("MRTI", v1)
  # fem.StoreSystemTimeStep("MRTI",timeID )
  #
  # # extract voi for QOI
  # vtkVOIExtract = vtk.vtkExtractVOI()
  # vtkVOIExtract.SetInput( vtkImageReader.GetOutput() )
  # VOI = [10,100,100,150,0,0]
  # vtkVOIExtract.SetVOI( VOI )
  # vtkVOIExtract.Update()
  # mrti_point_data= vtkVOIExtract.GetOutput().GetPointData()
  # mrti_array = vtkNumPy.vtk_to_numpy(mrti_point_data.GetArray('scalars'))
  # #print mrti_array
  # #print type(mrti_array)

  # Interpolate FEM onto imaging data structures
  vtkExodusIIReader = vtk.vtkExodusIIReader()
  vtkExodusIIReader.SetFileName( fem_mesh_file )
  vtkExodusIIReader.SetPointResultArrayStatus("u0",1)
  vtkExodusIIReader.SetPointResultArrayStatus("u0*",1)
  vtkExodusIIReader.SetPointResultArrayStatus("u1",1)

  matsize = int(dimensions[1])#get matrix size
  #preallocate size of arrays
  u0_array_1 = scipy.zeros((matsize,matsize))
  u0_array_2 = scipy.zeros((matsize,matsize,ntime*nsubstep))
  u1_array_1 = scipy.zeros((matsize,matsize))
  u1_array_2 = scipy.zeros((matsize,matsize,ntime*nsubstep))
  u0star_array_1 = scipy.zeros((matsize,matsize))
  u0star_array_2 = scipy.zeros((matsize,matsize,ntime*nsubstep))

  #for timeID in range(1,2):
  for timeID in range(1,ntime*nsubstep):
    vtkExodusIIReader.SetTimeStep(timeID-1)
    vtkExodusIIReader.Update()
    
    # apply the transform
    TransformedFEMMesh = None
    if vtkExodusIIReader.GetOutput().IsA("vtkMultiBlockDataSet"):
      AppendBlocks = vtk.vtkAppendFilter()
      iter = vtkExodusIIReader.GetOutput().NewIterator()
      iter.UnRegister(None)
      iter.InitTraversal()
      # loop over blocks...
      while not iter.IsDoneWithTraversal():
          curInput = iter.GetCurrentDataObject()
          vtkTransformFEMMesh = vtk.vtkTransformFilter()
          vtkTransformFEMMesh.SetTransform( AffineTransform )
          vtkTransformFEMMesh.SetInput( curInput )
          vtkTransformFEMMesh.Update()
          AppendBlocks.AddInput( vtkTransformFEMMesh.GetOutput() )
          AppendBlocks.Update( )
          iter.GoToNextItem();
      TransformedFEMMesh = AppendBlocks.GetOutput()
    else:
      vtkTransformFEMMesh = vtk.vtkTransformFilter()
      vtkTransformFEMMesh.SetTransform( AffineTransform )
      vtkTransformFEMMesh.SetInput( vtkExodusIIReader.GetOutput() )
      vtkTransformFEMMesh.Update()
      TransformedFEMMesh = vtkTransformFEMMesh.GetOutput()

    # reflect
    #vtkReflectX = vtk.vtkReflectionFilter()
    #vtkReflectX.SetPlaneToXMin()
    #vtkReflectX.SetInput( TransformedFEMMesh )
    #vtkReflectX.Update()

    # reflect
    #vtkReflectZ = vtk.vtkReflectionFilter()
    #vtkReflectZ.SetPlaneToZMax()
    #vtkReflectZ.SetInput( vtkReflectX.GetOutput() )
    #vtkReflectZ.Update()

    # reuse ShiftScale Geometry
    vtkResample = vtk.vtkCompositeDataProbeFilter()
    vtkResample.SetInput( templateImage )
    vtkResample.SetSource( TransformedFEMMesh )
    #vtkResample.SetSource( vtkReflectZ.GetOutput() )
    vtkResample.Update()
    fem_point_data= vtkResample.GetOutput().GetPointData()
    u0_array = vtkNumPy.vtk_to_numpy(fem_point_data.GetArray('u0'))
    u0star_array = vtkNumPy.vtk_to_numpy(fem_point_data.GetArray('u0*'))
    u1_array = vtkNumPy.vtk_to_numpy(fem_point_data.GetArray('u1'))
 
    
    #go from 1x256^2 array to 256X256 array for each timestep
    for nn in range(0,matsize):
     u0_array_1[nn,:]=u0_array[nn*matsize:(nn+1)*matsize]
     u0star_array_1[nn,:]=u0star_array[nn*matsize:(nn+1)*matsize]
     u1_array_1[nn,:]=u1_array[nn*matsize:(nn+1)*matsize]
   
    #apply proper rotations/reflections and combine 2D arrays into 3D array 
    u0_array_2[:,:,timeID-1]=numpy.fliplr(numpy.rot90(u0_array_1,k=3))
    u0star_array_2[:,:,timeID-1]=numpy.fliplr(numpy.rot90(u0star_array_1,k=3))
    u1_array_2[:,:,timeID-1]=numpy.fliplr(numpy.rot90(u1_array_1,k=3))
    
    # write numpy to disk in matlab
    #scipyio.savemat("MS795.%04d.mat" % (timeID), {'u0':u1_array,'MRTI0':MRTI0_array })

    # write output
    print "writing ", timeID
    vtkStatsWriter = vtk.vtkDataSetWriter()
    vtkStatsWriter.SetFileTypeToBinary()
    vtkStatsWriter.SetFileName("test.%04d.vtk" % timeID )
    vtkStatsWriter.SetInput(vtkResample.GetOutput())
    vtkStatsWriter.Update()

  scipyio.savemat("S695.mat",{'ModelFluence':u1_array_2,'MRTI':u0star_array_2,'ModelTemp':u0_array_2})
Пример #42
0
def shape2polyhedron(shpFile,dbfHeader=None,thickness=1.0,elevation=0.0):
    """
    Function to convert GIS .shp and dbf to VTK vtu polyhedron.


    """

    import vtk, pysal, numpy as np, vtk.util.numpy_support as npsup

    # Read the input shp file
    shp = pysal.open(shpFile,'r')
    # Read the connected dbf file
    dbfFile = shpFile.split('.shp')[0] + '.dbf'
    dbf = pysal.open(dbfFile,'r')

    # Define the thickness and elevation of the holes
    if 'vtkobject' in str(type(elevation)):
        # Make the holes larger taller then the elevation
        eB = elevation.GetBounds()
        holeThink = eB[-1]-eB[-2] + 20.
        holeElev = eB[-1]+10.
    else:
        holeThink = thickness + 20
        holeElev = elevation + 10

    # Make a vtk object.
    # Initialize the data
    shpPHAppFilt = vtk.vtkAppendFilter()
    shpPHAppFilt.MergePointsOn()
    for nr, poly in enumerate(shp):
        mainPolygon = vtkTools.polydata.normFilter(makeVolumePolygon(np.array(poly.parts[0][:-1]),thickness,elevation,triangulate=True))
        # Deal with holes
        if poly.holes[0] == []:
            mainPHGrid = _makePolyhedronCell(mainPolygon,returnGrid=True)
        else:
            holesAppendFilt = vtk.vtkAppendPolyData()
            for hole in poly.holes:
                holePoly = vtkTools.polydata.normFilter(makeVolumePolygon(np.array(hole[:-1]),holeThink,holeElev,triangulate=True))
                holesAppendFilt.AddInputData(holePoly)
            # Make holes polygon
            holesAppendFilt.Update()
            holesPolygons = holesAppendFilt.GetOutput()
            # Cut the holes
            mainCutHolesPolygon = vtkTools.polydata.join2Polydata(mainPolygon,holesPolygons,threshold1='upper',threshold2='lower')
            # Add the cut polyhedron
            mainPHGrid = _makePolyhedronCell(mainCutHolesPolygon,returnGrid=True)
        shpPHAppFilt.AddInputData(mainPHGrid)
    shpPHAppFilt.Update()
    # Extract the vtu object.
    vtuPolyhedObj = shpPHAppFilt.GetOutput()
    # np.load(fileT)
    # Check if there is data to be associated with the cells.
    if dbfHeader:
        # Find all the headers given
        for head in dbfHeader:
            # Get the data
            nparr = np.array(dbf.by_col[head])
            # Sort the type of data
            if nparr.dtype.type is np.string_:
                vtkarr = vtk.vtkStringArray()
                for ele in ['NoDef' if l=='' else l for l in nparr ]: # Add 'NoDef' if the string is '' (empty)
                    vtkarr.InsertNextValue(ele)
            elif nparr.dtype.type is np.object:
                for nr, i in enumerate(nparr):
                    if i is None:
                        nparr[nr] = np.nan
                nparr = np.array(nparr,dtype=np.float)
                vtkarr = npsup.numpy_to_vtk(nparr,deep=1)
            else:
                nparr = np.array(nparr,dtype=np.float)
                vtkarr = npsup.numpy_to_vtk(nparr,deep=1)
            vtkarr.SetName(head)

            vtuPolyhedObj.GetCellData().AddArray(vtkarr)# Return the PH grid

    return vtuPolyhedObj
Пример #43
0
#
ren1 = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren1)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
# create a camera model
camCS = vtk.vtkConeSource()
camCS.SetHeight(1.5)
camCS.SetResolution(12)
camCS.SetRadius(0.4)
camCBS = vtk.vtkCubeSource()
camCBS.SetXLength(1.5)
camCBS.SetZLength(0.8)
camCBS.SetCenter(0.4,0,0)
camAPD = vtk.vtkAppendFilter()
camAPD.AddInputConnection(camCS.GetOutputPort())
camAPD.AddInputConnection(camCBS.GetOutputPort())
camMapper = vtk.vtkDataSetMapper()
camMapper.SetInputConnection(camAPD.GetOutputPort())
camActor = vtk.vtkLODActor()
camActor.SetMapper(camMapper)
camActor.SetScale(2,2,2)
# draw the arrows
pd = vtk.vtkPolyData()
ca = vtk.vtkCellArray()
fp = vtk.vtkPoints()
fp.InsertNextPoint(0,1,0)
fp.InsertNextPoint(8,1,0)
fp.InsertNextPoint(8,2,0)
fp.InsertNextPoint(10,0.01,0)
Пример #44
0
def saveVtk(dataset, filename):
    polydata = vtk.vtkPolyData()
    points = vtk.vtkPoints()
    lines = vtk.vtkCellArray()

    points.SetNumberOfPoints(len(dataset['points']))
    for i,p in enumerate(dataset['points']):
        #print p
        points.SetPoint(i,p[0],p[1],p[2])

    for stream in dataset['streams']:
        lines.InsertNextCell(len(stream))
        for i in stream:
            lines.InsertCellPoint(i)

    polydata.SetPoints(points)
    polydata.SetLines(lines)

    pointdata = polydata.GetPointData()
    for i in  dataset['values']:
        print i,len(dataset['values'][i])
    for sname, sarr in dataset['values'].iteritems():
        arr = vtk.vtkFloatArray()
        arr.SetName(sname)
        arr.SetNumberOfComponents(1)
        for v in sarr:
            arr.InsertNextTuple1(v)
        pointdata.AddArray(arr)
        pointdata.SetActiveScalars(sname)


    print len(dataset['streams']),'streamlines, ',len(dataset['points']),' points.'

    if 'vtp' in filename:
        vreader = vtk.vtkXMLPolyDataReader()
        vwriter = vtk.vtkXMLPolyDataWriter()
    else:
        vreader = vtk.vtkPolyDataReader()
        vwriter = vtk.vtkPolyDataWriter()

    if os.path.isfile(filename):
        print '{} exists, appending to it'.format(filename)
        vreader.SetFileName(filename)
        vreader.Update()
        old_polydata = vreader.GetOutput()
        old_polydata.ReleaseDataFlagOn()
        appendfilter = vtk.vtkAppendFilter()
        appendfilter.AddInput(old_polydata)
        appendfilter.AddInput(polydata)
        appendfilter.Update()

        gfilter = vtk.vtkGeometryFilter()
        gfilter.SetInput(appendfilter.GetOutput())
        polydata = gfilter.GetOutput()
        polydata.ReleaseDataFlagOn()


    vwriter.SetInput(polydata)
    vwriter.SetFileName(filename)
    vwriter.Write()
    print 'saved',filename
Пример #45
0
writer.Write()

# ------------------------------------------------------------
# Save polydata shape
# ------------------------------------------------------------

writer = vtk.vtkXMLPolyDataWriter()
writer.SetInputData(boySource.GetOutput())
writer.SetFileName("BoySurface"+".vtp")
writer.Write()

# ------------------------------------------------------------
# Save unstructured grid
# ------------------------------------------------------------

appendFilter=vtk.vtkAppendFilter()
appendFilter.AddInputData(boySource.GetOutput())
appendFilter.Update()

unstructuredGrid=vtk.vtkUnstructuredGrid()#appendFilter.GetOutput()#
unstructuredGrid.DeepCopy(appendFilter.GetOutput())

writer=vtk.vtkXMLUnstructuredGridWriter()
writer.SetFileName("BoySurface"+".vtu")
writer.SetInputData(unstructuredGrid)
#writer.SetDataModeToBinary()
#writer.SetDataModeToAppended()
writer.EncodeAppendedDataOn()
writer.Write()

#Generate binary vtu file in append mode