Ejemplo n.º 1
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(
         self, module_manager,
         vtk.vtkReflectionFilter(), 'Processing.',
         ('vtkDataSet',), ('vtkUnstructuredGrid',),
         replaceDoc=True,
         inputFunctions=None, outputFunctions=None)
Ejemplo n.º 2
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(self,
                                       module_manager,
                                       vtk.vtkReflectionFilter(),
                                       'Processing.', ('vtkDataSet', ),
                                       ('vtkUnstructuredGrid', ),
                                       replaceDoc=True,
                                       inputFunctions=None,
                                       outputFunctions=None)
Ejemplo n.º 3
0
    def mirror(self):
        """
        Called when mirrorPlane != None
        The reflection plane is labeled as follows: From the vtkfiles documentation:
        ReflectionPlane {
        USE_X_MIN = 0, USE_Y_MIN = 1, USE_Z_MIN = 2, USE_X_MAX = 3,
        USE_Y_MAX = 4, USE_Z_MAX = 5, USE_X = 6, USE_Y = 7,
        USE_Z = 8
        }
        """

        vr=v.vtkReflectionFilter()
        vr.SetInputData(self.data)
        vr.SetPlane(self.mirrorPlane)
        self.data=vr.GetOutput()
        vr.Update()
        #self.data.Update()
        self.ncells = self.data.GetNumberOfCells()
Ejemplo n.º 4
0
    def landmark_reflection(self, ref_axis='x'):
        RefFilter = vtk.vtkReflectionFilter()
        if ref_axis == 'x':
            RefFilter.SetPlaneToX()
        elif ref_axis == 'y':
            RefFilter.SetPlaneToY()
        elif ref_axis == 'z':
            RefFilter.SetPlaneToZ()
        else:
            if self.warning:
                print('Invalid ref_axis!')

        RefFilter.CopyInputOff()
        RefFilter.SetInputData(self.vtkPolyData)
        RefFilter.Update()

        self.vtkPolyData = RefFilter.GetOutput()
        self.get_landmark_data_from_vtkPolyData()
Ejemplo n.º 5
0
    def mirror(self):
        """
        Called when mirrorPlane != None
        The reflection plane is labeled as follows: From the vtk documentation: 
        ReflectionPlane {
        USE_X_MIN = 0, USE_Y_MIN = 1, USE_Z_MIN = 2, USE_X_MAX = 3,
        USE_Y_MAX = 4, USE_Z_MAX = 5, USE_X = 6, USE_Y = 7,
        USE_Z = 8
        }
        """

        vr=v.vtkReflectionFilter()
        vr.SetInput(self.data)
        vr.SetPlane(self.mirrorPlane)
        self.data=vr.GetOutput()
        vr.Update()
        self.data.Update()
        self.ncells = self.data.GetNumberOfCells()
Ejemplo n.º 6
0
    def mesh_reflection(self, ref_axis='x'):
        '''
        This function is only for tooth arch model,
        it will flip the label (n=15 so far) as well.
        input:
            ref_axis: 'x'/'y'/'z'
        '''
        RefFilter = vtk.vtkReflectionFilter()
        if ref_axis == 'x':
            RefFilter.SetPlaneToX()
        elif ref_axis == 'y':
            RefFilter.SetPlaneToY()
        elif ref_axis == 'z':
            RefFilter.SetPlaneToZ()
        else:
            if self.warning:
                print('Invalid ref_axis!')

        RefFilter.CopyInputOff()
        RefFilter.SetInputData(self.vtkPolyData)
        RefFilter.Update()

        self.vtkPolyData = RefFilter.GetOutput()
        self.get_mesh_data_from_vtkPolyData()

        original_cell_labels = np.copy(
            self.cell_attributes['Label'])  # add original cell label back
        # for permanent teeth
        for i in range(1, 15):
            if len(original_cell_labels == i) > 0:
                self.cell_attributes['Label'][
                    original_cell_labels ==
                    i] = 15 - i  #1 -> 14, 2 -> 13, ..., 14 -> 1
        # for primary teeth
        for i in range(15, 25):
            if len(original_cell_labels == i) > 0:
                self.cell_attributes['Label'][
                    original_cell_labels ==
                    i] = 39 - i  #15 -> 24, 16 -> 23, ..., 24 -> 15
