Esempio n. 1
0
def read(filenames, timestep=None):
    '''Reads an unstructured mesh with added data.

    :param filenames: The files to read from.
    :type filenames: str
    :param timestep: Time step to read from, in case of an Exodus input mesh.
    :type timestep: int, optional
    :returns mesh{2,3}d: The mesh data.
    :returns point_data: Point data read from file.
    :type point_data: dict
    :returns field_data: Field data read from file.
    :type field_data: dict
    '''
    if isinstance(filenames, (list, tuple)) and len(filenames)==1:
        filenames = filenames[0]

    if isinstance(filenames, basestring):
        filename = filenames
        # serial files
        extension = os.path.splitext(filename)[1]

        import re
        # setup the reader
        # TODO Most readers have CanReadFile() -- use that.
        if extension == '.vtu':
            from vtk import vtkXMLUnstructuredGridReader
            reader = vtkXMLUnstructuredGridReader()
            vtk_mesh = _read_vtk_mesh(reader, filename)
        elif extension == '.vtk':
            from vtk import vtkUnstructuredGridReader
            reader = vtkUnstructuredGridReader()
            vtk_mesh = _read_vtk_mesh(reader, filename)
        elif extension == '.xmf':
            from vtk import vtkXdmfReader
            reader = vtkXdmfReader()
            vtk_mesh = _read_vtk_mesh(reader, filename)
        elif extension in [ '.ex2', '.exo', '.e' ]:
            from vtk import vtkExodusIIReader
            reader = vtkExodusIIReader()
            reader.SetFileName( filename )
            vtk_mesh = _read_exodusii_mesh(reader, timestep=timestep)
        elif re.match('[^\.]*\.e\.\d+\.\d+', filename):
            # Parallel Exodus files.
            # TODO handle with vtkPExodusIIReader
            from vtk import vtkExodusIIReader
            reader = vtkExodusIIReader()
            reader.SetFileName( filenames[0] )
            vtk_mesh = _read_exodusii_mesh(reader, timestep=timestep)
        else:
            raise RuntimeError( 'Unknown file type \'%s\'.' % filename )
    else:
        # Parallel files.
        # Assume Exodus format as we don't know anything else yet.
        from vtk import vtkPExodusIIReader
        # TODO Guess the file pattern or whatever.
        reader = vtkPExodusIIReader()
        reader.SetFileNames( filenames )
        vtk_mesh = _read_exodusii_mesh(reader, filename, timestep=timestep)

    return vtk_mesh
Esempio n. 2
0
def read_exodus(filename,
                animate_mode_shapes=True,
                apply_displacements=True,
                displacement_magnitude=1.0,
                enabled_sidesets=None):
    """Read an ExodusII file (``'.e'`` or ``'.exo'``)."""
    reader = vtk.vtkExodusIIReader()
    reader.SetFileName(filename)
    reader.UpdateInformation()
    reader.SetAnimateModeShapes(animate_mode_shapes)
    reader.SetApplyDisplacements(apply_displacements)
    reader.SetDisplacementMagnitude(displacement_magnitude)

    if enabled_sidesets is None:
        enabled_sidesets = list(range(reader.GetNumberOfSideSetArrays()))

    for sideset in enabled_sidesets:
        if isinstance(sideset, int):
            name = reader.GetSideSetArrayName(sideset)
        elif isinstance(sideset, str):
            name = sideset
        else:
            raise ValueError(
                'Could not parse sideset ID/name: {}'.format(sideset))

        reader.SetSideSetArrayStatus(name, 1)

    reader.Update()
    return pyvista.wrap(reader.GetOutput())
def GetMeshNodes(file_name):
  """
  return the number of DOF for a exodus file
  """
  import vtk
  vtkExodusIIReader = vtk.vtkExodusIIReader()
  vtkExodusIIReader.SetFileName(file_name)
  #vtkExodusIIReader.SetPointResultArrayStatus("u0",1)
  vtkExodusIIReader.Update()
  # multi block
  if vtkExodusIIReader.GetOutput().IsA("vtkMultiBlockDataSet"):
    iter = vtkExodusIIReader.GetOutput().NewIterator()
    iter.UnRegister(None)
    iter.InitTraversal()
    # initialize list for storage
    NumberOfNodes = 0
    # loop over blocks...
    while not iter.IsDoneWithTraversal():
      curInput = iter.GetCurrentDataObject()
      NumberOfNodes = NumberOfNodes + curInput.GetNumberOfPoints()
      iter.GoToNextItem();
    # return total number of nodes
    return NumberOfNodes 
  # single block
  else:
    return vtkExodusIIReader.GetNumberOfNodes()
Esempio n. 4
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(
         self, module_manager,
         vtk.vtkExodusIIReader(), 'Reading vtkExodusII.',
         (), ('vtkExodusII',),
         replaceDoc=True,
         inputFunctions=None, outputFunctions=None)
Esempio n. 5
0
  def __init__(self, mesh_item_data, file_name):
    MeshInfo.__init__(self, mesh_item_data)
    self.file_name = file_name
    import vtk
    reader = vtk.vtkExodusIIReader()
    reader.SetFileName(self.file_name)
    reader.UpdateInformation()
    num_nodesets = reader.GetNumberOfNodeSetArrays()
    num_sidesets = reader.GetNumberOfSideSetArrays()
    num_blocks = reader.GetNumberOfElementBlockArrays()

    self.nodesets = set()
    for i in xrange(num_nodesets):
      self.nodesets.add(reader.GetObjectId(vtk.vtkExodusIIReader.NODE_SET,i))
      if 'Unnamed' not in reader.GetObjectName(vtk.vtkExodusIIReader.NODE_SET,i).split(' '):
        self.nodesets.add(reader.GetObjectName(vtk.vtkExodusIIReader.NODE_SET,i).split(' ')[0])

    self.sidesets = set()
    for i in xrange(num_sidesets):
      self.sidesets.add(reader.GetObjectId(vtk.vtkExodusIIReader.SIDE_SET,i))
      if 'Unnamed' not in reader.GetObjectName(vtk.vtkExodusIIReader.SIDE_SET,i).split(' '):
        self.sidesets.add(reader.GetObjectName(vtk.vtkExodusIIReader.SIDE_SET,i).split(' ')[0])

    self.blocks = set()
    for i in xrange(num_blocks):
      self.blocks.add(reader.GetObjectId(vtk.vtkExodusIIReader.ELEM_BLOCK,i))
      if 'Unnamed' not in reader.GetObjectName(vtk.vtkExodusIIReader.ELEM_BLOCK,i).split(' '):
        self.blocks.add(reader.GetObjectName(vtk.vtkExodusIIReader.ELEM_BLOCK,i).split(' ')[0])
Esempio n. 6
0
def read(filetype, filename):
    if filetype == 'vtk':
        reader = vtk.vtkUnstructuredGridReader()
        reader.SetFileName(filename)
        reader.Update()
        vtk_mesh = reader.GetOutput()
    elif filetype == 'vtu':
        reader = vtk.vtkXMLUnstructuredGridReader()
        reader.SetFileName(filename)
        reader.Update()
        vtk_mesh = reader.GetOutput()
    elif filetype == 'exodus':
        reader = vtk.vtkExodusIIReader()
        reader.SetFileName(filename)
        vtk_mesh = _read_exodusii_mesh(reader)
    else:
        raise RuntimeError('Unknown file type \'%s\'.' % filename)

    # Explicitly extract points, cells, point data, field data
    points = vtk.util.numpy_support.vtk_to_numpy(
        vtk_mesh.GetPoints().GetData())
    cells = _read_cells(vtk_mesh)
    point_data = _read_data(vtk_mesh.GetPointData())
    cell_data = _read_data(vtk_mesh.GetCellData())
    field_data = _read_data(vtk_mesh.GetFieldData())

    return points, cells, point_data, cell_data, field_data
Esempio n. 7
0
 def __init__(self, exodusFileName, structuredGrid):
     '''
     Initialize with path to exodus file and the structured grid you wish
     to resample over
     '''
     self.eReader = vtk.vtkExodusIIReader()
     self.eReader.SetFileName(exodusFileName)
     self.grid = structuredGrid
Esempio n. 8
0
def average_fields(names, var):
    """ given list of filenames and var, generate average field """

    # open each file, and add the field data 
    # to our averaged array
    for name in names:
        d = vtk.vtkExodusIIReader() 
        d.SetFileName(name) 
        d.UpdateInformation() 
        
        d.SetPointResultArrayStatus(var,1) 
        d.Update() 
        
        blocks = d.GetOutput().GetNumberOfBlocks()
        data   = d.GetOutput()
        

        #
        # range to integrate over
        #
        height = 0.842820346355
        thresh = 0.004

        # open text file
        f = open('slices/'+var+'/'+name+'.txt', 'w')
        
        for j in xrange(blocks):
            blk = data.GetBlock(0).GetBlock(j)
            try:
                pts = blk.GetNumberOfPoints()
            except:
                ss='no data in this block'
            else:
                pt_data = blk.GetPointData().GetArray(var)
                if pt_data is None:
                    print 'Nada!'
                    print 'I cannot find the variable field: ', var
                    print 'Exiting...'
                    sys.exit(1)
                    
                for i in xrange(pts):
                    # gather x,y,z location
                    #z,y,x = blk.GetPoint(i)
                    x,y,z = blk.GetPoint(i)
                    
                    if(abs(z-height)<thresh):
                        # gather point scalar value
                        u = pt_data.GetValue(i)                     
                        f.write(str(x)+' , '+str(y)+' , '+str(u)+'\n')
                        
        # close file
        f.close()

    #
    # steady as she goes
    #
    return 0
Esempio n. 9
0
def main():
    colors = vtk.vtkNamedColors()

    # Input file and variable
    filename, nodal_var = get_program_parameters()

    # Read Exodus Data
    reader = vtk.vtkExodusIIReader()
    reader.SetFileName(filename)
    reader.UpdateInformation()
    reader.SetTimeStep(10)
    reader.SetAllArrayStatus(vtk.vtkExodusIIReader.NODAL,
                             1)  # enables all NODAL variables
    reader.Update()
    # print(reader)  # uncomment this to show the file information

    # Create Geometry
    geometry = vtk.vtkCompositeDataGeometryFilter()
    geometry.SetInputConnection(0, reader.GetOutputPort(0))
    geometry.Update()

    # Mapper
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(geometry.GetOutputPort())
    mapper.SelectColorArray(nodal_var)
    mapper.SetScalarModeToUsePointFieldData()
    mapper.InterpolateScalarsBeforeMappingOn()

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

    # Renderer
    renderer = vtk.vtkRenderer()
    renderer.AddViewProp(actor)
    renderer.SetBackground(colors.GetColor3d('DimGray'))

    renderer.GetActiveCamera().SetPosition(9.0, 9.0, 7.0)
    renderer.GetActiveCamera().SetFocalPoint(0, 0, 0)
    renderer.GetActiveCamera().SetViewUp(0.2, -0.7, 0.7)
    renderer.GetActiveCamera().SetDistance(14.5)

    # Window and Interactor
    window = vtk.vtkRenderWindow()
    window.AddRenderer(renderer)
    window.SetSize(600, 600)
    window.SetWindowName('ReadExodusData')

    interactor = vtk.vtkRenderWindowInteractor()
    interactor.SetRenderWindow(window)
    interactor.Initialize()

    # Show the result
    window.Render()
    interactor.Start()
Esempio n. 10
0
def integrate(name, var):
    """ given filename and var, generate profile """
    d = vtk.vtkExodusIIReader() 
    d.SetFileName(name) 
    d.UpdateInformation() 

    print var
    d.SetPointResultArrayStatus(var,1) 
    d.Update() 
    
    blocks = d.GetOutput().GetNumberOfBlocks()
    data   = d.GetOutput()
    
    #
    # range to integrate over
    #
    height = 0.804380714893
    thresh = 0.004
    
    rmin = 0.0
    rmax = 1.0
    nr   = 10
    dr = (rmax-rmin)/nr

    #
    # print data.GetBlock(0).GetBlock(0).GetPointData().GetArray(var).GetValue(0)
    #
    
    for j in xrange(blocks):
        blk = data.GetBlock(0).GetBlock(j)
        try:
            pts = blk.GetNumberOfPoints()
        except:
            ss='no data in this block'
        else:
            # grabbing vtkDataArray
            pt_data  = blk.GetPointData().GetArray(var)
            pt_data2 = blk.GetPointData().GetArray(var)

            
            
            if pt_data is None:
                print 'Nada!'
                print 'I cannot find the variable field: ', var
                print 'Exiting...'
                sys.exit(1)

            for i in xrange(pts):
                # gather x,y,z location
                z,y,x = blk.GetPoint(i)

                # gather point scalar value
                #print dir(pt_data)
                u = pt_data.GetValue(i)
                print u
Esempio n. 11
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(
         self,
         module_manager,
         vtk.vtkExodusIIReader(),
         "Reading vtkExodusII.",
         (),
         ("vtkExodusII",),
         replaceDoc=True,
         inputFunctions=None,
         outputFunctions=None,
     )
Esempio n. 12
0
    def testAll(self):
        reader = vtk.vtkExodusIIReader()
        reader.SetFileName("" + str(VTK_DATA_ROOT) + "/Data/disk_out_ref.ex2")
        reader.SetPointResultArrayStatus("Temp", 1)
        reader.SetPointResultArrayStatus("Pres", 1)
        reader.Update()

        input = reader.GetOutput().GetBlock(0).GetBlock(0)

        cf = vtk.vtkContourFilter()
        cf.SetInputData(input)
        cf.SetValue(0, 400)
        cf.SetInputArrayToProcess(0, 0, 0, 0, "Temp")
        cf.GenerateTrianglesOff()
        cf.Update()
        self.assertEqual(cf.GetOutput().GetNumberOfPoints(), 1047)
        self.assertEqual(cf.GetOutput().GetNumberOfCells(), 1028)

        cf.GenerateTrianglesOn()
        cf.Update()
        self.assertEqual(cf.GetOutput().GetNumberOfPoints(), 1047)
        self.assertEqual(cf.GetOutput().GetNumberOfCells(), 2056)

        # Check that expected arrays are in the output

        # The active scalars in the input shouldn't effect the
        # scalars in the output
        availableScalars = ["Temp", "Pres"]
        for scalar in availableScalars:

            input.GetPointData().SetActiveScalars(scalar)

            cf.ComputeScalarsOn()
            cf.Update()

            pd = cf.GetOutput().GetPointData()
            self.assertNotEqual(pd.GetArray("Temp"), None)
            self.assertNotEqual(pd.GetArray("Pres"), None)

            cf.ComputeScalarsOff()  # "Temp" array should not be in output
            cf.Update()

            pd = cf.GetOutput().GetPointData()
            self.assertEqual(pd.GetArray("Temp"), None)
            self.assertNotEqual(pd.GetArray("Pres"), None)
Esempio n. 13
0
  def testAll(self):
    reader = vtk.vtkExodusIIReader()
    reader.SetFileName("" + str(VTK_DATA_ROOT) + "/Data/disk_out_ref.ex2")
    reader.SetPointResultArrayStatus("Temp", 1);
    reader.SetPointResultArrayStatus("Pres", 1);
    reader.Update();

    input = reader.GetOutput().GetBlock(0).GetBlock(0);

    cf = vtk.vtkContourFilter()
    cf.SetInputData(input)
    cf.SetValue(0,400)
    cf.SetInputArrayToProcess(0, 0, 0, 0, "Temp");
    cf.GenerateTrianglesOff()
    cf.Update()
    self.assertEqual(cf.GetOutput().GetNumberOfPoints(), 1047)
    self.assertEqual(cf.GetOutput().GetNumberOfCells(), 1028)

    cf.GenerateTrianglesOn()
    cf.Update()
    self.assertEqual(cf.GetOutput().GetNumberOfPoints(), 1047)
    self.assertEqual(cf.GetOutput().GetNumberOfCells(), 2056)

    # Check that expected arrays are in the output

    # The active scalars in the input shouldn't effect the
    # scalars in the output
    availableScalars = ["Temp", "Pres"]
    for scalar in availableScalars:

      input.GetPointData().SetActiveScalars(scalar)

      cf.ComputeScalarsOn()
      cf.Update()

      pd = cf.GetOutput().GetPointData()
      self.assertNotEqual(pd.GetArray("Temp"), None)
      self.assertNotEqual(pd.GetArray("Pres"), None)

      cf.ComputeScalarsOff() # "Temp" array should not be in output
      cf.Update()

      pd = cf.GetOutput().GetPointData()
      self.assertEqual(pd.GetArray("Temp"), None)
      self.assertNotEqual(pd.GetArray("Pres"), None)
Esempio n. 14
0
    def __init__(self, filename, **kwargs):
        super(ExodusReader, self).__init__(**kwargs)

        # Set the filename for the reader.
        self.__filename = filename
        if not os.path.isfile(self.__filename):
            raise IOError("The file {} is not a valid filename.".format(
                self.__filename))

        self.__vtkreader = vtk.vtkExodusIIReader()
        self.__active = None  # see utils.get_active_filenames
        self.__current = None  # current TimeData object
        self.__timedata = []  # all the TimeData objects
        self.__fileinfo = collections.OrderedDict(
        )  # sorted FileInformation objects
        self.__blockinfo = dict()  # BlockInformation objects
        self.__variableinfo = collections.OrderedDict(
        )  # VariableInformation objects
Esempio n. 15
0
def integrate(name, var):
    """ given filename and var, generate profile """
    d = vtk.vtkExodusIIReader() 
    d.SetFileName(name) 
    d.UpdateInformation() 
    
    d.SetPointResultArrayStatus(var,1) 
    d.Update() 
    
    blocks = d.GetOutput().GetNumberOfBlocks()
    data   = d.GetOutput()
    
    # range to integrate at
    height = 0.804380714893
    thresh = 0.004
    
    rmin = 0.0
    rmax = 1.0
    nr   = 10
    dr = (rmax-rmin)/nr
    rint = np.zeros(nr)
    rn   = np.ones(nr)

    for j in xrange(blocks):
        blk = data.GetBlock(0).GetBlock(j)
        pts    = blk.GetNumberOfPoints()
        pt_data = blk.GetPointData().GetArray(var)

        for i in xrange(pts):
            # gather x,y,z location
            z,y,x = blk.GetPoint(i)

            # gather point scalar value
            u = pt_data.GetValue(i)

            # now, find all values near the target height
            # (convert to cylindrical)
            if(abs(z - height) < thresh):
                r  = np.sqrt((x)**2 + (y)**2)
                fr = np.floor(r/dr)
                rint[fr] += u
                rn  [fr] += 1
    return rint/rn
Esempio n. 16
0
    def __init__(self, filename, **kwargs):
        super(ExodusReader, self).__init__(**kwargs)

        # Set the filename for the reader.
        self.__filename = filename
        if not os.path.isfile(self.__filename):
            raise IOError("The file {} is not a valid filename.".format(self.__filename))

        self.__vtkreader = vtk.vtkExodusIIReader()
        self.__active = None # see utils.get_active_filenames
        self.__current = None # current TimeData object
        self.__timedata = [] # all the TimeData objects
        self.__fileinfo = collections.OrderedDict() # sorted FileInformation objects
        self.__blockinfo = dict() # BlockInformation objects
        self.__variableinfo = collections.OrderedDict() # VariableInformation objects

        # Error handling
        self._error_observer = ExodusReaderErrorObserver()
        self.__vtkreader.AddObserver('ErrorEvent', self._error_observer)
  def testAll(self):
    reader = vtk.vtkExodusIIReader()
    reader.SetFileName("" + str(VTK_DATA_ROOT) + "/Data/disk_out_ref.ex2")
    reader.SetPointResultArrayStatus("Temp",1);
    reader.Update ();

    input = reader.GetOutput().GetBlock(0).GetBlock(0);

    cf = vtk.vtkContourFilter()
    cf.SetInputData(input)
    cf.SetValue(0,400)
    cf.SetInputArrayToProcess(0, 0, 0, 0, "Temp");
    cf.GenerateTrianglesOff()
    cf.Update()
    self.failUnlessEqual(cf.GetOutput().GetNumberOfPoints(),1047)
    self.failUnlessEqual(cf.GetOutput().GetNumberOfCells(),1028)

    cf.GenerateTrianglesOn()
    cf.Update()
    self.failUnlessEqual(cf.GetOutput().GetNumberOfPoints(),1047)
    self.failUnlessEqual(cf.GetOutput().GetNumberOfCells(),2056)
Esempio n. 18
0
    def load(self):
        self._reader = vtk.vtkExodusIIReader()

        with common.lock_file(self._file_name):
            self._readTimeInfo()

            self._reader.SetFileName(self._file_name)
            if self._times is not None:
                self._reader.SetTimeStep(self._time_steps[-1])
            self._reader.UpdateInformation()
            self._reader.SetAllArrayStatus(vtk.vtkExodusIIReader.NODAL, 1)
            self._reader.SetAllArrayStatus(vtk.vtkExodusIIReader.ELEM_BLOCK, 1)
            self._reader.SetAllArrayStatus(vtk.vtkExodusIIReader.GLOBAL, 1)
            self._reader.Update()

            self._readBlockInfo()
            for obj_type, data in self._block_info.items():
                for info in data.values():
                    self._reader.SetObjectStatus(info.object_type,
                                                 info.object_index, 1)
            self._readVariableInfo()
Esempio n. 19
0
  def testAll(self):
    reader = vtk.vtkExodusIIReader()
    reader.SetFileName("" + str(VTK_DATA_ROOT) + "/Data/disk_out_ref.ex2")
    reader.SetPointResultArrayStatus("Temp",1);
    reader.Update ();

    input = reader.GetOutput().GetBlock(0).GetBlock(0);

    cf = vtk.vtkContourFilter()
    cf.SetInputData(input)
    cf.SetValue(0,400)
    cf.SetInputArrayToProcess(0, 0, 0, 0, "Temp");
    cf.GenerateTrianglesOff()
    cf.Update()
    self.failUnlessEqual(cf.GetOutput().GetNumberOfPoints(),1047)
    self.failUnlessEqual(cf.GetOutput().GetNumberOfCells(),1028)

    cf.GenerateTrianglesOn()
    cf.Update()
    self.failUnlessEqual(cf.GetOutput().GetNumberOfPoints(),1047)
    self.failUnlessEqual(cf.GetOutput().GetNumberOfCells(),2056)
def ExtractSolutionFromExodus(inputExodusFile,variableID,timeID,fileID):
  """
  extract data as a vector from exodus file
  """
  import vtk
  import vtk.util.numpy_support as vtkNumPy 
  import numpy
  vtkExodusIIReader = vtk.vtkExodusIIReader()
  print "opening %s " % inputExodusFile 
  vtkExodusIIReader.SetFileName( inputExodusFile )
  vtkExodusIIReader.Update()
  ntime  = vtkExodusIIReader.GetNumberOfTimeSteps()
  print "ntime %d varID %s time %d " % (ntime,variableID,timeID)
  vtkExodusIIReader.SetTimeStep(timeID) 
  vtkExodusIIReader.SetPointResultArrayStatus(variableID,1)
  vtkExodusIIReader.Update()
  # multi block
  if vtkExodusIIReader.GetOutput().IsA("vtkMultiBlockDataSet"):
    iter = vtkExodusIIReader.GetOutput().NewIterator()
    iter.UnRegister(None)
    iter.InitTraversal()
    # initialize list for storage
    Soln = []
    # loop over blocks...
    while not iter.IsDoneWithTraversal():
      curInput = iter.GetCurrentDataObject()
      fem_point_data= curInput.GetPointData() 
      Soln.append( vtkNumPy.vtk_to_numpy(fem_point_data.GetArray(variableID)) ) 
      iter.GoToNextItem();
    # concatenate blocks
    numpy.savetxt( ("data/"+SolnOutputTemplate+".%d") % (variableID,timeID,fileID),numpy.concatenate(Soln))
  # single block
  else:
    curInput = vtkExodusIIReader.GetOutput()
    fem_point_data= curInput.GetPointData() 
    Soln = vtkNumPy.vtk_to_numpy(fem_point_data.GetArray(variableID)) 
    numpy.savetxt( ("data/"+SolnOutputTemplate+".%d") % (variableID,timeID,fileID),Soln)
Esempio n. 21
0
def read(filetype, filename):
    import vtk
    from vtk.util import numpy_support

    def _read_data(data):
        """Extract numpy arrays from a VTK data set.
        """
        # Go through all arrays, fetch data.
        out = {}
        for k in range(data.GetNumberOfArrays()):
            array = data.GetArray(k)
            if array:
                array_name = array.GetName()
                out[array_name] = numpy.copy(
                    vtk.util.numpy_support.vtk_to_numpy(array))
        return out

    def _read_cells(vtk_mesh):
        data = numpy.copy(
            vtk.util.numpy_support.vtk_to_numpy(vtk_mesh.GetCells().GetData()))
        offsets = numpy.copy(
            vtk.util.numpy_support.vtk_to_numpy(
                vtk_mesh.GetCellLocationsArray()))
        types = numpy.copy(
            vtk.util.numpy_support.vtk_to_numpy(vtk_mesh.GetCellTypesArray()))

        # `data` is a one-dimensional vector with
        # (num_points0, p0, p1, ... ,pk, numpoints1, p10, p11, ..., p1k, ...
        # Translate it into the cells dictionary.
        cells = {}
        for vtk_type, meshio_type in vtk_to_meshio_type.items():
            # Get all offsets for vtk_type
            os = offsets[numpy.argwhere(types == vtk_type).transpose()[0]]
            num_cells = len(os)
            if num_cells > 0:
                if meshio_type == "polygon":
                    for idx_cell in range(num_cells):
                        num_pts = data[os[idx_cell]]
                        cell = data[os[idx_cell] + 1:os[idx_cell] + 1 +
                                    num_pts]
                        key = meshio_type + str(num_pts)
                        if key in cells:
                            cells[key] = numpy.vstack([cells[key], cell])
                        else:
                            cells[key] = cell
                else:
                    num_pts = data[os[0]]
                    # instantiate the array
                    arr = numpy.empty((num_cells, num_pts), dtype=int)
                    # store the num_pts entries after the offsets into the columns
                    # of arr
                    for k in range(num_pts):
                        arr[:, k] = data[os + k + 1]
                    cells[meshio_type] = arr

        return cells

    if filetype in ["vtk", "vtk-ascii", "vtk-binary"]:
        reader = vtk.vtkUnstructuredGridReader()
        reader.SetFileName(filename)
        reader.SetReadAllNormals(1)
        reader.SetReadAllScalars(1)
        reader.SetReadAllTensors(1)
        reader.SetReadAllVectors(1)
        reader.Update()
        vtk_mesh = reader.GetOutput()
    elif filetype in ["vtu", "vtu-ascii", "vtu-binary"]:
        reader = vtk.vtkXMLUnstructuredGridReader()
        reader.SetFileName(filename)
        reader.Update()
        vtk_mesh = reader.GetOutput()
    elif filetype in ["xdmf", "xdmf2"]:
        reader = vtk.vtkXdmfReader()
        reader.SetFileName(filename)
        reader.SetReadAllColorScalars(1)
        reader.SetReadAllFields(1)
        reader.SetReadAllNormals(1)
        reader.SetReadAllScalars(1)
        reader.SetReadAllTCoords(1)
        reader.SetReadAllTensors(1)
        reader.SetReadAllVectors(1)
        reader.Update()
        vtk_mesh = reader.GetOutputDataObject(0)
    elif filetype == "xdmf3":
        reader = vtk.vtkXdmf3Reader()
        reader.SetFileName(filename)
        reader.SetReadAllColorScalars(1)
        reader.SetReadAllFields(1)
        reader.SetReadAllNormals(1)
        reader.SetReadAllScalars(1)
        reader.SetReadAllTCoords(1)
        reader.SetReadAllTensors(1)
        reader.SetReadAllVectors(1)
        reader.Update()
        vtk_mesh = reader.GetOutputDataObject(0)
    else:
        assert filetype == "exodus", "Unknown file type '{}'.".format(filename)
        reader = vtk.vtkExodusIIReader()
        reader.SetFileName(filename)
        vtk_mesh = _read_exodusii_mesh(reader)

    # Explicitly extract points, cells, point data, field data
    points = numpy.copy(
        numpy_support.vtk_to_numpy(vtk_mesh.GetPoints().GetData()))
    cells = _read_cells(vtk_mesh)

    point_data = _read_data(vtk_mesh.GetPointData())
    field_data = _read_data(vtk_mesh.GetFieldData())

    cell_data = _read_data(vtk_mesh.GetCellData())
    # split cell_data by the cell type
    cd = {}
    index = 0
    for cell_type in cells:
        num_cells = len(cells[cell_type])
        cd[cell_type] = {}
        for name, array in cell_data.items():
            cd[cell_type][name] = array[index:index + num_cells]
        index += num_cells
    cell_data = cd

    return Mesh(points,
                cells,
                point_data=point_data,
                cell_data=cell_data,
                field_data=field_data)
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})
Esempio n. 23
0
  def setFileName(self, file_name):
    reader = vtk.vtkExodusIIReader()
    reader.SetFileName(self.file_name)
    reader.SetAllArrayStatus(vtk.vtkExodusIIReader.NODAL, 1)
    reader.SetAllArrayStatus(vtk.vtkExodusIIReader.EDGE_SET, 1)
    reader.SetAllArrayStatus(vtk.vtkExodusIIReader.SIDE_SET, 1)
    reader.SetAllArrayStatus(vtk.vtkExodusIIReader.NODE_SET, 1)
    reader.SetAllArrayStatus(vtk.vtkExodusIIReader.NODAL_TEMPORAL, 1)
    reader.UpdateInformation()
    reader.SetObjectStatus(vtk.vtkExodusIIReader.NODE_SET, 0, 1)

    num_sidesets = reader.GetNumberOfSideSetArrays()
    num_nodesets = reader.GetNumberOfNodeSetArrays()
    num_blocks = reader.GetNumberOfElementBlockArrays()

    self.sidesets = []
    self.sideset_id_to_exodus_block = {}
    for i in xrange(num_sidesets):
      sideset_id = reader.GetObjectId(vtk.vtkExodusIIReader.SIDE_SET,i)
      self.sidesets.append(sideset_id)
      self.sideset_id_to_exodus_block[sideset_id] = i
      reader.SetObjectStatus(vtk.vtkExodusIIReader.SIDE_SET, i, 1)

    self.nodesets = []
    self.nodeset_id_to_exodus_block = {}
    for i in xrange(num_nodesets):
      nodeset_id = reader.GetObjectId(vtk.vtkExodusIIReader.NODE_SET,i)
      self.nodesets.append(nodeset_id)
      self.nodeset_id_to_exodus_block[nodeset_id] = i
      reader.SetObjectStatus(vtk.vtkExodusIIReader.NODE_SET, i, 1)

    self.blocks = []
    self.block_id_to_exodus_block = {}
    for i in xrange(num_blocks):
      block_id = reader.GetObjectId(vtk.vtkExodusIIReader.ELEM_BLOCK,i)
      self.blocks.append(block_id)
      self.block_id_to_exodus_block[block_id] = i

    reader.SetTimeStep(1)
    reader.Update()

    self.data = reader.GetOutput()

    self.all_actors = []

    self.sideset_actors = {}
    self.clipped_sideset_actors = {}

    self.current_sideset_actors = self.sideset_actors
    for i in xrange(num_sidesets):
      actor = ExodusActor(self.renderer, self.data, ExodusMap.sideset_vtk_block, i)
      actor.setColor(red)
      self.sideset_actors[str(self.sidesets[i])] = actor
      self.all_actors.append(actor)

      clipped_actor = ClippedActor(actor, self.plane)
      self.clipped_sideset_actors[str(self.sidesets[i])] = clipped_actor
      self.all_actors.append(clipped_actor)

      name = reader.GetObjectName(vtk.vtkExodusIIReader.SIDE_SET,i).split(' ')
      if 'Unnamed' not in name:
        self.sideset_actors[name[0]] = actor
        self.clipped_sideset_actors[name[0]] = clipped_actor

    self.nodeset_actors = {}
    self.clipped_nodeset_actors = {}

    self.current_nodeset_actors = self.nodeset_actors
    for i in xrange(num_nodesets):
      actor = ExodusActor(self.renderer, self.data, ExodusMap.nodeset_vtk_block, i)
      actor.setColor(red)
      self.nodeset_actors[str(self.nodesets[i])] = actor
      self.all_actors.append(actor)

      clipped_actor = ClippedActor(actor, self.plane)
      self.clipped_nodeset_actors[str(self.nodesets[i])] = clipped_actor
      self.all_actors.append(clipped_actor)

      name = reader.GetObjectName(vtk.vtkExodusIIReader.NODE_SET,i).split(' ')
      if 'Unnamed' not in name:
        self.nodeset_actors[name[0]] = actor
        self.clipped_nodeset_actors[name[0]] = clipped_actor

    self.block_actors = {}
    self.clipped_block_actors = {}

    self.current_block_actors = self.block_actors
    for i in xrange(num_blocks):
      actor = ExodusActor(self.renderer, self.data, ExodusMap.element_vtk_block, i)
      self.block_actors[str(self.blocks[i])] = actor
      self.all_actors.append(actor)

      actor.show()
      actor.showEdges()

      clipped_actor = ClippedActor(actor, self.plane)
      self.clipped_block_actors[str(self.blocks[i])] = clipped_actor
      self.all_actors.append(clipped_actor)

      name = reader.GetObjectName(vtk.vtkExodusIIReader.ELEM_BLOCK,i).split(' ')
      if 'Unnamed' not in name:
        self.block_actors[name[0]] = actor
        self.clipped_block_actors[name[0]] = clipped_actor

    self.setBounds()

    # Avoid z-buffer fighting
    vtk.vtkPolyDataMapper().SetResolveCoincidentTopologyToPolygonOffset()

    self.renderer.ResetCamera()
    self.vtkwidget.updateGL()