Ejemplo n.º 7
0
#!/usr/bin/env python
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()

cone = vtk.vtkConeSource()
reflect = vtk.vtkReflectionFilter()
reflect.SetInputConnection(cone.GetOutputPort())
reflect.SetPlaneToXMax()
reflect2 = vtk.vtkReflectionFilter()
reflect2.SetInputConnection(reflect.GetOutputPort())
reflect2.SetPlaneToYMax()
reflect3 = vtk.vtkReflectionFilter()
reflect3.SetInputConnection(reflect2.GetOutputPort())
reflect3.SetPlaneToZMax()
mapper = vtk.vtkDataSetMapper()
mapper.SetInputConnection(reflect3.GetOutputPort())
actor = vtk.vtkActor()
actor.SetMapper(mapper)
ren1 = vtk.vtkRenderer()
ren1.AddActor(actor)
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren1)
renWin.SetSize(200, 200)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
iren.Initialize()
renWin.Render()
# --- end of script --
def ProjectImagingMesh(ini_file):
    import vtk.util.numpy_support as vtkNumPy
    import ConfigParser
    import scipy.io as scipyio
    # echo vtk version info
    print "using vtk version", vtk.vtkVersion.GetVTKVersion()
    # read config file
    config = ConfigParser.ConfigParser()
    config.add_section("imaging")
    config.add_section("fem")
    config.set("imaging", "listoffset", "[0]")
    config.read(ini_file)

    # get work directory
    work_dir = config.get('fem', 'work_dir')

    # FIXME  notice that order of operations is IMPORTANT
    # FIXME   translation followed by rotation will give different results
    # FIXME   than rotation followed by translation
    # FIXME  Translate -> RotateZ -> RotateY -> RotateX -> Scale seems to be the order of paraview
    RotateX = float(config.get('fem', 'rotatex'))
    RotateY = float(config.get('fem', 'rotatey'))
    RotateZ = float(config.get('fem', 'rotatez'))
    Translate = eval(config.get('fem', 'translate'))
    Scale = eval(config.get('fem', 'scale'))
    print "rotate", RotateX, RotateY, RotateZ, "translate", Translate, "scale", Scale

    # read imaging data geometry that will be used to project FEM data onto
    dimensions = eval(config.get('imaging', 'dimensions'))
    spacing = eval(config.get('imaging', 'spacing'))
    origin = eval(config.get('imaging', 'origin'))
    print spacing, origin, dimensions
    templateImage = CreateVTKImage(dimensions, spacing, origin)
    # write template image for position verification
    vtkTemplateWriter = vtk.vtkDataSetWriter()
    vtkTemplateWriter.SetFileName("%s/imageTemplate.vtk" % work_dir)
    vtkTemplateWriter.SetInput(templateImage)
    vtkTemplateWriter.Update()

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	  
	    # write output
	    print "writing ", timeID, mesh_filename, work_dir
	    vtkStatsWriter = vtk.vtkDataSetWriter()
	    vtkStatsWriter.SetFileTypeToBinary()
	    vtkStatsWriter.SetFileName("%s/modelstats.navg%d.%s.%04d.vtk"%(work_dir,naverage,mesh_filename,timeID))
	    vtkStatsWriter.SetInput(vtkResample.GetOutput())
	    vtkStatsWriter.Update()
def 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)
Ejemplo n.º 11
0
#!/usr/bin/env python
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()

cone = vtk.vtkConeSource()
reflect = vtk.vtkReflectionFilter()
reflect.SetInputConnection(cone.GetOutputPort())
reflect.SetPlaneToXMax()
reflect2 = vtk.vtkReflectionFilter()
reflect2.SetInputConnection(reflect.GetOutputPort())
reflect2.SetPlaneToYMax()
reflect3 = vtk.vtkReflectionFilter()
reflect3.SetInputConnection(reflect2.GetOutputPort())
reflect3.SetPlaneToZMax()
mapper = vtk.vtkDataSetMapper()
mapper.SetInputConnection(reflect3.GetOutputPort())
actor = vtk.vtkActor()
actor.SetMapper(mapper)
ren1 = vtk.vtkRenderer()
ren1.AddActor(actor)
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren1)
renWin.SetSize(200,200)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
iren.Initialize()
renWin.Render()
# --- end of script --
Ejemplo n.º 12
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()