def pennesModeling(**kwargs):
    """
  treatment planning model 
  """
    # import needed modules
    import petsc4py, numpy, sys
    PetscOptions = sys.argv
    PetscOptions.append("-ksp_monitor")
    PetscOptions.append("-ksp_rtol")
    PetscOptions.append("1.0e-15")
    #PetscOptions.append("-idb")
    petsc4py.init(PetscOptions)

    from petsc4py import PETSc

    # break processors into separate communicators
    petscRank = PETSc.COMM_WORLD.getRank()
    petscSize = PETSc.COMM_WORLD.Get_size()
    sys.stdout.write("petsc rank %d petsc nproc %d\n" % (petscRank, petscSize))

    # set shell context
    import femLibrary
    # initialize libMesh data structures
    libMeshInit = femLibrary.PyLibMeshInit(PetscOptions, PETSc.COMM_WORLD)

    # the original configuration ini file should be stored
    config = kwargs['config_parser']

    # store control variables
    getpot = femLibrary.PylibMeshGetPot(PetscOptions)

    # copy all values from the input file
    for section in config.sections():
        for name, value in config.items(section):
            #print "%s/%s" % (section,name) , value
            getpot.SetIniValue("%s/%s" % (section, name), value)

    # nodeset 1 will be treated as dirichlet
    dirichletID = 1
    getpot.SetIniValue("bc/u_dirichlet", '%d' % dirichletID)

    # set tissue lookup tables
    k_0Table = {
        "default": config.getfloat("thermal_conductivity", "k_0_healthy"),
        "vessel": config.getfloat("thermal_conductivity", "k_0_healthy"),
        "grey": config.getfloat("thermal_conductivity", "k_0_grey"),
        "white": config.getfloat("thermal_conductivity", "k_0_white"),
        "csf": config.getfloat("thermal_conductivity", "k_0_csf"),
        "tumor": config.getfloat("thermal_conductivity", "k_0_tumor")
    }
    w_0Table = {
        "default": config.getfloat("perfusion", "w_0_healthy"),
        "vessel": config.getfloat("perfusion", "w_0_healthy"),
        "grey": config.getfloat("perfusion", "w_0_grey"),
        "white": config.getfloat("perfusion", "w_0_white"),
        "csf": config.getfloat("perfusion", "w_0_csf"),
        "tumor": config.getfloat("perfusion", "w_0_tumor")
    }
    mu_aTable = {
        "default": config.getfloat("optical", "mu_a_healthy"),
        "vessel": config.getfloat("optical", "mu_a_healthy"),
        "grey": config.getfloat("optical", "mu_a_grey"),
        "white": config.getfloat("optical", "mu_a_white"),
        "csf": config.getfloat("optical", "mu_a_csf"),
        "tumor": config.getfloat("optical", "mu_a_tumor")
    }
    mu_sTable = {
        "default": config.getfloat("optical", "mu_s_healthy"),
        "vessel": config.getfloat("optical", "mu_s_healthy"),
        "grey": config.getfloat("optical", "mu_s_grey"),
        "white": config.getfloat("optical", "mu_s_white"),
        "csf": config.getfloat("optical", "mu_s_csf"),
        "tumor": config.getfloat("optical", "mu_s_tumor")
    }
    labelTable = {
        config.get("labels", "greymatter"): "grey",
        config.get("labels", "whitematter"): "white",
        config.get("labels", "csf"): "csf",
        config.get("labels", "tumor"): "tumor",
        config.get("labels", "vessel"): "vessel"
    }
    labelCount = {
        "default": 0,
        "grey": 0,
        "white": 0,
        "csf": 0,
        "tumor": 0,
        "vessel": 0
    }
    # imaging params
    import vtk
    import vtk.util.numpy_support as vtkNumPy
    SegmentFile = config.get("exec", "segment_file")
    # set the default reader based on extension
    if (SegmentFile.split(".").pop() == "vtk"):
        vtkImageReader = vtk.vtkDataSetReader
    elif (SegmentFile.split(".").pop() == "vti"):
        vtkImageReader = vtk.vtkXMLImageDataReader
    else:
        raise RuntimeError("uknown file")

    # get dimension info from header
    vtkSetupReader = vtkImageReader()
    vtkSetupReader.SetFileName(SegmentFile)
    vtkSetupReader.Update()
    vtkImageMask = vtkSetupReader.GetOutput()
    dimensions = vtkSetupReader.GetOutput().GetDimensions()
    numberPointsImage = vtkSetupReader.GetOutput().GetNumberOfPoints()
    spacing_mm = vtkSetupReader.GetOutput().GetSpacing()
    origin_mm = vtkSetupReader.GetOutput().GetOrigin()
    # convert to meters
    spacing = [dx * .001 for dx in spacing_mm]
    origin = [x0 * .001 for x0 in origin_mm]

    # pass pointer to c++
    image_cells = vtkImageMask.GetPointData()
    data_array = vtkNumPy.vtk_to_numpy(image_cells.GetArray(0))
    # need to pass numpy array's w/ Fortran storage... ie painful to debug
    imageDataVec = PETSc.Vec().createWithArray(numpy.ravel(data_array,
                                                           order='F'),
                                               comm=PETSc.COMM_SELF)

    # FIXME - center around quadrature in out-of-plane direction
    # FIXME - need better out of plane cooling model
    quadratureOffset = 1. / numpy.sqrt(3.0) * spacing[2] / 2.0
    # expecting roi and subsample of the form:
    #     roi = [(40,210),(30,220),(6,78)]
    #     subsample = [3,3,2]
    ROI = eval(config.get('exec', 'roi'))
    subsample = eval(config.get('exec', 'subsample'))
    nelemROI = [(pixel[1] - pixel[0] - 1) / sub
                for pixel, sub in zip(ROI, subsample)]
    xbounds = [
        origin[0] + spacing[0] * (ROI[0][0] + 0.5),
        origin[0] + spacing[0] * (ROI[0][1] + 0.5)
    ]
    ybounds = [
        origin[1] + spacing[1] * (ROI[1][0] + 0.5),
        origin[1] + spacing[1] * (ROI[1][1] + 0.5)
    ]
    zbounds = [
        origin[2] + spacing[2] * (ROI[2][0] + 0.5),
        origin[2] + spacing[2] * (ROI[2][1] + 0.5)
    ]
    if (petscRank == 0):
        print "#points", numberPointsImage, "dimensions ", dimensions, "spacing ", spacing, "origin ", origin
        print "ROI", ROI, "nelemROI ", nelemROI, "bounds", xbounds, ybounds, zbounds

    #set to steady state solve
    getpot.SetIniValue("steadystate/domain_0", "true")

    # initialize FEM Mesh
    femMesh = femLibrary.PylibMeshMesh()
    #femMesh.SetupUnStructuredGrid(kwargs['mesh_file'],0,RotationMatrix, Translation  )
    #femMesh.ReadFile(kwargs['mesh_file'])

    femMesh.SetupStructuredGrid(nelemROI, xbounds, ybounds, zbounds,
                                [2, 2, 2, 2, 2, 2])
    # get output file name else set default name
    try:
        MeshOutputFile = config.get("exec", "exodus_file")
    except ConfigParser.NoOptionError:
        MeshOutputFile = "fem.e"

    # add the data structures for the Background System Solve
    # set deltat, number of time steps, power profile, and add system
    eqnSystems = femLibrary.PylibMeshEquationSystems(femMesh, getpot)

    #getpot.SetIniPower(1,[[19,119],[90.0,100.0]] )
    getpot.SetIniPower(1, kwargs['powerHistory'])
    # AddPennesSDASystem
    # AddPennesRFSystem
    # AddPennesDeltaPSystem
    pennesSystem = eval("eqnSystems.%s('StateSystem',kwargs['deltat'])" %
                        kwargs['physics'])
    pennesSystem.AddStorageVectors(kwargs['ntime'] + 1)

    # add system for labels
    # FIXME: need both nodal, for dirichlet bc, and element version, for parameter masks
    maskElemSystem = eqnSystems.AddExplicitSystem("ElemImageMask")
    maskElemSystem.AddConstantMonomialVariable("maskElem")

    # initialize libMesh data structures
    eqnSystems.init()

    # print info
    eqnSystems.PrintSelf()

    # setup imaging to interpolate onto FEM mesh
    femImaging = femLibrary.PytttkImaging(getpot, dimensions, origin, spacing)
    # Project imaging onto libMesh data structures
    femImaging.ProjectImagingToFEMMesh("ElemImageMask", 0.0, imageDataVec,
                                       eqnSystems)
    femImaging.ProjectImagingToFEMMesh("StateSystem", 0.0, imageDataVec,
                                       eqnSystems)

    # create dirichlet nodes from this mask
    numNodes = pennesSystem.PetscFEMSystemCreateNodeSetFromMask(
        config.getfloat("labels", "vessel"), dirichletID)
    print "# of dirichlet nodes %d" % numNodes

    # get image label as numpy array
    imageLabel = maskElemSystem.GetSolutionVector()[...]
    #imageLabel = numpy.floor(10.0*imageLabel.copy())+1
    k_0Label = imageLabel.copy()
    w_0Label = imageLabel.copy()
    mu_aLabel = imageLabel.copy()
    mu_sLabel = imageLabel.copy()
    for (idpos, label) in enumerate(imageLabel):
        try:
            tissueType = labelTable["%d" % int(label)]
        except KeyError:
            tissueType = "default"
        labelCount[tissueType] = labelCount[tissueType] + 1
        k_0Label[idpos] = k_0Table[tissueType]
        w_0Label[idpos] = w_0Table[tissueType]
        mu_aLabel[idpos] = mu_aTable[tissueType]
        mu_sLabel[idpos] = mu_sTable[tissueType]
    # create array of imaging data as petsc vec
    k_0Vec = PETSc.Vec().createWithArray(k_0Label, comm=PETSc.COMM_SELF)
    w_0Vec = PETSc.Vec().createWithArray(w_0Label, comm=PETSc.COMM_SELF)
    mu_aVec = PETSc.Vec().createWithArray(mu_aLabel, comm=PETSc.COMM_SELF)
    mu_sVec = PETSc.Vec().createWithArray(mu_sLabel, comm=PETSc.COMM_SELF)
    # copy material properties to the system
    eqnSystems.GetSystem("k_0").SetSolutionVector(k_0Vec)
    eqnSystems.GetSystem("w_0").SetSolutionVector(w_0Vec)
    eqnSystems.GetSystem("mu_a").SetSolutionVector(mu_aVec)
    eqnSystems.GetSystem("mu_s").SetSolutionVector(mu_sVec)

    # write IC
    exodusII_IO = femLibrary.PylibMeshExodusII_IO(femMesh)
    exodusII_IO.WriteTimeStep(MeshOutputFile, eqnSystems, 1, 0.0)
    exodusII_IO.WriteParameterSystems(eqnSystems)

    # setup IC
    pennesSystem.PetscFEMSystemSetupInitialConditions()

    # create list of laser positions
    laserPositionList = [((.015, .015, 2 * spacing[2] + quadratureOffset),
                          (.018, .018, 2 * spacing[2] + quadratureOffset)),
                         ((.015, .015, 2 * spacing[2] + quadratureOffset),
                          (.016, .018, 2 * spacing[2] + quadratureOffset)),
                         ((.015, .015, 1 * spacing[2] + quadratureOffset),
                          (.014, .014, 1 * spacing[2] + quadratureOffset)),
                         ((.015, .015, 1 * spacing[2] + quadratureOffset),
                          (.015, .018, 3 * spacing[2] + quadratureOffset))]
    # time stamp
    import pickle, time
    timeStamp = 0
    # set power id to turn laser on
    pennesSystem.PetscFEMSystemUpdateTimeStep(1)
    # loop over laser position and solve steady state equations for each position
    #for (idpos,(pos0,pos1)) in enumerate(laserPositionList):
    # loop and read new laser parameters
    while (True):
        if (os.path.getmtime(fem_params['ini_filename']) > timeStamp):
            timeStamp = os.path.getmtime(fem_params['ini_filename'])
            newIni = ConfigParser.SafeConfigParser({})
            newIni.read(fem_params['ini_filename'])

            laserParams = {}
            laserParams['position1'] = [
                newIni.getfloat("probe", varID)
                for varID in ["x_0", "y_0", "z_0"]
            ]
            laserParams['position2'] = [
                newIni.getfloat("probe", varID)
                for varID in ["x_1", "y_1", "z_1"]
            ]

            print "laser position = ", newIni.getfloat("timestep",
                                                       "power"), laserParams
            pennesSystem.PennesSDASystemUpdateLaserPower(
                newIni.getfloat("timestep", "power"), 1)
            pennesSystem.PennesSDASystemUpdateLaserPosition(
                laserParams['position1'], laserParams['position2'])
            pennesSystem.SystemSolve()
            #fem.StoreTransientSystemTimeStep("StateSystem",timeID )
            #exodusII_IO.WriteTimeStep(MeshOutputFile ,eqnSystems, idpos+2, idpos*kwargs['deltat'])
            exodusII_IO.WriteTimeStep(MeshOutputFile, eqnSystems, 2, 1.0)
            exodusII_IO.WriteParameterSystems(eqnSystems)
            # write to txt file
            if (petscRank == 0):
                time.sleep(1)
                vtkExodusIIReader = vtk.vtkExodusIIReader()
                print "opening %s " % MeshOutputFile
                vtkExodusIIReader.SetFileName(MeshOutputFile)
                vtkExodusIIReader.Update()
                ntime = vtkExodusIIReader.GetNumberOfTimeSteps()
                variableID = "u0"
                print "ntime %d %s " % (ntime, variableID)
                vtkExodusIIReader.SetTimeStep(1)
                vtkExodusIIReader.SetPointResultArrayStatus(variableID, 1)
                vtkExodusIIReader.Update()
                curInput = None
                # multi block
                if vtkExodusIIReader.GetOutput().IsA("vtkMultiBlockDataSet"):
                    iter = vtkExodusIIReader.GetOutput().NewIterator()
                    iter.UnRegister(None)
                    iter.InitTraversal()
                    curInput = iter.GetCurrentDataObject()
                else:
                    curInput = vtkExodusIIReader.GetOutput()
                #fem_point_data= curInput.GetPointData().GetArray('u0')
                #Soln=vtkNumPy.vtk_to_numpy(fem_point_data)
                #numpy.savetxt( "temperature.txt" ,Soln)

                # 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
                # scale back to millimeter
                # TODO verify that the data sets are registered in the native slicer coordinate system
                # TODO   segmented data MUST be read in with:
                # TODO add data -> volume -> show options -> ignore orientation
                # TODO add data -> volume -> show options -> ignore orientation
                # TODO add data -> volume -> show options -> ignore orientation
                AffineTransform = vtk.vtkTransform()
                AffineTransform.Translate([0.0, 0.0, 0.0])
                AffineTransform.RotateZ(0.0)
                AffineTransform.RotateY(0.0)
                AffineTransform.RotateX(0.0)
                AffineTransform.Scale([1000., 1000., 1000.])
                # scale to millimeter
                transformFilter = vtk.vtkTransformFilter()
                transformFilter.SetInput(curInput)
                transformFilter.SetTransform(AffineTransform)
                transformFilter.Update()

                # setup contour filter
                vtkContour = vtk.vtkContourFilter()
                vtkContour.SetInput(transformFilter.GetOutput())
                # TODO: not sure why this works...
                # set the array to process at the temperature == u0
                vtkContour.SetInputArrayToProcess(0, 0, 0, 0, 'u0')
                contourValuesList = eval(newIni.get('exec', 'contours'))
                vtkContour.SetNumberOfContours(len(contourValuesList))
                print "plotting array:", vtkContour.GetArrayComponent()
                for idContour, contourValue in enumerate(contourValuesList):
                    print "plotting contour:", idContour, contourValue
                    vtkContour.SetValue(idContour, contourValue)
                vtkContour.Update()

                # setup threshold filter
                vtkThreshold = vtk.vtkThreshold()
                vtkThreshold.SetInput(transformFilter.GetOutput())
                vtkThreshold.ThresholdByLower(contourValuesList[0])
                #vtkThreshold.SetSelectedComponent( 0 )
                vtkThreshold.SetComponentModeToUseAny()
                vtkThreshold.Update()

                # resample onto image
                vtkResample = vtk.vtkCompositeDataProbeFilter()
                vtkResample.SetInput(vtkImageMask)
                vtkResample.SetSource(vtkThreshold.GetOutput())
                vtkResample.Update()

                # write output
                print "writing fem.vtk "
                vtkImageWriter = vtk.vtkDataSetWriter()
                vtkImageWriter.SetFileTypeToBinary()
                vtkImageWriter.SetFileName("fem.vtk")
                vtkImageWriter.SetInput(vtkResample.GetOutput())
                vtkImageWriter.Update()

                # write stl file
                stlWriter = vtk.vtkSTLWriter()
                stlWriter.SetInput(vtkContour.GetOutput())
                stlWriter.SetFileName("fem.stl")
                stlWriter.SetFileTypeToBinary()
                stlWriter.Write()
                # write support file to signal full stl file is written
                #  Slicer module will wait for this file to be written
                #  before trying to open stl file to avoid incomplete reads
                with open('./fem.finish', 'w') as signalFile:
                    signalFile.write("the stl file has been written\n")

        else:
            print "waiting on user input.."
            # echo lookup table
            if (petscRank == 0):
                print "lookup tables"
                print "labeled %d voxels" % len(imageLabel)
                print "labels", labelTable
                print "counts", labelCount
                print "conductivity", k_0Table
                print "perfusion", w_0Table
                print "absorption", mu_aTable
                print "scattering", mu_sTable
            time.sleep(2)
# import vtk module
import vtk
import vtk.util.numpy_support as vtkNumPy

# load FEM data
vtkExodusIIReader = vtk.vtkExodusIIReader()
vtkExodusIIReader.SetFileName("fem_data.e")
vtkExodusIIReader.Update()
ntime = vtkExodusIIReader.GetNumberOfTimeSteps()
femData = vtkExodusIIReader.GetOutput()

# get the bounding box
femBounds = None
if femData.IsA("vtkMultiBlockDataSet"):
    iter = femData.NewIterator()
    iter.UnRegister(None)
    iter.InitTraversal()
    while not iter.IsDoneWithTraversal():
        curInput = iter.GetCurrentDataObject()
        bounds = curInput.GetBounds()
        if femBounds == None:
            femBounds = bounds
        else:
            femBounds = (
                min(femBounds[0], bounds[0]),
                max(femBounds[1], bounds[1]),
                min(femBounds[2], bounds[2]),
                max(femBounds[3], bounds[3]),
                min(femBounds[4], bounds[4]),
                max(femBounds[5], bounds[5]),
            )
Esempio n. 26
0
    def setFileName(self, file_name):
        reader = vtk.vtkExodusIIReader()
        reader.SetFileName(self.file_name)
        reader.SetAllArrayStatus(vtk.vtkExodusIIReader.NODAL, 1)
        reader.SetAllArrayStatus(vtk.vtkExodusIIReader.EDGE_SET, 1)
        reader.SetAllArrayStatus(vtk.vtkExodusIIReader.SIDE_SET, 1)
        reader.SetAllArrayStatus(vtk.vtkExodusIIReader.NODE_SET, 1)
        reader.SetAllArrayStatus(vtk.vtkExodusIIReader.NODAL_TEMPORAL, 1)
        reader.UpdateInformation()
        reader.SetObjectStatus(vtk.vtkExodusIIReader.NODE_SET, 0, 1)

        num_sidesets = reader.GetNumberOfSideSetArrays()
        num_nodesets = reader.GetNumberOfNodeSetArrays()
        num_blocks = reader.GetNumberOfElementBlockArrays()

        self.sidesets = []
        self.sideset_id_to_exodus_block = {}
        for i in xrange(num_sidesets):
            sideset_id = reader.GetObjectId(vtk.vtkExodusIIReader.SIDE_SET, i)
            self.sidesets.append(sideset_id)
            self.sideset_id_to_exodus_block[sideset_id] = i
            reader.SetObjectStatus(vtk.vtkExodusIIReader.SIDE_SET, i, 1)

        self.nodesets = []
        self.nodeset_id_to_exodus_block = {}
        for i in xrange(num_nodesets):
            nodeset_id = reader.GetObjectId(vtk.vtkExodusIIReader.NODE_SET, i)
            self.nodesets.append(nodeset_id)
            self.nodeset_id_to_exodus_block[nodeset_id] = i
            reader.SetObjectStatus(vtk.vtkExodusIIReader.NODE_SET, i, 1)

        self.blocks = []
        self.block_id_to_exodus_block = {}
        for i in xrange(num_blocks):
            block_id = reader.GetObjectId(vtk.vtkExodusIIReader.ELEM_BLOCK, i)
            self.blocks.append(block_id)
            self.block_id_to_exodus_block[block_id] = i

        reader.SetTimeStep(1)
        reader.Update()

        self.data = reader.GetOutput()

        self.all_actors = []

        self.sideset_actors = {}
        self.clipped_sideset_actors = {}

        self.current_sideset_actors = self.sideset_actors
        for i in xrange(num_sidesets):
            actor = ExodusActor(self.renderer, self.data,
                                ExodusMap.sideset_vtk_block, i)
            actor.setColor(red)
            self.sideset_actors[str(self.sidesets[i])] = actor
            self.all_actors.append(actor)

            clipped_actor = ClippedActor(actor, self.plane)
            self.clipped_sideset_actors[str(self.sidesets[i])] = clipped_actor
            self.all_actors.append(clipped_actor)

            name = reader.GetObjectName(vtk.vtkExodusIIReader.SIDE_SET,
                                        i).split(' ')
            if 'Unnamed' not in name:
                self.sideset_actors[name[0]] = actor
                self.clipped_sideset_actors[name[0]] = clipped_actor

        self.nodeset_actors = {}
        self.clipped_nodeset_actors = {}

        self.current_nodeset_actors = self.nodeset_actors
        for i in xrange(num_nodesets):
            actor = ExodusActor(self.renderer, self.data,
                                ExodusMap.nodeset_vtk_block, i)
            actor.setColor(red)
            self.nodeset_actors[str(self.nodesets[i])] = actor
            self.all_actors.append(actor)

            clipped_actor = ClippedActor(actor, self.plane)
            self.clipped_nodeset_actors[str(self.nodesets[i])] = clipped_actor
            self.all_actors.append(clipped_actor)

            name = reader.GetObjectName(vtk.vtkExodusIIReader.NODE_SET,
                                        i).split(' ')
            if 'Unnamed' not in name:
                self.nodeset_actors[name[0]] = actor
                self.clipped_nodeset_actors[name[0]] = clipped_actor

        self.block_actors = {}
        self.clipped_block_actors = {}

        self.current_block_actors = self.block_actors
        for i in xrange(num_blocks):
            actor = ExodusActor(self.renderer, self.data,
                                ExodusMap.element_vtk_block, i)
            self.block_actors[str(self.blocks[i])] = actor
            self.all_actors.append(actor)

            actor.show()
            actor.showEdges()

            clipped_actor = ClippedActor(actor, self.plane)
            self.clipped_block_actors[str(self.blocks[i])] = clipped_actor
            self.all_actors.append(clipped_actor)

            name = reader.GetObjectName(vtk.vtkExodusIIReader.ELEM_BLOCK,
                                        i).split(' ')
            if 'Unnamed' not in name:
                self.block_actors[name[0]] = actor
                self.clipped_block_actors[name[0]] = clipped_actor

        self.setBounds()

        # Avoid z-buffer fighting
        vtk.vtkPolyDataMapper().SetResolveCoincidentTopologyToPolygonOffset()

        self.renderer.ResetCamera()
        self.vtkwidget.updateGL()
Esempio n. 27
0
    def go(self):
        
        print "Mapping",self.cfdData,"to",self.feaMesh
        
        # identify inner wall points

        """
        reader = vtk.vtkSTLReader()
        reader.SetFileName(self.feaMesh)
        reader.ScalarTagsOn()
        reader.Update()
        feadata = reader.GetOutput()
        """
        
        reader = vtk.vtkExodusIIReader()
        reader.SetFileName(self.feaMesh)
        reader.UpdateInformation()
        reader.SetAllArrayStatus(vtk.vtkExodusIIReader.NODAL, 1) # enables all NODAL variables
        reader.GenerateGlobalNodeIdArrayOn()
        reader.GenerateGlobalElementIdArrayOn()
        reader.ExodusModelMetadataOn()
        reader.Update()
        feadata = vtk.vtkCompositeDataGeometryFilter()
        feadata.SetInputConnection(0, reader.GetOutputPort(0))
        feadata.Update()

        transform = vtk.vtkTransform()
        transform.Scale(1000, 1000, 1000)
        test = vtk.vtkTransformPolyDataFilter()
        test.SetTransform(transform)
        test.SetInput(feadata.GetOutput())
        test.Update()
        feadata = test.GetOutput()
        
        normals = vtk.vtkPolyDataNormals()
        normals.SetInput(feadata)
        normals.ComputeCellNormalsOn()
        normals.ComputePointNormalsOn()
        normals.ConsistencyOn()
        normals.AutoOrientNormalsOn()
        normals.SplittingOn()
        normals.Update()
        feabody = normals.GetOutput()
        
        norms = feabody.GetPointData().GetArray('Normals')
        norms_n = numpy_support.vtk_to_numpy(norms)
        #print (norms_n)
        
        feapnts = feabody.GetPoints().GetData()
        feapnts_n = numpy_support.vtk_to_numpy(feapnts)
        #print (feapnts_n)

        reader = vtk.vtkPolyDataReader()
        reader.SetFileName(self.cfdData)
        reader.ReadAllVectorsOn()
        reader.ReadAllScalarsOn()
        reader.Update()
        cfddata = reader.GetOutput()
        
        transform = vtk.vtkTransform()
        transform.Scale(1000, 1000, 1000)
        test = vtk.vtkTransformPolyDataFilter()
        test.SetTransform(transform)
        test.SetInputConnection(reader.GetOutputPort())
        test.Update()
        cfddata = test.GetOutput()
        
        """
        reader = vtk.vtkUnstructuredGridReader()
        reader.SetFileName("volume.vtk")
        reader.ReadAllVectorsOn()
        reader.ReadAllScalarsOn()
        reader.Update()
        cfdvol = reader.GetOutput()
        """ 
       
        cfdpnts = cfddata.GetPoints().GetData()
        cfdpnts_n = numpy_support.vtk_to_numpy(cfdpnts)
        
        pointLocator = vtk.vtkPointLocator()
        pointLocator.SetDataSet(feabody)
        pointLocator.BuildLocator()

        innerIds = []
        for cfdpnt in cfdpnts_n:
            id = pointLocator.FindClosestPoint(cfdpnt)
            innerIds.append(id)
        innerIds = np.unique(innerIds)
            
        # foreach fea innerpoint
        # find the intersection point to cfddata
        # probe field cfddata using intersection point
        # append the field data to feabody
        
        caster = pycaster.rayCaster(cfddata) 
        
        interPoints={}
        interPointsSave = vtk.vtkPoints()
        ptcount=0
        for id in innerIds:
            feainpnt = feapnts_n[id]
            feainnorm = norms_n[id]
            sourcePnt = feainpnt
            targetPnt = feainpnt+(feainnorm*100)
            pointsIntersection = caster.castRay(sourcePnt, targetPnt)
            if len(pointsIntersection)!=0:
                interPointsSave.InsertPoint(ptcount, pointsIntersection[0]+(feainnorm*0))
                interPoints[id]=ptcount
                ptcount+=1
            else:
                targetPnt = feainpnt-(feainnorm*100)
                pointsIntersection = caster.castRay(sourcePnt, targetPnt)
                if len(pointsIntersection)!=0:
                    interPointsSave.InsertPoint(ptcount, pointsIntersection[0]-(feainnorm*0))
                    interPoints[id]=ptcount
                    ptcount+=1

        # for each interPoint, probe cfddata fields

        innerPointData = vtk.vtkPolyData()
        innerPointData.SetPoints(interPointsSave)
        
        """
        # IF LOADING FROM VOLUME
        transform = vtk.vtkTransform()
        transform.Scale(0.001,0.001,0.001)
        test = vtk.vtkTransformPolyDataFilter()
        test.SetTransform(transform)
        test.SetInput(innerPointData)
        test.Update()
        innerPointData = test.GetOutput()
        """
        
        probe = vtk.vtkProbeFilter()
        probe.SetInput(innerPointData)
        probe.SetSource(cfddata)
        
        pd = vtk.vtkAppendPolyData()
        pd.AddInputConnection(probe.GetOutputPort())
        pd.Update()
        probeData=pd.GetOutput()
        
        # detect all fields
        #fields=[]
        #for f in range(0,probeData.GetPointData().GetNumberOfArrays()):
        #    fields.append(probeData.GetPointData().GetArrayName(f))
        
        globalNodeIds=numpy_support.vtk_to_numpy(feabody.GetPointData().GetArray('PedigreeNodeId'))
        
        fieldData={}
        for f in self.fields:
            fieldData[f]=numpy_support.vtk_to_numpy(probeData.GetPointData().GetArray(f))
        
        for f in self.fields:
            ff = open("bc/"+f+"/"+f+"_"+self.cfdData.split("_")[1].replace(".vtk",".inp"),'w')
            if (f == "T"):
                ff.write("*BOUNDARY\n")
            elif (f == "p"):
                ff.write("*CLOAD\n")
            for id in innerIds:
                try:
                    #print ",".join([str(globalNodeIds[id]),'11','11',str(fieldData[f][interPoints[id]])])
                    if fieldData[f][interPoints[id]] != 0:
                        if (f == "T"):
                            ff.write(",".join([str(globalNodeIds[id]),'11','11',str(fieldData[f][interPoints[id]])])+"\n")
                        elif (f == "p"):
                            ff.write(",".join([str(globalNodeIds[id]),'3',str(fieldData[f][interPoints[id]])])+"\n")
                except:
                    pass
            ff.close()
        
        #writer = vtk.vtkDataSetWriter()
        #writer.SetFileName('probe.vtk')
        #writer.SetInput(probe.GetOutput())
        #writer.Write()

        """
        # WRITE INTERSECTION POINTS TO FILE
        interPointsSave = vtk.vtkPoints()
        ptcount=0
        for pnt in interPoints:
            interPointsSave.InsertPoint(ptcount, pnt)
            ptcount+=1
        innerPointData = vtk.vtkPolyData()
        innerPointData.SetPoints(interPointsSave)
        writer = vtk.vtkDataSetWriter()
        writer.SetFileName('points.vtk')
        writer.SetInput(innerPointData)
        writer.Write()
        """

        """
def pennesModeling(**kwargs):
  """
  treatment planning model 
  """
  # import needed modules
  import petsc4py, numpy, sys
  PetscOptions =  sys.argv
  PetscOptions.append("-ksp_monitor")
  PetscOptions.append("-ksp_rtol")
  PetscOptions.append("1.0e-15")
  #PetscOptions.append("-idb")
  petsc4py.init(PetscOptions)
  
  from petsc4py import PETSc
  
  # break processors into separate communicators
  petscRank = PETSc.COMM_WORLD.getRank()
  petscSize = PETSc.COMM_WORLD.Get_size()
  sys.stdout.write("petsc rank %d petsc nproc %d\n" % (petscRank, petscSize))
  
  # set shell context
  import femLibrary
  # initialize libMesh data structures
  libMeshInit = femLibrary.PyLibMeshInit(PetscOptions,PETSc.COMM_WORLD) 
  
  # the original configuration ini file should be stored
  config = kwargs['config_parser']

  # store control variables
  getpot = femLibrary.PylibMeshGetPot(PetscOptions) 

  # copy all values from the input file
  for section in config.sections():
    for name,value in  config.items(section):
      #print "%s/%s" % (section,name) , value
      getpot.SetIniValue( "%s/%s" % (section,name) , value ) 
  
  # nodeset 1 will be treated as dirichlet
  dirichletID = 1
  getpot.SetIniValue( "bc/u_dirichlet" , '%d' % dirichletID )

  # set tissue lookup tables
  k_0Table  = {"default":config.getfloat("thermal_conductivity","k_0_healthy")  ,
               "vessel" :config.getfloat("thermal_conductivity","k_0_healthy")  ,
               "grey"   :config.getfloat("thermal_conductivity","k_0_grey"   )  ,
               "white"  :config.getfloat("thermal_conductivity","k_0_white"  )  ,
               "csf"    :config.getfloat("thermal_conductivity","k_0_csf"    )  ,
               "tumor"  :config.getfloat("thermal_conductivity","k_0_tumor"  )  }
  w_0Table  = {"default":config.getfloat("perfusion","w_0_healthy")  ,
               "vessel" :config.getfloat("perfusion","w_0_healthy")  ,
               "grey"   :config.getfloat("perfusion","w_0_grey"   )  ,
               "white"  :config.getfloat("perfusion","w_0_white"  )  ,
               "csf"    :config.getfloat("perfusion","w_0_csf"    )  ,
               "tumor"  :config.getfloat("perfusion","w_0_tumor"  )  }
  mu_aTable = {"default":config.getfloat("optical","mu_a_healthy")  ,
               "vessel" :config.getfloat("optical","mu_a_healthy")  ,
               "grey"   :config.getfloat("optical","mu_a_grey"   )  ,
               "white"  :config.getfloat("optical","mu_a_white"  )  ,
               "csf"    :config.getfloat("optical","mu_a_csf"    )  ,
               "tumor"  :config.getfloat("optical","mu_a_tumor"  )  }
  mu_sTable = {"default":config.getfloat("optical","mu_s_healthy")  ,
               "vessel" :config.getfloat("optical","mu_s_healthy")  ,
               "grey"   :config.getfloat("optical","mu_s_grey"   )  ,
               "white"  :config.getfloat("optical","mu_s_white"  )  ,
               "csf"    :config.getfloat("optical","mu_s_csf"    )  ,
               "tumor"  :config.getfloat("optical","mu_s_tumor"  )  }
  labelTable= {config.get("labels","greymatter" ):"grey" , 
               config.get("labels","whitematter"):"white", 
               config.get("labels","csf"        ):"csf"  , 
               config.get("labels","tumor"      ):"tumor", 
               config.get("labels","vessel"     ):"vessel"}
  labelCount= {"default":0,
               "grey"   :0, 
               "white"  :0, 
               "csf"    :0, 
               "tumor"  :0, 
               "vessel" :0}
  # imaging params
  import vtk 
  import vtk.util.numpy_support as vtkNumPy 
  SegmentFile=config.get("exec","segment_file")
  # set the default reader based on extension
  if( SegmentFile.split(".").pop() == "vtk"):
     vtkImageReader = vtk.vtkDataSetReader
  elif( SegmentFile.split(".").pop() == "vti"):
     vtkImageReader = vtk.vtkXMLImageDataReader
  else:
     raise RuntimeError("uknown file")
  
  # get dimension info from header
  vtkSetupReader = vtkImageReader() 
  vtkSetupReader.SetFileName(SegmentFile ) 
  vtkSetupReader.Update() 
  vtkImageMask = vtkSetupReader.GetOutput()
  dimensions = vtkSetupReader.GetOutput().GetDimensions()
  numberPointsImage =  vtkSetupReader.GetOutput().GetNumberOfPoints()
  spacing_mm = vtkSetupReader.GetOutput().GetSpacing()
  origin_mm  = vtkSetupReader.GetOutput().GetOrigin()
  # convert to meters
  spacing = [dx*.001 for dx in spacing_mm]
  origin  = [x0*.001 for x0 in  origin_mm]
  
  # pass pointer to c++
  image_cells = vtkImageMask.GetPointData() 
  data_array = vtkNumPy.vtk_to_numpy( image_cells.GetArray(0) ) 
  # need to pass numpy array's w/ Fortran storage... ie painful to debug
  imageDataVec = PETSc.Vec().createWithArray(numpy.ravel(data_array,order='F'), comm=PETSc.COMM_SELF)

  # FIXME - center around quadrature in out-of-plane direction
  # FIXME - need better out of plane cooling model
  quadratureOffset  = 1./numpy.sqrt(3.0) * spacing[2]/2.0
  # expecting roi and subsample of the form:
  #     roi = [(40,210),(30,220),(6,78)]
  #     subsample = [3,3,2]
  ROI = eval(config.get('exec','roi'))
  subsample = eval(config.get('exec','subsample'))
  nelemROI  = [ (pixel[1] - pixel[0] - 1 )/sub for pixel,sub in zip(ROI,subsample)] 
  xbounds = [ origin[0]+spacing[0]*(ROI[0][0]+0.5),origin[0]+spacing[0]*(ROI[0][1]+0.5) ]
  ybounds = [ origin[1]+spacing[1]*(ROI[1][0]+0.5),origin[1]+spacing[1]*(ROI[1][1]+0.5) ]
  zbounds = [ origin[2]+spacing[2]*(ROI[2][0]+0.5),origin[2]+spacing[2]*(ROI[2][1]+0.5) ]
  if( petscRank ==0 ):
    print "#points",numberPointsImage , "dimensions ",dimensions , "spacing ",spacing , "origin ",origin 
    print "ROI",ROI , "nelemROI ",nelemROI , "bounds", xbounds, ybounds, zbounds

  #set to steady state solve 
  getpot.SetIniValue("steadystate/domain_0","true") 

  # initialize FEM Mesh
  femMesh = femLibrary.PylibMeshMesh()
  #femMesh.SetupUnStructuredGrid(kwargs['mesh_file'],0,RotationMatrix, Translation  ) 
  #femMesh.ReadFile(kwargs['mesh_file'])

  femMesh.SetupStructuredGrid(nelemROI,xbounds,ybounds,zbounds,
                              [2,2,2,2,2,2]) 
  # get output file name else set default name
  try:
    MeshOutputFile = config.get("exec","exodus_file" )
  except ConfigParser.NoOptionError:
    MeshOutputFile = "fem.e"

  # add the data structures for the Background System Solve
  # set deltat, number of time steps, power profile, and add system
  eqnSystems =  femLibrary.PylibMeshEquationSystems(femMesh,getpot)
    
  #getpot.SetIniPower(1,[[19,119],[90.0,100.0]] )
  getpot.SetIniPower(1,kwargs['powerHistory'] )
  # AddPennesSDASystem
  # AddPennesRFSystem
  # AddPennesDeltaPSystem
  pennesSystem = eval("eqnSystems.%s('StateSystem',kwargs['deltat'])" %  kwargs['physics'])
  pennesSystem.AddStorageVectors( kwargs['ntime']+1 ) 
  
  # add system for labels 
  # FIXME: need both nodal, for dirichlet bc, and element version, for parameter masks
  maskElemSystem = eqnSystems.AddExplicitSystem( "ElemImageMask" ) 
  maskElemSystem.AddConstantMonomialVariable( "maskElem" ) 

  # initialize libMesh data structures
  eqnSystems.init( ) 
  
  # print info
  eqnSystems.PrintSelf() 
  
  # setup imaging to interpolate onto FEM mesh
  femImaging = femLibrary.PytttkImaging(getpot, dimensions ,origin,spacing) 
  # Project imaging onto libMesh data structures
  femImaging.ProjectImagingToFEMMesh("ElemImageMask" ,0.0,imageDataVec,eqnSystems)  
  femImaging.ProjectImagingToFEMMesh("StateSystem"   ,0.0,imageDataVec,eqnSystems)  

  # create dirichlet nodes from this mask
  numNodes = pennesSystem.PetscFEMSystemCreateNodeSetFromMask(config.getfloat("labels","vessel"),dirichletID)
  print "# of dirichlet nodes %d" %numNodes 

  # get image label as numpy array
  imageLabel = maskElemSystem.GetSolutionVector()[...]
  #imageLabel = numpy.floor(10.0*imageLabel.copy())+1
  k_0Label  = imageLabel.copy()
  w_0Label  = imageLabel.copy()
  mu_aLabel = imageLabel.copy()
  mu_sLabel = imageLabel.copy()
  for (idpos,label) in enumerate(imageLabel):
     try:
       tissueType = labelTable["%d"%int(label)]
     except KeyError:
       tissueType = "default"
     labelCount[tissueType] = labelCount[tissueType] + 1
     k_0Label[ idpos] = k_0Table[ tissueType]
     w_0Label[ idpos] = w_0Table[ tissueType]
     mu_aLabel[idpos] = mu_aTable[tissueType]
     mu_sLabel[idpos] = mu_sTable[tissueType]
  # create array of imaging data as petsc vec
  k_0Vec  = PETSc.Vec().createWithArray(k_0Label , comm=PETSc.COMM_SELF)
  w_0Vec  = PETSc.Vec().createWithArray(w_0Label , comm=PETSc.COMM_SELF)
  mu_aVec = PETSc.Vec().createWithArray(mu_aLabel, comm=PETSc.COMM_SELF)
  mu_sVec = PETSc.Vec().createWithArray(mu_sLabel, comm=PETSc.COMM_SELF)
  # copy material properties to the system
  eqnSystems.GetSystem("k_0").SetSolutionVector( k_0Vec )
  eqnSystems.GetSystem("w_0").SetSolutionVector( w_0Vec )
  eqnSystems.GetSystem("mu_a").SetSolutionVector(mu_aVec)
  eqnSystems.GetSystem("mu_s").SetSolutionVector(mu_sVec)

  # write IC
  exodusII_IO = femLibrary.PylibMeshExodusII_IO(femMesh)
  exodusII_IO.WriteTimeStep(MeshOutputFile,eqnSystems, 1, 0.0 )  
  exodusII_IO.WriteParameterSystems(eqnSystems)  
  
  # setup IC 
  pennesSystem.PetscFEMSystemSetupInitialConditions( ) 

  # create list of laser positions
  laserPositionList = [ ((.015,.015,2*spacing[2]+quadratureOffset),
                         (.018,.018,2*spacing[2]+quadratureOffset) ),
                        ((.015,.015,2*spacing[2]+quadratureOffset),
                         (.016,.018,2*spacing[2]+quadratureOffset) ),
                        ((.015,.015,1*spacing[2]+quadratureOffset),
                         (.014,.014,1*spacing[2]+quadratureOffset) ),
                        ((.015,.015,1*spacing[2]+quadratureOffset),
                         (.015,.018,3*spacing[2]+quadratureOffset) )]
  # time stamp
  import pickle,time
  timeStamp =0 
  # set power id to turn laser on 
  pennesSystem.PetscFEMSystemUpdateTimeStep( 1 ) 
  # loop over laser position and solve steady state equations for each position
  #for (idpos,(pos0,pos1)) in enumerate(laserPositionList):
  # loop and read new laser parameters
  while(True):
    if(os.path.getmtime(fem_params['ini_filename']) > timeStamp):
      timeStamp = os.path.getmtime(fem_params['ini_filename'] ) 
      newIni = ConfigParser.SafeConfigParser({})
      newIni.read(fem_params['ini_filename'])

      laserParams = {}
      laserParams['position1'] = [newIni.getfloat("probe",varID ) for varID in ["x_0","y_0","z_0"] ]
      laserParams['position2'] = [newIni.getfloat("probe",varID ) for varID in ["x_1","y_1","z_1"] ]

      print "laser position = ", newIni.getfloat("timestep","power") , laserParams
      pennesSystem.PennesSDASystemUpdateLaserPower(newIni.getfloat("timestep","power"),1)
      pennesSystem.PennesSDASystemUpdateLaserPosition(laserParams['position1'],laserParams['position2'])
      pennesSystem.SystemSolve( ) 
      #fem.StoreTransientSystemTimeStep("StateSystem",timeID ) 
      #exodusII_IO.WriteTimeStep(MeshOutputFile ,eqnSystems, idpos+2, idpos*kwargs['deltat'])  
      exodusII_IO.WriteTimeStep(MeshOutputFile ,eqnSystems, 2, 1.0)  
      exodusII_IO.WriteParameterSystems(eqnSystems)  
      # write to txt file
      if( petscRank ==0 ):
        time.sleep(1)
        vtkExodusIIReader = vtk.vtkExodusIIReader()
        print "opening %s " % MeshOutputFile 
        vtkExodusIIReader.SetFileName( MeshOutputFile )
        vtkExodusIIReader.Update()
        ntime  = vtkExodusIIReader.GetNumberOfTimeSteps()
        variableID = "u0"
        print "ntime %d %s " % (ntime,variableID)
        vtkExodusIIReader.SetTimeStep(1) 
        vtkExodusIIReader.SetPointResultArrayStatus(variableID,1)
        vtkExodusIIReader.Update()
        curInput = None
        # multi block
        if vtkExodusIIReader.GetOutput().IsA("vtkMultiBlockDataSet"):
          iter = vtkExodusIIReader.GetOutput().NewIterator()
          iter.UnRegister(None)
          iter.InitTraversal()
          curInput = iter.GetCurrentDataObject()
        else: 
          curInput = vtkExodusIIReader.GetOutput()
        #fem_point_data= curInput.GetPointData().GetArray('u0') 
        #Soln=vtkNumPy.vtk_to_numpy(fem_point_data)
        #numpy.savetxt( "temperature.txt" ,Soln)

        # 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
        # scale back to millimeter
        # TODO verify that the data sets are registered in the native slicer coordinate system
        # TODO   segmented data MUST be read in with:
        # TODO add data -> volume -> show options -> ignore orientation
        # TODO add data -> volume -> show options -> ignore orientation
        # TODO add data -> volume -> show options -> ignore orientation
        AffineTransform = vtk.vtkTransform()
        AffineTransform.Translate([ 0.0,0.0,0.0])
        AffineTransform.RotateZ( 0.0  )
        AffineTransform.RotateY( 0.0  )
        AffineTransform.RotateX( 0.0  )
        AffineTransform.Scale([1000.,1000.,1000.])
        # scale to millimeter
        transformFilter = vtk.vtkTransformFilter()
        transformFilter.SetInput(curInput) 
        transformFilter.SetTransform(AffineTransform) 
        transformFilter.Update()

        # setup contour filter
        vtkContour = vtk.vtkContourFilter()
        vtkContour.SetInput( transformFilter.GetOutput() )
        # TODO: not sure why this works...
        # set the array to process at the temperature == u0
        vtkContour.SetInputArrayToProcess(0,0,0,0,'u0')
        contourValuesList  = eval(newIni.get('exec','contours'))
        vtkContour.SetNumberOfContours( len(contourValuesList ) )
        print "plotting array:", vtkContour.GetArrayComponent( )
        for idContour,contourValue in enumerate(contourValuesList):
           print "plotting contour:",idContour,contourValue
           vtkContour.SetValue( idContour,contourValue )
        vtkContour.Update( )

        # setup threshold filter
        vtkThreshold = vtk.vtkThreshold()
        vtkThreshold.SetInput( transformFilter.GetOutput() )
        vtkThreshold.ThresholdByLower( contourValuesList[0] )
        #vtkThreshold.SetSelectedComponent( 0 ) 
        vtkThreshold.SetComponentModeToUseAny( ) 
        vtkThreshold.Update()

        # resample onto image
        vtkResample = vtk.vtkCompositeDataProbeFilter()
        vtkResample.SetInput( vtkImageMask )
        vtkResample.SetSource( vtkThreshold.GetOutput() )
        vtkResample.Update()

        # write output
        print "writing fem.vtk "
        vtkImageWriter = vtk.vtkDataSetWriter()
        vtkImageWriter.SetFileTypeToBinary()
        vtkImageWriter.SetFileName("fem.vtk")
        vtkImageWriter.SetInput(vtkResample.GetOutput())
        vtkImageWriter.Update()

        # write stl file
        stlWriter = vtk.vtkSTLWriter()
        stlWriter.SetInput(vtkContour.GetOutput( ))
        stlWriter.SetFileName("fem.stl")
        stlWriter.SetFileTypeToBinary()
        stlWriter.Write()
        # write support file to signal full stl file is written
        #  Slicer module will wait for this file to be written
        #  before trying to open stl file to avoid incomplete reads
        with open('./fem.finish', 'w') as signalFile:
          signalFile.write("the stl file has been written\n")
 
    else:
      print "waiting on user input.."
      # echo lookup table
      if( petscRank ==0 ):
         print "lookup tables"
         print "labeled %d voxels" % len(imageLabel)
         print "labels"      , labelTable
         print "counts"      , labelCount
         print "conductivity", k_0Table  
         print "perfusion"   , w_0Table  
         print "absorption"  , mu_aTable  
         print "scattering"  , mu_sTable  
      time.sleep(2)
Esempio n. 29
0
  def buildActors(self, file_name):
    reader = vtk.vtkExodusIIReader()
    reader.SetFileName(self.file_name)
    reader.SetAllArrayStatus(vtk.vtkExodusIIReader.NODAL, 1)
    reader.SetAllArrayStatus(vtk.vtkExodusIIReader.EDGE_SET, 1)
    reader.SetAllArrayStatus(vtk.vtkExodusIIReader.SIDE_SET, 1)
    reader.SetAllArrayStatus(vtk.vtkExodusIIReader.NODE_SET, 1)
    reader.SetAllArrayStatus(vtk.vtkExodusIIReader.NODAL_TEMPORAL, 1)
    reader.UpdateInformation()
    reader.SetObjectStatus(vtk.vtkExodusIIReader.NODE_SET, 0, 1)

    num_sidesets = reader.GetNumberOfSideSetArrays()
    num_nodesets = reader.GetNumberOfNodeSetArrays()
    num_blocks = reader.GetNumberOfElementBlockArrays()

    self.sidesets = []
    self.sideset_id_to_exodus_block = {}
    self.sideset_id_to_name = {}
    self.name_to_sideset_id = {}
    for i in xrange(num_sidesets):
      sideset_id = reader.GetObjectId(vtk.vtkExodusIIReader.SIDE_SET,i)
      self.sidesets.append(sideset_id)
      self.sideset_id_to_exodus_block[sideset_id] = i
      reader.SetObjectStatus(vtk.vtkExodusIIReader.SIDE_SET, i, 1)
      name = reader.GetObjectName(vtk.vtkExodusIIReader.SIDE_SET,i).split(' ')
      if 'Unnamed' not in name:
        self.sideset_id_to_name[sideset_id] = name[0]
        self.name_to_sideset_id[name[0]] = sideset_id

    self.nodesets = []
    self.nodeset_id_to_exodus_block = {}
    self.nodeset_id_to_name = {}
    self.name_to_nodeset_id = {}
    for i in xrange(num_nodesets):
      nodeset_id = reader.GetObjectId(vtk.vtkExodusIIReader.NODE_SET,i)
      self.nodesets.append(nodeset_id)
      self.nodeset_id_to_exodus_block[nodeset_id] = i
      reader.SetObjectStatus(vtk.vtkExodusIIReader.NODE_SET, i, 1)
      name = reader.GetObjectName(vtk.vtkExodusIIReader.NODE_SET,i).split(' ')
      if 'Unnamed' not in name:
        self.nodeset_id_to_name[nodeset_id] = name[0]
        self.name_to_nodeset_id[name[0]] = nodeset_id

    self.blocks = []
    self.block_id_to_exodus_block = {}
    self.block_id_to_name = {}
    self.name_to_block_id = {}
    for i in xrange(num_blocks):
      block_id = reader.GetObjectId(vtk.vtkExodusIIReader.ELEM_BLOCK,i)
      self.blocks.append(block_id)
      self.block_id_to_exodus_block[block_id] = i
      name = reader.GetObjectName(vtk.vtkExodusIIReader.ELEM_BLOCK,i).split(' ')
      if 'Unnamed' not in name:
        self.block_id_to_name[block_id] = name[0]
        self.name_to_block_id[name[0]] = block_id

    reader.SetTimeStep(1)
    reader.Update()

    self.data = reader.GetOutput()

    for i in xrange(num_sidesets):
      actor = ExodusActor(self.renderer, self.data, ExodusMap.sideset_vtk_block, i)
      self.sideset_actors[str(self.sidesets[i])] = actor
      self.all_actors.append(actor)

      clipped_actor = ClippedActor(actor, self.plane)
      self.clipped_sideset_actors[str(self.sidesets[i])] = clipped_actor
      self.all_actors.append(clipped_actor)

    for i in xrange(num_nodesets):
      actor = ExodusActor(self.renderer, self.data, ExodusMap.nodeset_vtk_block, i)
      self.nodeset_actors[str(self.nodesets[i])] = actor
      self.all_actors.append(actor)

      clipped_actor = ClippedActor(actor, self.plane)
      self.clipped_nodeset_actors[str(self.nodesets[i])] = clipped_actor
      self.all_actors.append(clipped_actor)

    for i in xrange(num_blocks):
      actor = ExodusActor(self.renderer, self.data, ExodusMap.element_vtk_block, i)
      self.block_actors[str(self.blocks[i])] = actor
      self.all_actors.append(actor)

      clipped_actor = ClippedActor(actor, self.plane)
      self.clipped_block_actors[str(self.blocks[i])] = clipped_actor
      self.all_actors.append(clipped_actor)
Esempio n. 30
0
def convertExodusII2MSH(fname):
    import vtk
    import numpy
    import struct
    from ctypes import c_int, c_double

    useBinaryFormat = True

    def write_in_binary_format(fname):
        file = open(fname, 'wb')
        file.writelines(("$MeshFormat\n", "2.1 1 8\n"))
        file.write(struct.pack("i", 1))
        file.write("\n".encode("utf-8"))
        file.writelines(
            ("$EndMeshFormat\n", "$Nodes\n", "%d\n" % len(node_dict)))

        rnode_dict = numpy.zeros((len(node_dict), 3), dtype=float)
        for k, v in node_dict.items():
            rnode_dict[v - 1][0] = k[0]
            rnode_dict[v - 1][1] = k[1]
            rnode_dict[v - 1][2] = k[2]
        dtype = [("index", c_int), ("x", c_double, (3, ))]
        tmp = numpy.empty(len(node_dict), dtype=dtype)
        tmp["index"] = 1 + numpy.arange(len(node_dict))
        tmp["x"] = numpy.asarray(rnode_dict)
        file.write(tmp.tostring())

        file.write("\n".encode("utf-8"))
        file.write("$EndNodes\n")
        file.write("$Elements\n")
        file.write("%d\n" % (len(ele_face_dict) + len(ele_vol_dict)))
        # header
        file.write(struct.pack("i", 2))
        file.write(struct.pack(
            "i", len(ele_face_dict)))  # or maybe +len(ele_face_dict)
        file.write(struct.pack("i", 2))
        for k, ele in enumerate(ele_face_dict):
            file.write(
                struct.pack("iiiiii", k + 1, ele[0], ele[0], ele[1], ele[2],
                            ele[3]))

        file.write(struct.pack("i", 4))
        file.write(struct.pack(
            "i", len(ele_vol_dict)))  # or maybe +len(ele_face_dict)
        file.write(struct.pack("i", 2))
        for k, ele in enumerate(ele_vol_dict):
            file.write(
                struct.pack("iiiiiii", k + 1 + len(ele_face_dict), ele[0],
                            ele[0], ele[1], ele[2], ele[3], ele[4]))
        file.write("\n".encode("utf-8"))
        file.write("$EndElements\n")
        file.close()

    def write_in_ASCII_format(fname):
        file = open(fname, 'w')

        file.writelines(("$MeshFormat\n", "2.2 0 8\n", "$EndMeshFormat\n",
                         "$Nodes\n", "%d\n" % len(node_dict)))
        for k in range(len(node_dict)):
            p = rnode_dict[k + 1]
            file.write("%d %f %f %f\n" % (k + 1, p[0], p[1], p[2]))
        file.write("$EndNodes\n")
        file.write("$Elements\n")
        file.write("%d\n" % (len(ele_face_dict) + len(ele_vol_dict)))
        for k, ele in enumerate(ele_face_dict):
            file.write("%d 2 2 %d %d %d %d %d\n" %
                       (k + 1, ele[0], ele[0], ele[1], ele[2], ele[3]))
        for k, ele in enumerate(ele_vol_dict):
            file.write("%d 4 2 %d %d %d %d %d %d\n" %
                       (k + 1, ele[0], ele[0], ele[1], ele[2], ele[3], ele[4]))
        file.write("$EndElements\n")
        file.close()

    r = vtk.vtkExodusIIReader()
    if (fname[-2:] == '-h'):
        print 'This script converts a general exodus ii file into ASCII .msh file format. It requires the vtk python library to be installed on the system.'
        print 'The input should be the name of the file, and the output is that same name .msh. Example: python exodus2msh.py test.e'
        print 'To convert to .msh binary format use the option /geometry/create_binary_msh in Diamond.'
        exit()
    elif (fname[-2:] != '.e'):
        fname += '.e'
    print 'Converting the input exodus ii file into .msh format...'
    r.SetFileName(fname)
    r.UpdateInformation()
    r.GenerateGlobalNodeIdArrayOn()
    r.GenerateGlobalElementIdArrayOn()
    r.GenerateObjectIdCellArrayOn()
    #r.ExodusModelMetadataOn()
    #r.PackExodusModelOntoOutputOn()
    for i in range(r.GetNumberOfSideSetArrays()):
        name = r.GetSideSetArrayName(i)
        r.SetSideSetArrayStatus(name, 1)
    r.Update()

    data = r.GetOutput()

    node_dict = {}
    ele_face_dict = []
    ele_vol_dict = []

    n = 1

    def f():
        global n
        a = n
        n = n + 1
        return a

    for j in range(data.GetBlock(4).GetNumberOfBlocks()):
        ug = data.GetBlock(4).GetBlock(j)
        sidesetID = r.GetObjectId(3, j)
        for k in range(ug.GetNumberOfPoints()):
            lnodes = {}
            p = ug.GetPoint(k)
            N = node_dict.get(p)
            if N == None:
                node_dict[p] = n
                n += 1
            lnodes[k] = node_dict.get(p)
        for k in range(ug.GetNumberOfCells()):
            cp = ug.GetCell(k).GetPoints()
            ele_face_dict.append(
                (sidesetID, node_dict[cp.GetPoint(0)],
                 node_dict[cp.GetPoint(1)], node_dict[cp.GetPoint(2)]))

    for j in range(data.GetBlock(0).GetNumberOfBlocks()):
        ug = data.GetBlock(0).GetBlock(j)
        blockID = r.GetObjectId(1, j)
        for k in range(ug.GetNumberOfPoints()):
            lnodes = {}
            p = ug.GetPoint(k)
            N = node_dict.get(p)
            if N == None:
                node_dict[p] = n
                n += 1
            lnodes[k] = node_dict.get(p)
        for k in range(ug.GetNumberOfCells()):
            cp = ug.GetCell(k).GetPoints()
            ele_vol_dict.append(
                (blockID, node_dict[cp.GetPoint(0)], node_dict[cp.GetPoint(1)],
                 node_dict[cp.GetPoint(2)], node_dict[cp.GetPoint(3)]))

    fname = fname[:-2] + '.msh'

    if useBinaryFormat:
        write_in_binary_format(fname)
    else:
        write_in_ASCII_format(fname)

    print '...file created => ' + fname
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()
Esempio n. 32
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 AssembleStatistics(data_dir):
  """
  collect all statistics into one exodus file
  """
  # post process stats on FEM mesh
  # import petsc and numpy
  import vtk, numpy
  import vtk.util.numpy_support as vtkNumPy 

  # initialize FEM Mesh
  pkl_file = open('%s/CaseInfo.pkl' % ".", 'rb')
  fem_params = pickle.load(pkl_file)
  pkl_file.close()
   
  vtkExodusIIReader = vtk.vtkExodusIIReader()
  print "opening %s " % fem_params['mesh_file'] 
  vtkExodusIIReader.SetFileName( fem_params['mesh_file'] )
  #vtkExodusIIReader.SetFileName( "/data/fuentes/utsa/vasculature_july10/vessel_0/realization.1//fem_data.0001.e")
  vtkExodusIIReader.ExodusModelMetadataOn ()
  vtkExodusIIReader.Update()
  exodusObject = vtkExodusIIReader.GetOutput()
  responseLevelVarList = fem_params['responseLevelVarList'] 
  probabilityLevelList = fem_params['probabilityLevelList'] 
  reliabilityLevelList = fem_params['reliabilityLevelList'] 

  # loop over time steps and import data
  # vtkTemporalDataSet = vtk.vtkTemporalDataSet()
  # multiBlockData = {}
  #for timeID in [69]:
  #TODO how can we assemble all time steps at once ? 
  #for timeID in range(0,fem_params['ntime']+1):
  for timeID in [int(data_dir.split(".").pop())]:
    for variable,responseList in responseLevelVarList:
      #(variable,responseList) = responseLevelVarList[0]
      basePath = "%s/%s" % (data_dir,variable)
      # mean
      meanFile=open("%s/meanFile.txt" % (basePath) ,"r")
      meandataList = [float(line.strip()) for line in meanFile]
      meanFile.close()
      # std dev
      stdFile=open("%s/stddFile.txt" % (basePath),"r")
      stdddataList = [float(line.strip()) for line in stdFile]
      stdFile.close()
      # skewness
      skewFile=open("%s/skewFile.txt" % (basePath),"r")
      skewdataList = [float(line.strip()) for line in skewFile]
      skewFile.close()
      # kurtosis
      kurtFile=open("%s/kurtFile.txt" % (basePath),"r")
      kurtdataList = [float(line.strip()) for line in kurtFile]
      kurtFile.close()
      # response data
      responsedataList = []
      for iii,response in enumerate(responseList):
        responseFile=open("%s/response.%d.txt" %(basePath,iii),"r")
        singleresponseList = [float(line.strip()) for line in responseFile]
        responseFile.close()
        responsedataList.append(singleresponseList)
      # probability data
      probabilitydataList = []
      for iii,probability in enumerate(probabilityLevelList):
        probFile=open("%s/probability.%d.txt" %(basePath,iii),"r")
        probList = [float(line.strip()) for line in probFile]
        probFile.close()
        probabilitydataList.append(probList)
      # reliability data
      reliabilitydataList = []
      for iii,reliability in enumerate(reliabilityLevelList):
        reliabFile=open("%s/reliability.%d.txt" %(basePath,iii),"r")
        reliabList = [float(line.strip()) for line in reliabFile]
        reliabFile.close()
        reliabilitydataList.append(reliabList) 
      # multi block
      if exodusObject.IsA("vtkMultiBlockDataSet"):
        iter = exodusObject.NewIterator()
        iter.UnRegister(None)
        iter.InitTraversal()
        # iter.GoToNextItem();
        # iter.GoToNextItem();
        metadata = exodusObject.GetMetaData(iter)
        # initialize list for storage
        listSliceInit = 0
        # loop over blocks...
        while not iter.IsDoneWithTraversal():
          curInput = iter.GetCurrentDataObject()
          curNumberPoints = curInput.GetNumberOfPoints()
          fem_point_data= curInput.GetPointData() 
          DeepCopy = 1
          #print timeID,listSliceInit,curNumberPoints 
          vtkMean= vtkNumPy.numpy_to_vtk( meandataList[listSliceInit:listSliceInit+curNumberPoints ] , DeepCopy) 
          vtkStdD= vtkNumPy.numpy_to_vtk( stdddataList[listSliceInit:listSliceInit+curNumberPoints ] , DeepCopy) 
          vtkSkew= vtkNumPy.numpy_to_vtk( skewdataList[listSliceInit:listSliceInit+curNumberPoints ] , DeepCopy) 
          vtkKurt= vtkNumPy.numpy_to_vtk( kurtdataList[listSliceInit:listSliceInit+curNumberPoints ] , DeepCopy) 
          vtkMean.SetName(       "Var%sMean"        % variable  )
          vtkStdD.SetName(       "Var%sStdDev"      % variable  )
          vtkSkew.SetName(       "Var%sSkew"        % variable  )
          vtkKurt.SetName(       "Var%sKurt"        % variable  )
          fem_point_data.AddArray( vtkMean )
          fem_point_data.AddArray( vtkStdD )
          fem_point_data.AddArray( vtkSkew )
          fem_point_data.AddArray( vtkKurt )
          fem_point_data.Update()
          for iii,response in enumerate(responsedataList):
            vtkResponse= vtkNumPy.numpy_to_vtk( response[listSliceInit:listSliceInit+curNumberPoints ] , DeepCopy) 
            vtkResponse.SetName(   "Var%sresponse%d" %(variable,iii) )
            fem_point_data.AddArray( vtkResponse )
            fem_point_data.Update()
          for iii,probability in enumerate(probabilitydataList):
            vtkProb= vtkNumPy.numpy_to_vtk( probability[listSliceInit:listSliceInit+curNumberPoints ] , DeepCopy) 
            vtkProb.SetName(   "Var%sprobability%d" %(variable,iii) )
            fem_point_data.AddArray( vtkProb )
            fem_point_data.Update()
          for iii,reliability in enumerate(reliabilitydataList):
            vtkReliab= vtkNumPy.numpy_to_vtk( reliability[listSliceInit:listSliceInit+curNumberPoints ] , DeepCopy) 
            vtkReliab.SetName(   "Var%sreliability%d" %(variable,iii) )
            fem_point_data.AddArray( vtkReliab )
            fem_point_data.Update()
          #vtkSoln = vtkNumPy.numpy_to_vtk( listSliceInit * numpy.ones(curNumberPoints ), DeepCopy ) 
          #vtkSoln.SetName("%d" % listSliceInit) 
          curInput.Update()
          # multiBlockData['%d' % timeID] = vtk.vtkUnstructuredGrid()
          # multiBlockData['%d' % timeID].DeepCopy( curInput )
          listSliceInit = listSliceInit + curNumberPoints 
          iter.GoToNextItem();
      # single block
      else:
        raise RuntimeError("not implemented yet... " )
      vtkExodusIIWriter = vtk.vtkExodusIIWriter()
      vtkExodusIIWriter.SetFileName( '%s/fem_stats.%04d.e' % (".",timeID) )
      vtkExodusIIWriter.SetInput( exodusObject)
      vtkExodusIIWriter.Update()
Esempio n. 34
0
def read(filetype, filename):
    import vtk
    from vtk.util import numpy_support

    def _read_data(data):
        '''Extract numpy arrays from a VTK data set.
        '''
        # Go through all arrays, fetch data.
        out = {}
        for k in range(data.GetNumberOfArrays()):
            array = data.GetArray(k)
            if array:
                array_name = array.GetName()
                out[array_name] = vtk.util.numpy_support.vtk_to_numpy(array)

        return out

    def _read_cells(vtk_mesh):
        data = vtk.util.numpy_support.vtk_to_numpy(
                vtk_mesh.GetCells().GetData()
                )
        offsets = vtk.util.numpy_support.vtk_to_numpy(
                vtk_mesh.GetCellLocationsArray()
                )
        types = vtk.util.numpy_support.vtk_to_numpy(
                vtk_mesh.GetCellTypesArray()
                )

        vtk_to_meshio_type = {
            vtk.VTK_VERTEX: 'vertex',
            vtk.VTK_LINE: 'line',
            vtk.VTK_TRIANGLE: 'triangle',
            vtk.VTK_QUAD: 'quad',
            vtk.VTK_TETRA: 'tetra',
            vtk.VTK_HEXAHEDRON: 'hexahedron',
            vtk.VTK_WEDGE: 'wedge',
            vtk.VTK_PYRAMID: 'pyramid'
            }

        # `data` is a one-dimensional vector with
        # (num_points0, p0, p1, ... ,pk, numpoints1, p10, p11, ..., p1k, ...
        # Translate it into the cells dictionary.
        cells = {}
        for vtk_type, meshio_type in vtk_to_meshio_type.items():
            # Get all offsets for vtk_type
            os = offsets[numpy.argwhere(types == vtk_type).transpose()[0]]
            num_cells = len(os)
            if num_cells > 0:
                num_pts = data[os[0]]
                # instantiate the array
                arr = numpy.empty((num_cells, num_pts), dtype=int)
                # sort the num_pts entries after the offsets into the columns
                # of arr
                for k in range(num_pts):
                    arr[:, k] = data[os+k+1]
                cells[meshio_type] = arr

        return cells

    if filetype == 'vtk':
        reader = vtk.vtkUnstructuredGridReader()
        reader.SetFileName(filename)
        reader.Update()
        vtk_mesh = reader.GetOutput()
    elif filetype == 'vtu':
        reader = vtk.vtkXMLUnstructuredGridReader()
        reader.SetFileName(filename)
        reader.Update()
        vtk_mesh = reader.GetOutput()
    elif filetype == 'xdmf':
        reader = vtk.vtkXdmfReader()
        reader.SetFileName(filename)
        reader.Update()
        vtk_mesh = reader.GetOutputDataObject(0)
    elif filetype == 'exodus':
        reader = vtk.vtkExodusIIReader()
        reader.SetFileName(filename)
        vtk_mesh = _read_exodusii_mesh(reader)
    else:
        raise RuntimeError('Unknown file type \'%s\'.' % filename)

    # Explicitly extract points, cells, point data, field data
    points = vtk.util.numpy_support.vtk_to_numpy(
            vtk_mesh.GetPoints().GetData()
            )
    cells = _read_cells(vtk_mesh)
    point_data = _read_data(vtk_mesh.GetPointData())
    cell_data = _read_data(vtk_mesh.GetCellData())
    field_data = _read_data(vtk_mesh.GetFieldData())

    return points, cells, point_data, cell_data, field_data
Esempio n. 35
0
def read(filetype, filename):
    import vtk
    from vtk.util import numpy_support

    def _read_data(data):
        '''Extract numpy arrays from a VTK data set.
        '''
        # Go through all arrays, fetch data.
        out = {}
        for k in range(data.GetNumberOfArrays()):
            array = data.GetArray(k)
            if array:
                array_name = array.GetName()
                out[array_name] = vtk.util.numpy_support.vtk_to_numpy(array)

        return out

    def _read_cells(vtk_mesh):
        data = vtk.util.numpy_support.vtk_to_numpy(
            vtk_mesh.GetCells().GetData())
        offsets = vtk.util.numpy_support.vtk_to_numpy(
            vtk_mesh.GetCellLocationsArray())
        types = vtk.util.numpy_support.vtk_to_numpy(
            vtk_mesh.GetCellTypesArray())

        vtk_to_meshio_type = {
            vtk.VTK_VERTEX: 'vertex',
            vtk.VTK_LINE: 'line',
            vtk.VTK_TRIANGLE: 'triangle',
            vtk.VTK_QUAD: 'quad',
            vtk.VTK_TETRA: 'tetra',
            vtk.VTK_HEXAHEDRON: 'hexahedron',
            vtk.VTK_WEDGE: 'wedge',
            vtk.VTK_PYRAMID: 'pyramid'
        }

        # `data` is a one-dimensional vector with
        # (num_points0, p0, p1, ... ,pk, numpoints1, p10, p11, ..., p1k, ...
        # Translate it into the cells dictionary.
        cells = {}
        for vtk_type, meshio_type in vtk_to_meshio_type.items():
            # Get all offsets for vtk_type
            os = offsets[numpy.argwhere(types == vtk_type).transpose()[0]]
            num_cells = len(os)
            if num_cells > 0:
                num_pts = data[os[0]]
                # instantiate the array
                arr = numpy.empty((num_cells, num_pts), dtype=int)
                # sort the num_pts entries after the offsets into the columns
                # of arr
                for k in range(num_pts):
                    arr[:, k] = data[os + k + 1]
                cells[meshio_type] = arr

        return cells

    if filetype == 'vtk':
        reader = vtk.vtkUnstructuredGridReader()
        reader.SetFileName(filename)
        reader.Update()
        vtk_mesh = reader.GetOutput()
    elif filetype == 'vtu':
        reader = vtk.vtkXMLUnstructuredGridReader()
        reader.SetFileName(filename)
        reader.Update()
        vtk_mesh = reader.GetOutput()
    elif filetype == 'xdmf':
        reader = vtk.vtkXdmfReader()
        reader.SetFileName(filename)
        reader.Update()
        vtk_mesh = reader.GetOutputDataObject(0)
    elif filetype == 'exodus':
        reader = vtk.vtkExodusIIReader()
        reader.SetFileName(filename)
        vtk_mesh = _read_exodusii_mesh(reader)
    else:
        raise RuntimeError('Unknown file type \'%s\'.' % filename)

    # Explicitly extract points, cells, point data, field data
    points = vtk.util.numpy_support.vtk_to_numpy(
        vtk_mesh.GetPoints().GetData())
    cells = _read_cells(vtk_mesh)
    point_data = _read_data(vtk_mesh.GetPointData())
    cell_data = _read_data(vtk_mesh.GetCellData())
    field_data = _read_data(vtk_mesh.GetFieldData())

    return points, cells, point_data, cell_data, field_data
templateImage = vtkReader.GetOutput()
dimensions = templateImage.GetDimensions()
spacing = templateImage.GetSpacing()
origin = templateImage.GetOrigin()

# loop over time steps and solve
for timeID in range(1, ntime):
    print "time step = ", timeID
    fem.UpdateTransientSystemTimeStep("StateSystem", timeID)
    fem.SystemSolve("StateSystem")
    #fem.StoreTransientSystemTimeStep("StateSystem",timeID )
    fem.WriteTimeStep("fem_data.e", timeID + 1, timeID * deltat)

    # Interpolate FEM onto imaging data structures
    if (petscRank == -1):
        vtkExodusIIReader = vtk.vtkExodusIIReader()
        vtkExodusIIReader.SetFileName("fem_data.e")
        vtkExodusIIReader.SetPointResultArrayStatus("u0", 1)
        vtkExodusIIReader.SetTimeStep(timeID - 1)
        vtkExodusIIReader.Update()

        # reuse ShiftScale Geometry
        vtkResample = vtk.vtkCompositeDataProbeFilter()
        vtkResample.SetInput(templateImage)
        vtkResample.SetSource(vtkExodusIIReader.GetOutput())
        vtkResample.Update()

        # FIXME this is prob the longest round about way possible...
        # FIXME convert to binary first then read back in a single component
        # For VTK to be able to use the data, it must be stored as a VTK-image. This can be done by the vtkImageImport-class which
        # imports raw data and stores it.
def deltapModeling(**kwargs):
  """
  treatment planning model 
  """
  # import petsc and numpy
  import petsc4py, numpy
  # init petsc
  PetscOptions =  sys.argv
  PetscOptions.append("-ksp_monitor")
  PetscOptions.append("-ksp_rtol")
  PetscOptions.append("1.0e-15")
  #PetscOptions.append("-help")
  #PetscOptions.append("-idb")
  petsc4py.init(PetscOptions)
  #
  # break processors into separate communicators
  from petsc4py import PETSc
  petscRank = PETSc.COMM_WORLD.getRank()
  petscSize = PETSc.COMM_WORLD.Get_size()
  sys.stdout.write("petsc rank %d petsc nproc %d\n" % (petscRank, petscSize))

  # set shell context
  # TODO import vtk should be called after femLibrary ???? 
  # FIXME WHY IS THIS????
  import femLibrary
  # initialize libMesh data structures
  libMeshInit = femLibrary.PyLibMeshInit(PetscOptions,PETSc.COMM_WORLD) 
  
  # store control variables
  getpot = femLibrary.PylibMeshGetPot(PetscOptions) 
  # from Duck table 2.11 pig dermis 
  getpot.SetIniValue( "material/specific_heat","3280.0" ) 
  # set ambient temperature 
  getpot.SetIniValue( "initial_condition/u_init","0.0" ) 
  # from Duck 2.7 Rat tumor measured in vivo
  getpot.SetIniValue( "thermal_conductivity/k_0_tumor","0.32" ) 
  getpot.SetIniValue( "thermal_conductivity/k_0_healthy",kwargs['cv']['k_0_healthy'] ) 
  # water properties at http://www.d-a-instruments.com/light_absorption.html
  getpot.SetIniValue( "optical/mu_a_healthy", kwargs['cv']['mu_a_healthy'] ) 
  # FIXME large mu_s (> 30) in agar causing negative fluence to satisfy BC 
  getpot.SetIniValue( "optical/mu_s_healthy",
              kwargs['cv']['mu_s_healthy'] ) 
  # from AE paper
  #http://scitation.aip.org/journals/doc/MPHYA6-ft/vol_36/iss_4/1351_1.html#F3

  #For SPIOs
  #getpot.SetIniValue( "optical/guass_radius","0.0035" ) 
  #For NR/NS
  getpot.SetIniValue( "optical/guass_radius",".003" )

  # cauchy BC
  getpot.SetIniValue( "bc/u_infty","0.0" )
  getpot.SetIniValue( "bc/newton_coeff","1.0e5" )

  # 1-300
  getpot.SetIniValue( "optical/mu_a_tumor",
              kwargs['cv']['mu_a_tumor'] ) 
  # 1-300
  getpot.SetIniValue( "optical/mu_s_tumor",
              kwargs['cv']['mu_s_tumor'] ) 
  #getpot.SetIniValue( "optical/mu_a_tumor","71.0" ) 
  #getpot.SetIniValue( "optical/mu_s_tumor","89.0" ) 
  # .9  - .99
  getpot.SetIniValue( "optical/anfact",kwargs['cv']['anfact'] ) 
  #agar length

  #for SPIOs
  #getpot.SetIniValue( "optical/agar_length","0.0206" ) 
  #for NR/NS
  getpot.SetIniValue( "optical/agar_length","0.023" )

  getpot.SetIniValue("optical/refractive_index","1.0")
  #
  #  given the original orientation as two points along the centerline z = x2 -x1
  #     the transformed orienteation would be \hat{z} = A x2 + b - A x1 - b = A z
  #  ie transformation w/o translation which is exactly w/ vtk has implemented w/ TransformVector
  #  TransformVector = TransformPoint - the transation
  #Setup Affine Transformation for registration
  RotationMatrix = [[1.,0.,0.],
                    [0.,1.,0.],
                    [0.,0.,1.]]
  Translation =     [0.,0.,0.]
  # original coordinate system laser input
  # For SPIOs 67_11
  #laserTip         =  [0.,-.000625,.035] 
  # For SPIOs 67_10
  #laserTip         =  [0.,-.0001562,.035]
  # For SPIOs 335_11
  #laserTip         =  [0.,-.0014062,.035]
  # For NR		
  #laserTip         =  [0.,.0002,.035]
  # For NS
  laserTip         =  [0.00001,.000001,.000001]

  laserOrientation =  [0.0,0.,-1.0] 
  
  import vtk
  import vtk.util.numpy_support as vtkNumPy 
  # 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

  # For NS
  #AffineTransform.Translate([ .01320,-.0037,0.00000010])
  #AffineTransform.Translate([ .005,-.0035,0.0])
  AffineTransform.Translate([-.006,-.0022,0.0])
  AffineTransform.RotateZ( 0.0 )
  AffineTransform.RotateY( -90.0 )
  AffineTransform.RotateX( 0.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 )

  # set laser orientation values
  getpot.SetIniValue( "probe/x_0","%f" % laserTip[0]) 
  getpot.SetIniValue( "probe/y_0","%f" % laserTip[1]) 
  getpot.SetIniValue( "probe/z_0","%f" % laserTip[2]) 
  getpot.SetIniValue( "probe/x_orientation","%f" % laserOrientation[0] ) 
  getpot.SetIniValue( "probe/y_orientation","%f" % laserOrientation[1] ) 
  getpot.SetIniValue( "probe/z_orientation","%f" % laserOrientation[2] ) 
  
  # initialize FEM Mesh
  femMesh = femLibrary.PylibMeshMesh()
  # must setup Ini File first
  #For SPIOs
  #femMesh.SetupUnStructuredGrid( "/work/01741/cmaclell/data/mdacc/deltap_phantom_oct10/phantomMeshFullTess.e",0,RotationMatrix, Translation  ) 
  #For NS/NR
  RotationMatrix = [[1,0,0],
                    [0,1,0],
                    [0,0,1]]
  Translation =     [.0000001,.00000001,.000001]
  #
  femMesh.SetupUnStructuredGrid( "./sphereMesh.e",0,RotationMatrix, Translation  )
  #femMesh.SetupUnStructuredGrid( "phantomMesh.e",0,RotationMatrix, Translation  )

  MeshOutputFile = "fem_data.%04d.e" % kwargs['fileID'] 
  #femMes.SetupStructuredGrid( (10,10,4) ,[0.0,1.0],[0.0,2.0],[0.0,1.0]) 
  
  # add the data structures for the background system solve
  # set deltat, number of time steps, power profile, and add system
  nsubstep = 1
  #for SPIOs
  #acquisitionTime = 4.9305
  #for NS/NR
  acquisitionTime = 5.09
  deltat = acquisitionTime / nsubstep
  ntime  = 60 
  eqnSystems =  femLibrary.PylibMeshEquationSystems(femMesh,getpot)
  #For SPIOs
  #getpot.SetIniPower(nsubstep,  [ [1,6,30,ntime],[1.0,0.0,4.5,0.0] ])
  #For NS/NR
  getpot.SetIniPower(nsubstep,  [ [1,6,42,ntime],[1.0,0.0,1.13,0.0] ])
  deltapSystem = eqnSystems.AddPennesDeltaPSystem("StateSystem",deltat) 
  deltapSystem.AddStorageVectors(ntime)

  # hold imaging
  mrtiSystem = eqnSystems.AddExplicitSystem( "MRTI" ) 
  mrtiSystem.AddFirstLagrangeVariable( "u0*" ) 
  mrtiSystem.AddStorageVectors(ntime)
  maskSystem = eqnSystems.AddExplicitSystem( "ImageMask" ) 
  maskSystem.AddFirstLagrangeVariable( "mask" ) 
  
  # initialize libMesh data structures
  eqnSystems.init( ) 
  
  # print info
  eqnSystems.PrintSelf() 
  
  # write IC
  exodusII_IO = femLibrary.PylibMeshExodusII_IO(femMesh)
  exodusII_IO.WriteTimeStep(MeshOutputFile,eqnSystems, 1, 0.0 )  
  
  # read imaging data geometry that will be used to project FEM data onto
  #For 67_11
  #vtkReader.SetFileName('/work/01741/cmaclell/data/mdacc/deltap_phantom_oct10/spio/spioVTK/67_11/tmap_67_11.0000.vtk')
  #For 67_10
  #vtkReader.SetFileName('/work/01741/cmaclell/data/mdacc/deltap_phantom_oct10/spio/spioVTK/67_10/tmap_67_10.0000.vtk')
  #For 335_11 
  #vtkReader.SetFileName('/work/01741/cmaclell/data/mdacc/deltap_phantom_oct10/spio/spioVTK/335_11/tmap_335_11.0000.vtk')
  #For NS
  #vtkReader.SetFileName('/work/01741/cmaclell/data/mdacc/deltap_phantom_oct10/nrtmapsVTK/S695/S695.0000.vtk') 
  #For NR
  imageFileNameTemplate = '/work/01741/cmaclell/data/mdacc/NanoMouseJune12/matlab_VTK/control_1_tmap.%04d.vtk'
  imageFileNameTemplate = '/FUS4/data2/CJM/SPIO_mice/matlab_VTK/control_1_tmap.%04d.vtk'
  #imageFileNameTemplate = "/share/work/fuentes/deltap_phantom_oct10/nrtmapsVTK/R695/R695.%04d.vtk"
  #imageFileNameTemplate = "/data/fuentes/mdacc/deltap_phantom_oct10/nrtmapsVTK/R695/R695.%04d.vtk"

  #vtkReader = vtk.vtkXMLImageDataReader() 
  vtkReader = vtk.vtkDataSetReader() 
  vtkReader.SetFileName( imageFileNameTemplate % 0 )
  vtkReader.Update()
  templateImage = vtkReader.GetOutput()
  dimensions = templateImage.GetDimensions()
  spacing = templateImage.GetSpacing()
  origin  = templateImage.GetOrigin()
  print spacing, origin, dimensions
  femImaging = femLibrary.PytttkImaging(getpot, dimensions ,origin,spacing) 
  
  ObjectiveFunction = 0.0
  # loop over time steps and solve
  for timeID in range(1,ntime*nsubstep):
  #for timeID in range(1,10):
     # project imaging onto fem mesh
     vtkImageReader = vtk.vtkDataSetReader() 
     vtkImageReader.SetFileName( imageFileNameTemplate % 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)
     femImaging.ProjectImagingToFEMMesh("MRTI",0.0,v1,eqnSystems)  
     mrtiSystem.StoreSystemTimeStep(timeID ) 
  
     # create image mask 
     #  The = operator for numpy arrays just copies by reference
     #   .copy() provides a deep copy (ie physical memory copy)
     image_mask = data_array.copy().reshape(dimensions,order='F')
     # Set all image pixels to large value
     largeValue = 1.e6
     image_mask[:,:] = 1 
     # RMS error will be computed within this ROI/VOI imagemask[xcoords/column,ycoords/row]
     #image_mask[93:153,52:112] = 1.0
     #image_mask[98:158,46:106] = 1.0
     v2 = PETSc.Vec().createWithArray(image_mask, comm=PETSc.COMM_SELF)
     femImaging.ProjectImagingToFEMMesh("ImageMask",largeValue,v2,eqnSystems)  
     #print mrti_array
     #print type(mrti_array)

     print "time step = " ,timeID
     eqnSystems.UpdatePetscFEMSystemTimeStep("StateSystem",timeID ) 
     deltapSystem.SystemSolve()
     #eqnSystems.StoreTransientSystemTimeStep("StateSystem",timeID ) 
  
     # accumulate objective function
     # 
     # qoi  = ( (FEM - MRTI) / ImageMask)^2
     # 
     qoi = femLibrary.WeightedL2Norm( deltapSystem,"u0",
                                      mrtiSystem,"u0*",
                                      maskSystem,"mask" ) 
     ObjectiveFunction =( ObjectiveFunction + qoi) 
    
     # control write output
     writeControl = True
     if ( timeID%nsubstep == 0 and writeControl ):
       # write exodus file
       exodusII_IO.WriteTimeStep(MeshOutputFile,eqnSystems, timeID+1, timeID*deltat )  
       # Interpolate FEM onto imaging data structures
       if (vtk != None):
         vtkExodusIIReader = vtk.vtkExodusIIReader()
         vtkExodusIIReader.SetFileName(MeshOutputFile )
         vtkExodusIIReader.SetPointResultArrayStatus("u0",1)
         vtkExodusIIReader.SetTimeStep(timeID-1) 
         vtkExodusIIReader.Update()
         # reflect
         vtkReflect = vtk.vtkReflectionFilter()
         vtkReflect.SetPlaneToYMax()
         vtkReflect.SetInput( vtkExodusIIReader.GetOutput() )
         vtkReflect.Update()
         # reuse ShiftScale Geometry
         vtkResample = vtk.vtkCompositeDataProbeFilter()
         vtkResample.SetInput( vtkImageReader.GetOutput() )
         vtkResample.SetSource( vtkReflect.GetOutput() ) 
         vtkResample.Update()
         fem_point_data= vtkResample.GetOutput().GetPointData() 
         fem_array = vtkNumPy.vtk_to_numpy(fem_point_data.GetArray('u0')) 
         #print fem_array 
         #print type(fem_array )
       # only rank 0 should write
       #if ( petscRank == 0 ):
       #   print "writing ", timeID
       #   vtkTemperatureWriter = vtk.vtkDataSetWriter()
       #   vtkTemperatureWriter.SetFileTypeToBinary()
       #   vtkTemperatureWriter.SetFileName("invspio_67_11.%04d.vtk" % timeID )
       #   vtkTemperatureWriter.SetInput(vtkResample.GetOutput())
       #   vtkTemperatureWriter.Update()
  print 'Objective Fn'
  print ObjectiveFunction
  retval = dict([])
  retval['fns'] = [ObjectiveFunction *10000000.]
  retval['rank'] = petscRank 
  return(retval)
Esempio n. 38
0
    def buildActors(self, file_name):
        reader = vtk.vtkExodusIIReader()
        reader.SetFileName(self.file_name)
        reader.SetAllArrayStatus(vtk.vtkExodusIIReader.NODAL, 1)
        reader.SetAllArrayStatus(vtk.vtkExodusIIReader.EDGE_SET, 1)
        reader.SetAllArrayStatus(vtk.vtkExodusIIReader.SIDE_SET, 1)
        reader.SetAllArrayStatus(vtk.vtkExodusIIReader.NODE_SET, 1)
        reader.SetAllArrayStatus(vtk.vtkExodusIIReader.NODAL_TEMPORAL, 1)
        reader.UpdateInformation()
        reader.SetObjectStatus(vtk.vtkExodusIIReader.NODE_SET, 0, 1)

        num_sidesets = reader.GetNumberOfSideSetArrays()
        num_nodesets = reader.GetNumberOfNodeSetArrays()
        num_blocks = reader.GetNumberOfElementBlockArrays()

        self.sidesets = []
        self.sideset_id_to_exodus_block = {}
        self.sideset_id_to_name = {}
        self.name_to_sideset_id = {}
        for i in xrange(num_sidesets):
            sideset_id = reader.GetObjectId(vtk.vtkExodusIIReader.SIDE_SET, i)
            self.sidesets.append(sideset_id)
            self.sideset_id_to_exodus_block[sideset_id] = i
            reader.SetObjectStatus(vtk.vtkExodusIIReader.SIDE_SET, i, 1)
            name = reader.GetObjectName(vtk.vtkExodusIIReader.SIDE_SET,
                                        i).split(' ')
            if 'Unnamed' not in name:
                self.sideset_id_to_name[sideset_id] = name[0]
                self.name_to_sideset_id[name[0]] = sideset_id

        self.nodesets = []
        self.nodeset_id_to_exodus_block = {}
        self.nodeset_id_to_name = {}
        self.name_to_nodeset_id = {}
        for i in xrange(num_nodesets):
            nodeset_id = reader.GetObjectId(vtk.vtkExodusIIReader.NODE_SET, i)
            self.nodesets.append(nodeset_id)
            self.nodeset_id_to_exodus_block[nodeset_id] = i
            reader.SetObjectStatus(vtk.vtkExodusIIReader.NODE_SET, i, 1)
            name = reader.GetObjectName(vtk.vtkExodusIIReader.NODE_SET,
                                        i).split(' ')
            if 'Unnamed' not in name:
                self.nodeset_id_to_name[nodeset_id] = name[0]
                self.name_to_nodeset_id[name[0]] = nodeset_id

        self.blocks = []
        self.block_id_to_exodus_block = {}
        self.block_id_to_name = {}
        self.name_to_block_id = {}
        for i in xrange(num_blocks):
            block_id = reader.GetObjectId(vtk.vtkExodusIIReader.ELEM_BLOCK, i)
            self.blocks.append(block_id)
            self.block_id_to_exodus_block[block_id] = i
            name = reader.GetObjectName(vtk.vtkExodusIIReader.ELEM_BLOCK,
                                        i).split(' ')
            if 'Unnamed' not in name:
                self.block_id_to_name[block_id] = name[0]
                self.name_to_block_id[name[0]] = block_id

        reader.SetTimeStep(1)
        reader.Update()

        self.data = reader.GetOutput()

        for i in xrange(num_sidesets):
            actor = ExodusActor(self.renderer, self.data,
                                ExodusMap.sideset_vtk_block, i)
            self.sideset_actors[str(self.sidesets[i])] = actor
            self.all_actors.append(actor)

            clipped_actor = ClippedActor(actor, self.plane)
            self.clipped_sideset_actors[str(self.sidesets[i])] = clipped_actor
            self.all_actors.append(clipped_actor)

        for i in xrange(num_nodesets):
            actor = ExodusActor(self.renderer, self.data,
                                ExodusMap.nodeset_vtk_block, i)
            self.nodeset_actors[str(self.nodesets[i])] = actor
            self.all_actors.append(actor)

            clipped_actor = ClippedActor(actor, self.plane)
            self.clipped_nodeset_actors[str(self.nodesets[i])] = clipped_actor
            self.all_actors.append(clipped_actor)

        for i in xrange(num_blocks):
            actor = ExodusActor(self.renderer, self.data,
                                ExodusMap.element_vtk_block, i)
            self.block_actors[str(self.blocks[i])] = actor
            self.all_actors.append(actor)

            clipped_actor = ClippedActor(actor, self.plane)
            self.clipped_block_actors[str(self.blocks[i])] = clipped_actor
            self.all_actors.append(clipped_actor)
Esempio n. 39
0
    def setFileName(self, file_name, lut):

        try:
            self.currently_has_actor = True
            self.lut = lut

            self.file_name = file_name
            self.reader = vtk.vtkExodusIIReader()
            self.reader.SetFileName(self.file_name)
            self.reader.UpdateInformation()

            self.current_dim = self.reader.GetDimensionality()

            self.min_timestep = 0
            self.max_timestep = 0
            range = self.reader.GetTimeStepRange()
            self.min_timestep = range[0]
            self.max_timestep = range[1]

            self.reader.SetAllArrayStatus(vtk.vtkExodusIIReader.ELEM_BLOCK, 1)
            self.reader.SetAllArrayStatus(vtk.vtkExodusIIReader.NODAL, 1)
            self.reader.SetAllArrayStatus(vtk.vtkExodusIIReader.NODAL_TEMPORAL, 1)
            self.reader.SetTimeStep(self.max_timestep)
            self.reader.Update()
            self.current_variable_point_data = {}
            self.current_nodal_variables = []
            self.current_elemental_variables = []
            self.current_nodal_components = {}
            self.current_elemental_components = {}
            self.component_index = -1

            num_blocks = self.reader.GetNumberOfElementBlockArrays()
            self.blocks = set()
            self.block_to_name = {}
            for i in xrange(num_blocks):
                block_num = self.reader.GetObjectId(vtk.vtkExodusIIReader.ELEM_BLOCK,i)
                self.blocks.add(block_num)
                if 'Unnamed' not in self.reader.GetObjectName(vtk.vtkExodusIIReader.ELEM_BLOCK,i).split(' '):
                    self.block_to_name[block_num] = self.reader.GetObjectName(vtk.vtkExodusIIReader.ELEM_BLOCK,i).split(' ')[0]

            cdp = vtk.vtkCompositeDataPipeline()
            vtk.vtkAlgorithm.SetDefaultExecutivePrototype(cdp)

            self.output = self.reader.GetOutput()
            self.geom = vtk.vtkCompositeDataGeometryFilter()
            self.geom.SetInputConnection(0,self.reader.GetOutputPort(0))
            self.geom.Update()

            self.data = self.geom.GetOutput()

            num_nodal_variables = self.data.GetPointData().GetNumberOfArrays()
            for var_num in xrange(num_nodal_variables):
                var_name = self.data.GetPointData().GetArrayName(var_num)
                self.current_nodal_variables.append(var_name)
                components = self.data.GetPointData().GetVectors(var_name).GetNumberOfComponents()
                self.current_nodal_components[var_name] = components
                # self.data.GetPointData().GetVectors(value_string).GetComponentName(0)

            num_elemental_variables = self.data.GetCellData().GetNumberOfArrays()
            for var_num in xrange(num_elemental_variables):
                var_name = self.data.GetCellData().GetArrayName(var_num)
                self.current_elemental_variables.append(var_name)
                components = self.data.GetCellData().GetVectors(var_name).GetNumberOfComponents()
                self.current_elemental_components[var_name] = components

            self.application_filter = self.render_widget.application.filterResult(self.geom)

            self.mapper = vtk.vtkPolyDataMapper()
    #    self.mapper.SetInputConnection(self.tf.GetOutputPort())
            self.mapper.SetInputConnection(self.application_filter.GetOutputPort())
            self.mapper.ScalarVisibilityOn()
            self.mapper.SetLookupTable(lut)
            self.mapper.SetColorModeToMapScalars()
            self.mapper.InterpolateScalarsBeforeMappingOn()

            self.actor = vtk.vtkActor()
            self.current_actors.append(self.actor)
            self.actor.SetMapper(self.mapper)
            self.current_actor = self.actor

            self.clipper = vtk.vtkTableBasedClipDataSet()
            if vtk.VTK_MAJOR_VERSION <= 5:
                self.clipper.SetInput(self.output)
            else:
                self.clipper.SetInputData(self.output)
            self.clipper.SetClipFunction(self.plane)
            self.clipper.Update()

            self.clip_geom = vtk.vtkCompositeDataGeometryFilter()
            self.clip_geom.SetInputConnection(0,self.clipper.GetOutputPort(0))
            self.clip_geom.Update()

            self.clip_data = self.clip_geom.GetOutput()

            self.clip_application_filter = self.render_widget.application.filterResult(self.clip_geom)

            self.clip_mapper = vtk.vtkPolyDataMapper()
            self.clip_mapper.SetInputConnection(self.clip_application_filter.GetOutputPort())
            self.clip_mapper.ScalarVisibilityOn()
            self.clip_mapper.SetLookupTable(lut)

            self.clip_actor = vtk.vtkActor()
            self.clip_actor.SetMapper(self.clip_mapper)
            self.current_actors.append(self.clip_actor)

            self.scalar_bar = vtk.vtkScalarBarActor()
            self.current_actors.append(self.scalar_bar)
            self.scalar_bar.SetLookupTable(self.mapper.GetLookupTable())
            self.scalar_bar.SetNumberOfLabels(4)

            self.current_bounds = self.actor.GetBounds()
        except:
            pass
Esempio n. 40
0
    def setFileName(self, file_name, lut):

        try:
            self.currently_has_actor = True
            self.lut = lut

            self.file_name = file_name
            self.reader = vtk.vtkExodusIIReader()
            self.reader.SetFileName(self.file_name)
            self.reader.UpdateInformation()

            self.current_dim = self.reader.GetDimensionality()

            self.min_timestep = 0
            self.max_timestep = 0
            range = self.reader.GetTimeStepRange()
            self.min_timestep = range[0]
            self.max_timestep = range[1]

            self.reader.SetAllArrayStatus(vtk.vtkExodusIIReader.ELEM_BLOCK, 1)
            self.reader.SetAllArrayStatus(vtk.vtkExodusIIReader.NODAL, 1)
            self.reader.SetAllArrayStatus(vtk.vtkExodusIIReader.NODAL_TEMPORAL,
                                          1)
            self.reader.SetTimeStep(self.max_timestep)
            self.reader.Update()
            self.current_variable_point_data = {}
            self.current_nodal_variables = []
            self.current_elemental_variables = []
            self.current_nodal_components = {}
            self.current_elemental_components = {}
            self.component_index = -1

            num_blocks = self.reader.GetNumberOfElementBlockArrays()
            self.blocks = set()
            self.block_to_name = {}
            for i in xrange(num_blocks):
                block_num = self.reader.GetObjectId(
                    vtk.vtkExodusIIReader.ELEM_BLOCK, i)
                self.blocks.add(block_num)
                if 'Unnamed' not in self.reader.GetObjectName(
                        vtk.vtkExodusIIReader.ELEM_BLOCK, i).split(' '):
                    self.block_to_name[block_num] = self.reader.GetObjectName(
                        vtk.vtkExodusIIReader.ELEM_BLOCK, i).split(' ')[0]

            cdp = vtk.vtkCompositeDataPipeline()
            vtk.vtkAlgorithm.SetDefaultExecutivePrototype(cdp)

            self.output = self.reader.GetOutput()
            self.geom = vtk.vtkCompositeDataGeometryFilter()
            self.geom.SetInputConnection(0, self.reader.GetOutputPort(0))
            self.geom.Update()

            self.data = self.geom.GetOutput()

            num_nodal_variables = self.data.GetPointData().GetNumberOfArrays()
            for var_num in xrange(num_nodal_variables):
                var_name = self.data.GetPointData().GetArrayName(var_num)
                self.current_nodal_variables.append(var_name)
                components = self.data.GetPointData().GetVectors(
                    var_name).GetNumberOfComponents()
                self.current_nodal_components[var_name] = components
                # self.data.GetPointData().GetVectors(value_string).GetComponentName(0)

            num_elemental_variables = self.data.GetCellData(
            ).GetNumberOfArrays()
            for var_num in xrange(num_elemental_variables):
                var_name = self.data.GetCellData().GetArrayName(var_num)
                self.current_elemental_variables.append(var_name)
                components = self.data.GetCellData().GetVectors(
                    var_name).GetNumberOfComponents()
                self.current_elemental_components[var_name] = components

            self.application_filter = self.render_widget.application.filterResult(
                self.geom)

            self.mapper = vtk.vtkPolyDataMapper()
            #    self.mapper.SetInputConnection(self.tf.GetOutputPort())
            self.mapper.SetInputConnection(
                self.application_filter.GetOutputPort())
            self.mapper.ScalarVisibilityOn()
            self.mapper.SetLookupTable(lut)
            self.mapper.SetColorModeToMapScalars()
            self.mapper.InterpolateScalarsBeforeMappingOn()

            self.actor = vtk.vtkActor()
            self.current_actors.append(self.actor)
            self.actor.SetMapper(self.mapper)
            self.current_actor = self.actor

            self.clipper = vtk.vtkTableBasedClipDataSet()
            if vtk.VTK_MAJOR_VERSION <= 5:
                self.clipper.SetInput(self.output)
            else:
                self.clipper.SetInputData(self.output)
            self.clipper.SetClipFunction(self.plane)
            self.clipper.Update()

            self.clip_geom = vtk.vtkCompositeDataGeometryFilter()
            self.clip_geom.SetInputConnection(0, self.clipper.GetOutputPort(0))
            self.clip_geom.Update()

            self.clip_data = self.clip_geom.GetOutput()

            self.clip_application_filter = self.render_widget.application.filterResult(
                self.clip_geom)

            self.clip_mapper = vtk.vtkPolyDataMapper()
            self.clip_mapper.SetInputConnection(
                self.clip_application_filter.GetOutputPort())
            self.clip_mapper.ScalarVisibilityOn()
            self.clip_mapper.SetLookupTable(lut)

            self.clip_actor = vtk.vtkActor()
            self.clip_actor.SetMapper(self.clip_mapper)
            self.current_actors.append(self.clip_actor)

            self.scalar_bar = vtk.vtkScalarBarActor()
            self.current_actors.append(self.scalar_bar)
            self.scalar_bar.SetLookupTable(self.mapper.GetLookupTable())
            self.scalar_bar.SetNumberOfLabels(4)

            self.current_bounds = self.actor.GetBounds()
        except:
            pass
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()