Ejemplo n.º 1
0
def gradient(narray, dataset=None):
    "Returns the gradient of an array of scalars/vectors."
    if not dataset: dataset = narray.DataSet
    if not dataset: raise RuntimeError('Need a dataset to compute gradient')

    try:
      ncomp = narray.shape[1]
    except IndexError:
      ncomp = 1
    if ncomp != 1 and ncomp != 3:
       raise RuntimeError('Gradient only works with scalars (1 component) and vectors (3 component)' +
                          ' Input shape ' + str(narray.shape))

    cd = vtk.vtkCellDerivatives()
    if ncomp == 1 : attribute_type = 'scalars'
    else : attribute_type = 'vectors'

    res = _cell_derivatives(narray, dataset, attribute_type, cd)

    if ncomp == 1 : retVal = res.GetVectors()
    else : retVal = res.GetTensors()

    try:
        if narray.GetName() : retVal.SetName("gradient of " + narray.GetName())
        else : retVal.SetName("gradient")
    except AttributeError : retVal.SetName("gradient")

    ans = dsa.vtkDataArrayToVTKArray(retVal, dataset)

    # The association information has been lost over the vtk filter
    # we must reconstruct it otherwise lower pipeline will be broken.
    ans.Association = narray.Association

    return ans
Ejemplo n.º 2
0
def gradient(narray, dataset=None):
    "Returns the gradient of an array of scalars/vectors."
    if not dataset: dataset = narray.DataSet
    if not dataset: raise RuntimeError, 'Need a dataset to compute gradient'

    try:
      ncomp = narray.shape[1]
    except IndexError:
      ncomp = 1
    if ncomp != 1 and ncomp != 3:
       raise RuntimeError, 'Gradient only works with scalars (1 component) and vectors (3 component)'\
                           'Input shape ' + narray.shape

    cd = vtk.vtkCellDerivatives()
    if ncomp == 1 : attribute_type = 'scalars'
    else : attribute_type = 'vectors'

    res = _cell_derivatives(narray, dataset, attribute_type, cd)

    if ncomp == 1 : retVal = res.GetVectors()
    else : retVal = res.GetTensors()

    try:
        if narray.GetName() : retVal.SetName("gradient of " + narray.GetName())
        else : retVal.SetName("gradient")
    except AttributeError : retVal.SetName("gradient")

    ans = dsa.vtkDataArrayToVTKArray(retVal, dataset)

    # The association information has been lost over the vtk filter
    # we must reconstruct it otherwise lower pipeline will be broken.
    ans.Association = narray.Association

    return ans
Ejemplo n.º 3
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(
         self, module_manager,
         vtk.vtkCellDerivatives(), 'Processing.',
         ('vtkDataSet',), ('vtkDataSet',),
         replaceDoc=True,
         inputFunctions=None, outputFunctions=None)
Ejemplo n.º 4
0
def VtuFieldGradient(inputVtu, fieldName):
  """
  Return the gradient of a scalar field in a vtu
  """
  
  tempVtu = vtu()
  # Add the points
  tempVtu.ugrid.SetPoints(inputVtu.ugrid.GetPoints())
  # Add the cells
  tempVtu.ugrid.SetCells(inputVtu.ugrid.GetCellTypesArray(), inputVtu.ugrid.GetCellLocationsArray(), inputVtu.ugrid.GetCells())
  # Add the field
  tempVtu.AddField(fieldName, inputVtu.GetScalarField(fieldName))
  tempVtu.ugrid.GetPointData().SetActiveScalars(fieldName)
    
  gradientFilter = vtk.vtkCellDerivatives()
  gradientFilter.SetInput(tempVtu.ugrid)
  gradientFilter.Update()
  
  projectionFilter = vtk.vtkCellDataToPointData()
  projectionFilter.SetInputConnection(gradientFilter.GetOutputPort())
  projectionFilter.Update()
  
  tempVtu = vtu()
  tempVtu.ugrid = PolyDataToUnstructuredGrid(projectionFilter.GetOutput())
  
  return tempVtu.GetField(tempVtu.GetFieldNames()[-1])
Ejemplo n.º 5
0
 def GetDerivative(self, name):
   """
   Returns the derivative of field 'name', a
   vector field if 'name' is scalar, and a tensor field
   if 'name' is a vector. The field 'name' has to be point-wise data.
   The returned array gives a cell-wise derivative.
   """
   cd=vtk.vtkCellDerivatives()
   cd.SetInput(self.ugrid)
   pointdata=self.ugrid.GetPointData()
   nc=pointdata.GetArray(name).GetNumberOfComponents()
   if nc==1:
     cd.SetVectorModeToComputeGradient()
     cd.SetTensorModeToPassTensors()
     pointdata.SetActiveScalars(name)
     cd.Update()
     vtkdata=cd.GetUnstructuredGridOutput().GetCellData().GetArray('ScalarGradient')
     return arr([vtkdata.GetTuple3(i) for i in range(vtkdata.GetNumberOfTuples())])
   else:
     cd.SetTensorModeToComputeGradient()
     cd.SetVectorModeToPassVectors()
     pointdata.SetActiveVectors(name)
     cd.Update()
     vtkdata=cd.GetUnstructuredGridOutput().GetCellData().GetArray('VectorGradient')
     return arr([vtkdata.GetTuple9(i) for i in range(vtkdata.GetNumberOfTuples())])
Ejemplo n.º 6
0
def strain(narray, dataset=None):
    "Returns the strain of an array of 3D vectors."
    if not dataset:
        dataset = narray.DataSet
    if not dataset:
        raise RuntimeError("Need a dataset to compute strain")

    if 2 != narray.ndim or 3 != narray.shape[1]:
        raise RuntimeError("strain only works with an array of 3D vectors" + "Input shape " + str(narray.shape))

    cd = vtk.vtkCellDerivatives()
    cd.SetTensorModeToComputeStrain()

    res = _cell_derivatives(narray, dataset, "vectors", cd)

    retVal = res.GetTensors()
    retVal.SetName("strain")

    ans = dsa.vtkDataArrayToVTKArray(retVal, dataset)

    # The association information has been lost over the vtk filter
    # we must reconstruct it otherwise lower pipeline will be broken.
    ans.Association = narray.Association

    return ans
Ejemplo n.º 7
0
 def GetDerivative(self, name):
   """
   Returns the derivative of field 'name', a
   vector field if 'name' is scalar, and a tensor field
   if 'name' is a vector. The field 'name' has to be point-wise data.
   The returned array gives a cell-wise derivative.
   """
   cd=vtk.vtkCellDerivatives()
   cd.SetInputData(self.ugrid)
   pointdata=self.ugrid.GetPointData()
   nc=pointdata.GetArray(name).GetNumberOfComponents()
   if nc==1:
     cd.SetVectorModeToComputeGradient()
     cd.SetTensorModeToPassTensors()
     pointdata.SetActiveScalars(name)
     cd.Update()
     vtkdata=cd.GetUnstructuredGridOutput().GetCellData().GetArray('ScalarGradient')
     return arr([vtkdata.GetTuple3(i) for i in range(vtkdata.GetNumberOfTuples())])
   else:
     cd.SetTensorModeToComputeGradient()
     cd.SetVectorModeToPassVectors()
     pointdata.SetActiveVectors(name)
     cd.Update()
     vtkdata=cd.GetUnstructuredGridOutput().GetCellData().GetArray('VectorGradient')
     return arr([vtkdata.GetTuple9(i) for i in range(vtkdata.GetNumberOfTuples())])
Ejemplo n.º 8
0
def VtuFieldGradient(inputVtu, fieldName):
    """
  Return the gradient of a scalar field in a vtu
  """

    tempVtu = vtu()
    # Add the points
    tempVtu.ugrid.SetPoints(inputVtu.ugrid.GetPoints())
    # Add the cells
    tempVtu.ugrid.SetCells(inputVtu.ugrid.GetCellTypesArray(),
                           inputVtu.ugrid.GetCellLocationsArray(),
                           inputVtu.ugrid.GetCells())
    # Add the field
    tempVtu.AddField(fieldName, inputVtu.GetScalarField(fieldName))
    tempVtu.ugrid.GetPointData().SetActiveScalars(fieldName)

    gradientFilter = vtk.vtkCellDerivatives()
    gradientFilter.SetInput(tempVtu.ugrid)
    gradientFilter.Update()

    projectionFilter = vtk.vtkCellDataToPointData()
    projectionFilter.SetInputConnection(gradientFilter.GetOutputPort())
    projectionFilter.Update()

    tempVtu = vtu()
    tempVtu.ugrid = PolyDataToUnstructuredGrid(projectionFilter.GetOutput())

    return tempVtu.GetField(tempVtu.GetFieldNames()[-1])
Ejemplo n.º 9
0
 def initialize (self):
     debug ("In Vorticity::initialize()")
     self.fil = vtk.vtkCellDerivatives ()
     self.fil.SetVectorModeToComputeVorticity ()
     self.fil.SetInput(self.prev_fil.GetOutput ())        
     self.fil.Update ()
     self.dimension_to_allow = Tkinter.IntVar ()
     self.dimension_to_allow.set (-1)
     self.vector_name = Tkinter.StringVar ()
     self.vector_name.set ("Vorticity")
Ejemplo n.º 10
0
 def GetVorticity(self, name):
   """
   Returns the vorticity of vectorfield 'name'.
   The field 'name' has to be point-wise data.
   The returned array gives a cell-wise derivative.
   """
   cd=vtk.vtkCellDerivatives()
   cd.SetInput(self.ugrid)
   pointdata=self.ugrid.GetPointData()
   cd.SetVectorModeToComputeVorticity()
   cd.SetTensorModeToPassTensors()
   pointdata.SetActiveVectors(name)
   cd.Update()
   vtkdata=cd.GetUnstructuredGridOutput().GetCellData().GetArray('VectorGradient')
   return arr([vtkdata.GetTuple3(i) for i in range(vtkdata.GetNumberOfTuples())])
Ejemplo n.º 11
0
 def GetVorticity(self, name):
   """
   Returns the vorticity of vectorfield 'name'.
   The field 'name' has to be point-wise data.
   The returned array gives a cell-wise derivative.
   """
   cd=vtk.vtkCellDerivatives()
   cd.SetInputData(self.ugrid)
   pointdata=self.ugrid.GetPointData()
   cd.SetVectorModeToComputeVorticity()
   cd.SetTensorModeToPassTensors()
   pointdata.SetActiveVectors(name)
   cd.Update()
   vtkdata=cd.GetUnstructuredGridOutput().GetCellData().GetArray('VectorGradient')
   return arr([vtkdata.GetTuple3(i) for i in range(vtkdata.GetNumberOfTuples())])
Ejemplo n.º 12
0
def addDeformationGradients(mesh,
                            disp_array_name="Displacement",
                            defo_grad_array_name="DeformationGradient",
                            verbose=0):

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

    mypy.my_print(
        min(verbose, 1),
        "*** Warning: at some point the ordering of vector gradient components has changed, and uses C ordering instead of F. ***"
    )
    if (vtk.vtkVersion.GetVTKMajorVersion() >= 8):
        ordering = "C"
    elif (vtk.vtkVersion.GetVTKMajorVersion()
          == 7) and ((vtk.vtkVersion.GetVTKMinorVersion() > 0) or
                     (vtk.vtkVersion.GetVTKBuildVersion() > 0)):
        ordering = "C"
    else:
        ordering = "F"

    n_cells = mesh.GetNumberOfCells()

    assert (mesh.GetPointData().HasArray(disp_array_name))
    mesh.GetPointData().SetActiveVectors(disp_array_name)
    cell_derivatives = vtk.vtkCellDerivatives()
    cell_derivatives.SetVectorModeToPassVectors()
    cell_derivatives.SetTensorModeToComputeGradient()
    if (vtk.vtkVersion.GetVTKMajorVersion() >= 6):
        cell_derivatives.SetInputData(mesh)
    else:
        cell_derivatives.SetInput(mesh)
    cell_derivatives.Update()
    farray_gu = cell_derivatives.GetOutput().GetCellData().GetArray(
        "VectorGradient")

    farray_defo_grad = myvtk.createFloatArray(name=defo_grad_array_name,
                                              n_components=9,
                                              n_tuples=n_cells)
    mesh.GetCellData().AddArray(farray_defo_grad)
    I = numpy.eye(3)
    for k_cell in range(n_cells):
        GU = numpy.reshape(farray_gu.GetTuple(k_cell), (3, 3), order=ordering)
        F = I + GU
        farray_defo_grad.SetTuple(k_cell, numpy.reshape(F, 9, order='C'))
def addDeformationGradients(
        mesh,
        disp_array_name="Displacement",
        defo_grad_array_name="DeformationGradient",
        verbose=0):

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

    mypy.my_print(min(verbose,1), "*** Warning: at some point the ordering of vector gradient components has changed, and uses C ordering instead of F. ***")
    if   (vtk.vtkVersion.GetVTKMajorVersion() >= 8):
        ordering = "C"
    elif (vtk.vtkVersion.GetVTKMajorVersion() == 7) and ((vtk.vtkVersion.GetVTKMinorVersion() > 0) or (vtk.vtkVersion.GetVTKBuildVersion() > 0)):
        ordering = "C"
    else:
        ordering = "F"

    n_cells = mesh.GetNumberOfCells()

    assert (mesh.GetPointData().HasArray(disp_array_name))
    mesh.GetPointData().SetActiveVectors(disp_array_name)
    cell_derivatives = vtk.vtkCellDerivatives()
    cell_derivatives.SetVectorModeToPassVectors()
    cell_derivatives.SetTensorModeToComputeGradient()
    if (vtk.vtkVersion.GetVTKMajorVersion() >= 6):
        cell_derivatives.SetInputData(mesh)
    else:
        cell_derivatives.SetInput(mesh)
    cell_derivatives.Update()
    farray_gu = cell_derivatives.GetOutput().GetCellData().GetArray("VectorGradient")

    farray_defo_grad = myvtk.createFloatArray(
        name=defo_grad_array_name,
        n_components=9,
        n_tuples=n_cells)
    mesh.GetCellData().AddArray(farray_defo_grad)
    I = numpy.eye(3)
    for k_cell in range(n_cells):
        GU = numpy.reshape(farray_gu.GetTuple(k_cell), (3,3), order=ordering)
        F = I + GU
        farray_defo_grad.SetTuple(k_cell, numpy.reshape(F, 9, order='C'))
Ejemplo n.º 14
0
def curl (narray, dataset=None):
    "Returns the curl of an array of 3D vectors."
    if not dataset : dataset = narray.DataSet
    if not dataset : raise RuntimeError('Need a dataset to compute curl.')

    if narray.ndim != 2 or narray.shape[1] != 3 :
       raise RuntimeError('Curl only works with an array of 3D vectors.' +
                          'Input shape ' + str(narray.shape))

    cd = vtk.vtkCellDerivatives()
    cd.SetVectorModeToComputeVorticity()

    res = _cell_derivatives(narray, dataset, 'vectors', cd)

    retVal = res.GetVectors()
    retVal.SetName("vorticity")

    ans = dsa.vtkDataArrayToVTKArray(retVal, dataset)

    # The association information has been lost over the vtk filter
    # we must reconstruct it otherwise lower pipeline will be broken.
    ans.Association = narray.Association

    return ans
Ejemplo n.º 15
0
def strain (narray, dataset=None) :
    "Returns the strain of an array of 3D vectors."
    if not dataset : dataset = narray.DataSet
    if not dataset : raise RuntimeError('Need a dataset to compute strain')

    if 2 != narray.ndim or 3 != narray.shape[1] :
       raise RuntimeError('strain only works with an array of 3D vectors' +
                          'Input shape ' + str(narray.shape))

    cd = vtk.vtkCellDerivatives()
    cd.SetTensorModeToComputeStrain()

    res = _cell_derivatives(narray, dataset, 'vectors', cd)

    retVal = res.GetTensors()
    retVal.SetName("strain")

    ans = dsa.vtkDataArrayToVTKArray(retVal, dataset)

    # The association information has been lost over the vtk filter
    # we must reconstruct it otherwise lower pipeline will be broken.
    ans.Association = narray.Association

    return ans
Ejemplo n.º 16
0
def curl (narray, dataset=None):
    "Returns the curl of an array of 3D vectors."
    if not dataset : dataset = narray.DataSet
    if not dataset : raise RuntimeError, 'Need a dataset to compute curl.'

    if narray.ndim != 2 or narray.shape[1] != 3 :
       raise RuntimeError, 'Curl only works with an array of 3D vectors.'\
                           'Input shape ' + narray.shape

    cd = vtk.vtkCellDerivatives()
    cd.SetVectorModeToComputeVorticity()

    res = _cell_derivatives(narray, dataset, 'vectors', cd)

    retVal = res.GetVectors()
    retVal.SetName("vorticity")

    ans = dsa.vtkDataArrayToVTKArray(retVal, dataset)

    # The association information has been lost over the vtk filter
    # we must reconstruct it otherwise lower pipeline will be broken.
    ans.Association = narray.Association

    return ans
def read_data_and_differentiate(pod_mode_dir,num_modes,num_points,num_boundary_faces,num_dimensions,num_components,correct_for_cell_volumes, \
				u,v,w,dudx,dudy,dudz,dvdx,dvdy,dvdz,dwdx,dwdy,dwdz,\
				uF,vF,wF,dudxF,dudyF,dudzF,dvdxF,dvdyF,dvdzF,dwdxF,dwdyF,dwdzF,cell_volume,norm,calibrate_coefficients):

	u_read = np.array(np.zeros((num_points,3), dtype=np.float64))
	dudx_read = np.array(np.zeros((num_points,3,3), dtype=np.float64))
	uF_read = np.array(np.zeros((num_boundary_faces,3), dtype=np.float64))
	dudxF_read = np.array(np.zeros((num_boundary_faces,3,3), dtype=np.float64))

	# ..................................................
	# Read meanfield and spatially differentiate
	filename = pod_mode_dir + "/spatial_meanfield.vtk"
	print '   Reading file ', filename.strip()
	reader = vtk.vtkUnstructuredGridReader()
	reader.ReadAllScalarsOn()
	reader.ReadAllVectorsOn()
	reader.ReadAllTensorsOn()
	reader.SetFileName(filename)
	reader.Update()
	grid = vtk.vtkUnstructuredGrid()
	grid.DeepCopy(reader.GetOutput())

	# get cell volumes
	if (correct_for_cell_volumes=="true"):
	        cell_volume[:] = VN.vtk_to_numpy(grid.GetPointData().GetScalars("cell_volume"))
	else:
        	cell_volume[:] = 1.0

	# get mean velocity field within volume
	u_read = VN.vtk_to_numpy(grid.GetPointData().GetVectors("u"))
	u[:,0] = u_read[:,0].copy()
	v[:,0] = u_read[:,1].copy()
	w[:,0] = u_read[:,2].copy()
	grid.GetPointData().SetVectors(grid.GetPointData().GetVectors("u"))

	# get mean velocity derivative field within volume
	differentiator = vtk.vtkCellDerivatives()
	differentiator.SetTensorModeToComputeGradient()
	differentiator.SetInput(grid)
	differentiator.Update()
	cell_to_point_data = vtk.vtkCellDataToPointData()
	cell_to_point_data.SetInput(differentiator.GetOutput())
	cell_to_point_data.Update()
        grid.GetPointData().SetTensors(cell_to_point_data.GetOutput().GetPointData().GetTensors())
	dudx_read = VN.vtk_to_numpy(cell_to_point_data.GetOutput().GetPointData().GetTensors())
	dudx[:,0] = dudx_read[:,0].copy() 
	dvdx[:,0] = dudx_read[:,1].copy() 
	dwdx[:,0] = dudx_read[:,2].copy() 
	dudy[:,0] = dudx_read[:,3].copy() 
	dvdy[:,0] = dudx_read[:,4].copy() 
	dwdy[:,0] = dudx_read[:,5].copy() 
	dudz[:,0] = dudx_read[:,6].copy() 
	dvdz[:,0] = dudx_read[:,7].copy() 
	dwdz[:,0] = dudx_read[:,8].copy() 

	# extract boundary surface data
	if( (calibrate_coefficients=="none") or (calibrate_coefficients=="constant") ):
		geom_filter = vtk.vtkDataSetSurfaceFilter()
		geom_filter.SetInput(grid)
		geom_filter.Update()
		boundary_faces = vtk.vtkPolyData()
		boundary_faces = geom_filter.GetOutput()
		point_to_cell_data = vtk.vtkPointDataToCellData()
		point_to_cell_data.SetInput(geom_filter.GetOutput())
		point_to_cell_data.Update()

		# get mean velocity field on boundary surface
		uF_read = VN.vtk_to_numpy(point_to_cell_data.GetOutput().GetCellData().GetVectors("u"))
		uF[:,0] = uF_read[:,0]
		vF[:,0] = uF_read[:,1]
		wF[:,0] = uF_read[:,2]

		# get mean derivative velocity field on boundary surface
		dudxF_read = VN.vtk_to_numpy(point_to_cell_data.GetOutput().GetCellData().GetTensors())
		dudxF[:,0] = dudxF_read[:,0] 
		dvdxF[:,0] = dudxF_read[:,1] 
		dwdxF[:,0] = dudxF_read[:,2] 
		dudyF[:,0] = dudxF_read[:,3] 
		dvdyF[:,0] = dudxF_read[:,4] 
		dwdyF[:,0] = dudxF_read[:,5] 
		dudzF[:,0] = dudxF_read[:,6] 
		dvdzF[:,0] = dudxF_read[:,7] 
		dwdzF[:,0] = dudxF_read[:,8] 

		# get boundary face normals
		norm_filter = vtk.vtkPolyDataNormals()
		norm_filter.ComputeCellNormalsOn()
		norm_filter.SetInput(boundary_faces)
		norm_filter.Update()
		area_filter = vtk.vtkMeshQuality()
		area_filter.SetQuadQualityMeasureToArea()
		area_filter.SetTriangleQualityMeasureToArea()
		area_filter.SetInput(boundary_faces)
		area_filter.Update()
		for j in range(0,num_boundary_faces):
			area = area_filter.GetOutput().GetCellData().GetArray("Quality").GetComponent(j,0)
			norm[j,:] = norm_filter.GetOutput().GetCellData().GetNormals().GetTuple(j)
			norm[j,:] = norm[j,:] * area

	# ..................................................
	# Read modes and spatially differentiate
	for j in range(0,num_modes):
		j_index = j+1
		filename = pod_mode_dir + '/POD.spatial_mode_' + '%04d'%j_index + '.vtk'
		print '   Reading file ', filename.strip(), 'file number ', j_index, ' of ', num_modes
		reader.SetFileName(filename)
		reader.Update()

		# get mode velocity field within volume
		u_read = VN.vtk_to_numpy(reader.GetOutput().GetPointData().GetVectors("u"))
		u[:,j_index] = u_read[:,0]
		v[:,j_index] = u_read[:,1]
		w[:,j_index] = u_read[:,2]

		# get mode velocity derivative fields within volume
		grid.GetPointData().SetVectors(reader.GetOutput().GetPointData().GetVectors("u"))
		differentiator.SetInput(grid)
		differentiator.Update()
		cell_to_point_data.SetInput(differentiator.GetOutput())
		cell_to_point_data.Update()
        	grid.GetPointData().SetTensors(cell_to_point_data.GetOutput().GetPointData().GetTensors())
		dudx_read = VN.vtk_to_numpy(cell_to_point_data.GetOutput().GetPointData().GetTensors())
		dudx[:,j_index] = dudx_read[:,0] 
		dvdx[:,j_index] = dudx_read[:,1] 
		dwdx[:,j_index] = dudx_read[:,2] 
		dudy[:,j_index] = dudx_read[:,3] 
		dvdy[:,j_index] = dudx_read[:,4] 
		dwdy[:,j_index] = dudx_read[:,5] 
		dudz[:,j_index] = dudx_read[:,6] 
		dvdz[:,j_index] = dudx_read[:,7] 
		dwdz[:,j_index] = dudx_read[:,8]

		# extract boundary surface data
		if( (calibrate_coefficients=="none") or (calibrate_coefficients=="constant") ):
			geom_filter.SetInput(grid)
			geom_filter.Update()
			boundary_faces = geom_filter.GetOutput()
			point_to_cell_data.SetInput(geom_filter.GetOutput())
			point_to_cell_data.Update()

			# get mode velocity field on boundary surface
			uF_read = VN.vtk_to_numpy(point_to_cell_data.GetOutput().GetCellData().GetVectors("u"))
			uF[:,j_index] = uF_read[:,0]
			vF[:,j_index] = uF_read[:,1]
			wF[:,j_index] = uF_read[:,2]

			# get mean derivative velocity field on boundary surface
			dudxF_read = VN.vtk_to_numpy(point_to_cell_data.GetOutput().GetCellData().GetTensors())
			dudxF[:,j_index] = dudxF_read[:,0] 
			dvdxF[:,j_index] = dudxF_read[:,1] 
			dwdxF[:,j_index] = dudxF_read[:,2] 
			dudyF[:,j_index] = dudxF_read[:,3] 
			dvdyF[:,j_index] = dudxF_read[:,4] 
			dwdyF[:,j_index] = dudxF_read[:,5] 
			dudzF[:,j_index] = dudxF_read[:,6] 
			dvdzF[:,j_index] = dudxF_read[:,7] 
			dwdzF[:,j_index] = dudxF_read[:,8] 

	# ..................................................
	# zero appropriate coefficients
	if (num_dimensions<3):
		dudz[:,:] = 0.0
		dvdz[:,:] = 0.0
		dwdz[:,:] = 0.0
	if (num_dimensions<2):
		dudy[:,:] = 0.0
		dvdy[:,:] = 0.0
		dwdy[:,:] = 0.0
	if (num_components<3):
		w[:,:] = 0.0
		dwdx[:,:] = 0.0
		dwdy[:,:] = 0.0
		dwdz[:,:] = 0.0
	if (num_components<2):
		v[:,:] = 0.0
		dvdx[:,:] = 0.0
		dvdy[:,:] = 0.0
		dvdz[:,:] = 0.0
	if( (calibrate_coefficients=="none") or (calibrate_coefficients=="constant") ):
		if (num_dimensions<3):
			dudzF[:,:] = 0.0
			dvdzF[:,:] = 0.0
			dwdzF[:,:] = 0.0
		if (num_dimensions<2):
			dudyF[:,:] = 0.0
			dvdyF[:,:] = 0.0
			dwdyF[:,:] = 0.0
		if (num_components<3):
			wF[:,j_index] = 0.0
			dwdxF[:,:] = 0.0
			dwdyF[:,:] = 0.0
			dwdzF[:,:] = 0.0
		if (num_components<2):
			vF[:,:] = 0.0
			dvdxF[:,:] = 0.0
			dvdyF[:,:] = 0.0
			dvdzF[:,:] = 0.0
Ejemplo n.º 18
0
def read_data_and_differentiate(pod_mode_dir,num_modes,num_points,num_boundary_faces,num_dimensions,num_components,correct_for_cell_volumes, \
    u,v,w,dudx,dudy,dudz,dvdx,dvdy,dvdz,dwdx,dwdy,dwdz,\
    uF,vF,wF,dudxF,dudyF,dudzF,dvdxF,dvdyF,dvdzF,dwdxF,dwdyF,dwdzF,cell_volume,norm,calibrate_coefficients):

    u_read = np.array(np.zeros((num_points, 3), dtype=np.float64))
    dudx_read = np.array(np.zeros((num_points, 3, 3), dtype=np.float64))
    uF_read = np.array(np.zeros((num_boundary_faces, 3), dtype=np.float64))
    dudxF_read = np.array(
        np.zeros((num_boundary_faces, 3, 3), dtype=np.float64))

    # ..................................................
    # Read meanfield and spatially differentiate
    filename = pod_mode_dir + "/spatial_meanfield.vtk"
    print '   Reading file ', filename.strip()
    reader = vtk.vtkUnstructuredGridReader()
    reader.ReadAllScalarsOn()
    reader.ReadAllVectorsOn()
    reader.ReadAllTensorsOn()
    reader.SetFileName(filename)
    reader.Update()
    grid = vtk.vtkUnstructuredGrid()
    grid.DeepCopy(reader.GetOutput())

    # get cell volumes
    if (correct_for_cell_volumes == "true"):
        cell_volume[:] = VN.vtk_to_numpy(
            grid.GetPointData().GetScalars("cell_volume"))
    else:
        cell_volume[:] = 1.0

    # get mean velocity field within volume
    u_read = VN.vtk_to_numpy(grid.GetPointData().GetVectors("u"))
    u[:, 0] = u_read[:, 0].copy()
    v[:, 0] = u_read[:, 1].copy()
    w[:, 0] = u_read[:, 2].copy()
    grid.GetPointData().SetVectors(grid.GetPointData().GetVectors("u"))

    # get mean velocity derivative field within volume
    differentiator = vtk.vtkCellDerivatives()
    differentiator.SetTensorModeToComputeGradient()
    differentiator.SetInput(grid)
    differentiator.Update()
    cell_to_point_data = vtk.vtkCellDataToPointData()
    cell_to_point_data.SetInput(differentiator.GetOutput())
    cell_to_point_data.Update()
    grid.GetPointData().SetTensors(
        cell_to_point_data.GetOutput().GetPointData().GetTensors())
    dudx_read = VN.vtk_to_numpy(
        cell_to_point_data.GetOutput().GetPointData().GetTensors())
    dudx[:, 0] = dudx_read[:, 0].copy()
    dvdx[:, 0] = dudx_read[:, 1].copy()
    dwdx[:, 0] = dudx_read[:, 2].copy()
    dudy[:, 0] = dudx_read[:, 3].copy()
    dvdy[:, 0] = dudx_read[:, 4].copy()
    dwdy[:, 0] = dudx_read[:, 5].copy()
    dudz[:, 0] = dudx_read[:, 6].copy()
    dvdz[:, 0] = dudx_read[:, 7].copy()
    dwdz[:, 0] = dudx_read[:, 8].copy()

    # extract boundary surface data
    if ((calibrate_coefficients == "none")
            or (calibrate_coefficients == "constant")):
        geom_filter = vtk.vtkDataSetSurfaceFilter()
        geom_filter.SetInput(grid)
        geom_filter.Update()
        boundary_faces = vtk.vtkPolyData()
        boundary_faces = geom_filter.GetOutput()
        point_to_cell_data = vtk.vtkPointDataToCellData()
        point_to_cell_data.SetInput(geom_filter.GetOutput())
        point_to_cell_data.Update()

        # get mean velocity field on boundary surface
        uF_read = VN.vtk_to_numpy(
            point_to_cell_data.GetOutput().GetCellData().GetVectors("u"))
        uF[:, 0] = uF_read[:, 0]
        vF[:, 0] = uF_read[:, 1]
        wF[:, 0] = uF_read[:, 2]

        # get mean derivative velocity field on boundary surface
        dudxF_read = VN.vtk_to_numpy(
            point_to_cell_data.GetOutput().GetCellData().GetTensors())
        dudxF[:, 0] = dudxF_read[:, 0]
        dvdxF[:, 0] = dudxF_read[:, 1]
        dwdxF[:, 0] = dudxF_read[:, 2]
        dudyF[:, 0] = dudxF_read[:, 3]
        dvdyF[:, 0] = dudxF_read[:, 4]
        dwdyF[:, 0] = dudxF_read[:, 5]
        dudzF[:, 0] = dudxF_read[:, 6]
        dvdzF[:, 0] = dudxF_read[:, 7]
        dwdzF[:, 0] = dudxF_read[:, 8]

        # get boundary face normals
        norm_filter = vtk.vtkPolyDataNormals()
        norm_filter.ComputeCellNormalsOn()
        norm_filter.SetInput(boundary_faces)
        norm_filter.Update()
        area_filter = vtk.vtkMeshQuality()
        area_filter.SetQuadQualityMeasureToArea()
        area_filter.SetTriangleQualityMeasureToArea()
        area_filter.SetInput(boundary_faces)
        area_filter.Update()
        for j in range(0, num_boundary_faces):
            area = area_filter.GetOutput().GetCellData().GetArray(
                "Quality").GetComponent(j, 0)
            norm[j, :] = norm_filter.GetOutput().GetCellData().GetNormals(
            ).GetTuple(j)
            norm[j, :] = norm[j, :] * area

    # ..................................................
    # Read modes and spatially differentiate
    for j in range(0, num_modes):
        j_index = j + 1
        filename = pod_mode_dir + '/POD.spatial_mode_' + '%04d' % j_index + '.vtk'
        print '   Reading file ', filename.strip(
        ), 'file number ', j_index, ' of ', num_modes
        reader.SetFileName(filename)
        reader.Update()

        # get mode velocity field within volume
        u_read = VN.vtk_to_numpy(
            reader.GetOutput().GetPointData().GetVectors("u"))
        u[:, j_index] = u_read[:, 0]
        v[:, j_index] = u_read[:, 1]
        w[:, j_index] = u_read[:, 2]

        # get mode velocity derivative fields within volume
        grid.GetPointData().SetVectors(
            reader.GetOutput().GetPointData().GetVectors("u"))
        differentiator.SetInput(grid)
        differentiator.Update()
        cell_to_point_data.SetInput(differentiator.GetOutput())
        cell_to_point_data.Update()
        grid.GetPointData().SetTensors(
            cell_to_point_data.GetOutput().GetPointData().GetTensors())
        dudx_read = VN.vtk_to_numpy(
            cell_to_point_data.GetOutput().GetPointData().GetTensors())
        dudx[:, j_index] = dudx_read[:, 0]
        dvdx[:, j_index] = dudx_read[:, 1]
        dwdx[:, j_index] = dudx_read[:, 2]
        dudy[:, j_index] = dudx_read[:, 3]
        dvdy[:, j_index] = dudx_read[:, 4]
        dwdy[:, j_index] = dudx_read[:, 5]
        dudz[:, j_index] = dudx_read[:, 6]
        dvdz[:, j_index] = dudx_read[:, 7]
        dwdz[:, j_index] = dudx_read[:, 8]

        # extract boundary surface data
        if ((calibrate_coefficients == "none")
                or (calibrate_coefficients == "constant")):
            geom_filter.SetInput(grid)
            geom_filter.Update()
            boundary_faces = geom_filter.GetOutput()
            point_to_cell_data.SetInput(geom_filter.GetOutput())
            point_to_cell_data.Update()

            # get mode velocity field on boundary surface
            uF_read = VN.vtk_to_numpy(
                point_to_cell_data.GetOutput().GetCellData().GetVectors("u"))
            uF[:, j_index] = uF_read[:, 0]
            vF[:, j_index] = uF_read[:, 1]
            wF[:, j_index] = uF_read[:, 2]

            # get mean derivative velocity field on boundary surface
            dudxF_read = VN.vtk_to_numpy(
                point_to_cell_data.GetOutput().GetCellData().GetTensors())
            dudxF[:, j_index] = dudxF_read[:, 0]
            dvdxF[:, j_index] = dudxF_read[:, 1]
            dwdxF[:, j_index] = dudxF_read[:, 2]
            dudyF[:, j_index] = dudxF_read[:, 3]
            dvdyF[:, j_index] = dudxF_read[:, 4]
            dwdyF[:, j_index] = dudxF_read[:, 5]
            dudzF[:, j_index] = dudxF_read[:, 6]
            dvdzF[:, j_index] = dudxF_read[:, 7]
            dwdzF[:, j_index] = dudxF_read[:, 8]

    # ..................................................
    # zero appropriate coefficients
    if (num_dimensions < 3):
        dudz[:, :] = 0.0
        dvdz[:, :] = 0.0
        dwdz[:, :] = 0.0
    if (num_dimensions < 2):
        dudy[:, :] = 0.0
        dvdy[:, :] = 0.0
        dwdy[:, :] = 0.0
    if (num_components < 3):
        w[:, :] = 0.0
        dwdx[:, :] = 0.0
        dwdy[:, :] = 0.0
        dwdz[:, :] = 0.0
    if (num_components < 2):
        v[:, :] = 0.0
        dvdx[:, :] = 0.0
        dvdy[:, :] = 0.0
        dvdz[:, :] = 0.0
    if ((calibrate_coefficients == "none")
            or (calibrate_coefficients == "constant")):
        if (num_dimensions < 3):
            dudzF[:, :] = 0.0
            dvdzF[:, :] = 0.0
            dwdzF[:, :] = 0.0
        if (num_dimensions < 2):
            dudyF[:, :] = 0.0
            dvdyF[:, :] = 0.0
            dwdyF[:, :] = 0.0
        if (num_components < 3):
            wF[:, j_index] = 0.0
            dwdxF[:, :] = 0.0
            dwdyF[:, :] = 0.0
            dwdzF[:, :] = 0.0
        if (num_components < 2):
            vF[:, :] = 0.0
            dvdxF[:, :] = 0.0
            dvdyF[:, :] = 0.0
            dvdzF[:, :] = 0.0
Ejemplo n.º 19
0
    def deformableRegistration(self):
        """
        Performs deformable image registration on images reconstructed from polygonal surfaces at a user-specified precision.
        If **animate** parameter is *True*, this also spawns a VTK interative rendering that can animate the deformation. 

        Returns
        -------
        cell_fields
        """
        for r, mesh in enumerate(self.rmeshes):
            print(("Performing deformable image registration for object {:d}"
                  .format(r + 1)))
            rimg, dimg, rpoly = self._poly2img(r)
            origin = rimg.GetOrigin()
            rimg.SetOrigin((0, 0, 0))
            dimg.SetOrigin((0, 0, 0))

            steplength = np.min(dimg.GetSpacing()) * 5.0
            rimg = sitk.AntiAliasBinary(rimg)
            dimg = sitk.AntiAliasBinary(dimg)

            #peform the deformable registration
            register = sitk.FastSymmetricForcesDemonsRegistrationFilter()
            register.SetNumberOfIterations(
                self.deformableSettings['Iterations'])
            register.SetMaximumRMSError(self.deformableSettings['Maximum RMS'])
            register.SmoothDisplacementFieldOn()
            register.SetStandardDeviations(
                self.deformableSettings['Displacement Smoothing'])
            register.SmoothUpdateFieldOff()
            register.UseImageSpacingOn()
            register.SetMaximumUpdateStepLength(steplength)
            register.SetUseGradientType(0)
            disp_field = register.Execute(rimg, dimg)
            print(("...Elapsed iterations: {:d}"
                  .format(register.GetElapsedIterations())))
            print(("...Change in RMS error: {:6.3f}"
                  .format(register.GetRMSChange())))

            disp_field.SetOrigin(origin)

            #translate displacement field to VTK regular grid
            a = sitk.GetArrayFromImage(disp_field)
            disp = vtk.vtkImageData()
            disp.SetOrigin(disp_field.GetOrigin())
            disp.SetSpacing(disp_field.GetSpacing())
            disp.SetDimensions(disp_field.GetSize())
            arr = numpy_to_vtk(a.ravel(), deep=True, array_type=vtk.VTK_DOUBLE)
            arr.SetNumberOfComponents(3)
            arr.SetName("Displacement")
            disp.GetPointData().SetVectors(arr)

            #calculate the strain from displacement field
            getStrain = vtk.vtkCellDerivatives()
            getStrain.SetInputData(disp)
            getStrain.SetTensorModeToComputeStrain()
            getStrain.Update()
            #add the strain tensor to the displacement field structured grid
            strains = getStrain.GetOutput()
            c2p = vtk.vtkCellDataToPointData()
            c2p.PassCellDataOff()
            c2p.SetInputData(strains)
            c2p.Update()
            disp = c2p.GetOutput()

            #use VTK probe filter to interpolate displacements and strains
            #to 3D meshes of cells and save as UnstructuredGrid (.vtu)
            # to visualize in ParaView; this is a linear interpolation
            print("...Interpolating displacements to 3D mesh.")
            if self.rigidInitial:
                #transform 3D Mesh
                tf = vtk.vtkTransformFilter()
                tf.SetInputData(mesh)
                tf.SetTransform(self.rigidTransforms[r])
                tf.Update()
                mesh = tf.GetOutput()
            probe = vtk.vtkProbeFilter()
            probe.SetInputData(mesh)
            probe.SetSourceData(disp)
            probe.Update()
            field = probe.GetOutput()
            if self.display:
                probe2 = vtk.vtkProbeFilter()
                probe2.SetInputData(rpoly)
                probe2.SetSourceData(disp)
                probe2.Update()

            self.cell_fields.append(field)
            if self.saveFEA:
                idisp = field.GetPointData().GetVectors()
                bcs = np.zeros((len(self._snodes[r]), 3), float)
                for j, node in enumerate(self._snodes[r]):
                    d = idisp.GetTuple3(node - 1)
                    bcs[j, 0] = d[0]
                    bcs[j, 1] = d[1]
                    bcs[j, 2] = d[2]
                self._bcs.append(bcs)
            idWriter = vtk.vtkXMLUnstructuredGridWriter()
            idWriter.SetFileName(
                str(os.path.normpath(self._def_dir + os.sep +
                                     'cell{:04d}.vtu'.format(r + 1))))
            idWriter.SetInputData(self.cell_fields[r])
            idWriter.Write()
            if self.display:
                self.animate(probe2.GetOutput(), r)
        print("Registration completed.")
Ejemplo n.º 20
0
        locals()[get_variable_name("", cell, "Scalar")].SetValue(i, 0)
        i = i + 1

    locals()[get_variable_name("", cell, "Scalar")].SetValue(0, 4)
    locals()[get_variable_name("", cell, "Grid")].GetPointData().SetScalars(
        locals()[get_variable_name("", cell, "Scalar")])

    pass
# write to the temp directory if possible, otherwise use .
dir = "."
if (info.commands(globals(), locals(), "rtTester") == "rtTester"):
    dir = rtTester.GetTempDirectory()
    pass
for cell in "aVoxel aHexahedron aWedge aPyramid aTetra  aQuad aTriangle aTriangleStrip aLine  aPolyLine aVertex aPolyVertex aPixel aPolygon aPenta aHexa".split(
):
    locals()[get_variable_name("", cell, "derivs")] = vtk.vtkCellDerivatives()
    locals()[get_variable_name("", cell, "derivs")].SetInputData(
        locals()[get_variable_name("", cell, "Grid")])
    locals()[get_variable_name("", cell,
                               "derivs")].SetVectorModeToComputeGradient()
    FileName = dir
    FileName += cell
    FileName += ".vtk"
    # make sure the directory is writeable first
    if (catch.catch(
            globals(),
            """channel = open("" + str(dir) + "/test.tmp", "w")""") == 0):
        channel.close()
        file.delete("-force", "" + str(dir) + "/test.tmp")
        locals()[get_variable_name(
            "", cell, "Writer")] = vtk.vtkUnstructuredGridWriter()
Ejemplo n.º 21
0
def main(argv):
    try:
        opts, args = getopt.getopt(argv,"hi:o:x:a:y:b:z:c:d:u:", ["ifile=","ofile=","sx=","ex=","sy=","ez=","dataset=","comp="])
    except getopt.GetoptError as err:
        print 'getmultithresh.py -i <inputfile.h5> -o <outputfile.vti> -sx -ex -sy -ey -sz -ez -dataset -comptype'
        print (str(err))
    for opt, arg in opts:
        if opt == '-h':
            print 'getmultithresh.py -i <inputfile.h5> -o <outputfile.vti> -sx -ex -sy -ey -sz -ez -dataset'
            sys.exit()
        elif opt in ("-i", "--ifile"):
            inputfile = arg
        elif opt in ("-o", "--ofile"):
            outputfile = arg
        elif opt in ("-x", "--sx"):
            sx = int(arg)
        elif opt in ("-a", "--ex"):
            ex = int(arg)
        elif opt in ("-y", "--sy"):
            sy = int(arg)
        elif opt in ("-b", "--ey"):
            ey = int(arg)
        elif opt in ("-z", "--sz"):
            sz = int(arg)
        elif opt in ("-c", "--ez"):
            ez = int(arg)
        elif opt in ("-d", "--dataset"):
            dataset = str(arg)
        elif opt in ("-u", "--du"):
            comptype = str(arg)
    print ("Loading file, %s" % inputfile)
    #Determine if file is h5 or numpy
    if (inputfile.split(".")[1] == "npy"):
        rs = timeit.default_timer()
        vel = np.load(inputfile)
        re = timeit.default_timer()
    else:
        #read in file
        rs = timeit.default_timer()
        data_file = h5py.File(inputfile, 'r')
        vel = np.array(data_file[dataset])
        data_file.close()
        re = timeit.default_timer()

    cs = timeit.default_timer()
    #convert numpy array to vtk
    vtkdata = numpy_support.numpy_to_vtk(vel.flat, deep=True, array_type=vtk.VTK_FLOAT)
    vtkdata.SetNumberOfComponents(3)
    vtkdata.SetName("Velocity")
    image = vtk.vtkImageData()
    image.GetPointData().SetVectors(vtkdata)
    image.SetExtent(sx,ex,sy,ey,sz,ez)
    #NOTE: Hardcoding Spacing

    image.SetSpacing(.006135923, .006135923, .006135923)
    print ("Doing computation")
    ce = timeit.default_timer()
    vs = timeit.default_timer()
    ve = timeit.default_timer()
    print ("Generating contour")
    ms = timeit.default_timer()
    mag = vtk.vtkImageMagnitude()

    for x in range (0,1):
        start = timeit.default_timer()
        threshold = (22.39 * (2.5))
        if (comptype == "q"):
            threshold= (783.3)
            vort = vtk.vtkGradientFilter()
            vort.SetInputData(image)
            vort.SetInputScalars(image.FIELD_ASSOCIATION_POINTS,"Velocity")
            vort.ComputeQCriterionOn()
            vort.Update()
            image.GetPointData().SetScalars(vort.GetOutput().GetPointData().GetVectors("Q-criterion"))
        else:
            v = vtk.vtkCellDerivatives()
            v.SetVectorModeToComputeVorticity()
            v.SetTensorModeToPassTensors()
            v.SetInputData(image)
            v.Update()
            vort = vtk.vtkImageMagnitude()
            cp = vtk.vtkCellDataToPointData()
            cp.SetInputData(v.GetOutput())
            cp.Update()
            image.GetPointData().SetScalars(cp.GetOutput().GetPointData().GetVectors())
            vort.SetInputData(image)
            vort.Update()
        #ni = vtk.vtkImageData()
        #ni.SetSpacing(.006135923, .006135923, .006135923)
        #ni.SetExtent(sx,ex,sy,ey,sz,ez)
        #ni.GetPointData().SetScalars(q.GetOutput().GetPointData().GetVectors("Q-criterion"))
        mend = timeit.default_timer()
        me = mend
        comptime = mend-start
        print("Magnitude Computation time: " + str(comptime) + "s")
        c = vtk.vtkContourFilter()
        c.SetValue(0,threshold)
        if (comptype == "q"):
            c.SetInputData(image)
        else:
            c.SetInputData(vort.GetOutput())
            
        print("Computing Contour with threshold", threshold)
        c.Update()
        w = vtk.vtkXMLPolyDataWriter()
        w.SetEncodeAppendedData(0) #turn of base 64 encoding for fast write
        w.SetFileName(outputfile + str(x) + ".vtp	")
        w.SetInputData(c.GetOutput())
        ws = timeit.default_timer()
        w.Write()
        we = timeit.default_timer()
         
        print("Results:")
        print("Read time: %s" % str(re-rs))
        print ("Convert to vtk: %s" % str(ce-cs))
        if (comptype == "q"):
            print ("Q Computation: %s" % str(ve-vs))
            print ("Q Magnitude: %s" % str(me-ms))
        else:
            print ("Vorticity Computation: %s" % str(ve-vs))
            print ("Vorticity Magnitude: %s" % str(me-ms))
        #print ("Threshold: %s" % str(te-ts))
        print ("Write %s" % str(we-ws))
        print ("Total time: %s" % str(we-rs))
Ejemplo n.º 22
0
    i = 0
    while i < N:
        locals()[get_variable_name("", cell, "Scalar")].SetValue(i,0)
        i = i + 1

    locals()[get_variable_name("", cell, "Scalar")].SetValue(0,4)
    locals()[get_variable_name("", cell, "Grid")].GetPointData().SetScalars(locals()[get_variable_name("", cell, "Scalar")])

    pass
# write to the temp directory if possible, otherwise use .
dir = "."
if (info.commands(globals(), locals(),  "rtTester") == "rtTester"):
    dir = rtTester.GetTempDirectory()
    pass
for cell in "aVoxel aHexahedron aWedge aPyramid aTetra  aQuad aTriangle aTriangleStrip aLine  aPolyLine aVertex aPolyVertex aPixel aPolygon aPenta aHexa".split():
    locals()[get_variable_name("", cell, "derivs")] = vtk.vtkCellDerivatives()
    locals()[get_variable_name("", cell, "derivs")].SetInputData(locals()[get_variable_name("", cell, "Grid")])
    locals()[get_variable_name("", cell, "derivs")].SetVectorModeToComputeGradient()
    FileName = dir
    FileName += cell
    FileName += ".vtk"
    # make sure the directory is writeable first
    if (catch.catch(globals(),"""channel = open("" + str(dir) + "/test.tmp", "w")""") == 0):
        channel.close()
        file.delete("-force", "" + str(dir) + "/test.tmp")
        locals()[get_variable_name("", cell, "Writer")] = vtk.vtkUnstructuredGridWriter()
        locals()[get_variable_name("", cell, "Writer")].SetInputConnection(locals()[get_variable_name("", cell, "derivs")].GetOutputPort())
        locals()[get_variable_name("", cell, "Writer")].SetFileName(FileName)
        locals()[get_variable_name("", cell, "Writer")].Write()
        # delete the file
        file.delete("-force", FileName)
Ejemplo n.º 23
0
import vtk
print vtk.VTK_VERSION
r = vtk.vtkXMLImageDataReader()
r.SetFileName("iso0_67.vti")
r.Update()

image = r.GetOutput()

vorticity = vtk.vtkCellDerivatives()
vorticity.SetVectorModeToComputeVorticity()
vorticity.SetTensorModeToPassTensors()

vorticity.SetInputData(image)
vorticity.Update()
mag = vtk.vtkImageMagnitude()
cp = vtk.vtkCellDataToPointData()
cp.SetInputData(vorticity.GetOutput())

cp.Update()
image.GetPointData().SetScalars(cp.GetOutput().GetPointData().GetVectors())
mag.SetInputData(image)
mag.Update()

#Remove velocity field
#m = mag.GetOutput()
#m.GetPointData().RemoveArray("Velocity")

t = vtk.vtkImageThreshold()
t.SetInputData(mag.GetOutput())
t.SetInputArrayToProcess(0, 0, 0,
                         mag.GetOutput().FIELD_ASSOCIATION_POINTS, "Magnitude")
Ejemplo n.º 24
0
    def getvtkimage(self, webargs, timestep):
        #Setup query
        DBSTRING = os.environ['db_connection_string']
        conn = pyodbc.connect(DBSTRING, autocommit=True)
        cursor = conn.cursor()
        #url = "http://localhost:8000/cutout/getcutout/"+ token + "/" + dataset + "/" + datafield + "/" + ts + "," +te + "/" + xs + "," + xe +"/" + ys + "," + ye +"/" + zs + "," + ze
        w = webargs.split("/")
        ts = int(w[3].split(',')[0])
        te = int(w[3].split(',')[1])
        xs = int(w[4].split(',')[0])
        xe = int(w[4].split(',')[1])
        ys = int(w[5].split(',')[0])
        ye = int(w[5].split(',')[1])
        zs = int(w[6].split(',')[0])
        ze = int(w[6].split(',')[1])
        extent = (xs, ys, zs, xe, ye, ze)
        overlap = 2 #Used only on contours--vorticity and Q-criterion
        #Look for step parameters
        if (len(w) > 9):
            step = True;
	    s = w[8].split(",")
            tstep = s[0]
            xstep = float(s[1])
            ystep = float(s[2])
            zstep = float(s[3])
            filterwidth = w[9]
        else:
            step = False;
            xstep = 1
            ystep = 1
            zstep = 1
            filterwidth = 1
        cfieldlist = w[2].split(",")
        firstval = cfieldlist[0]    
        maxrange = self.getmaxrange(w[1])     
        if ((firstval == 'vo') or (firstval == 'qc') or (firstval == 'cvo') or (firstval == 'qcc')):
            component = 'u'
            computation = firstval #We are doing a computation, so we need to know which one.
            #check to see if we have a threshold (only for contours)
            if (len(cfieldlist) > 1):
                threshold = float(cfieldlist[1])
            else:
                threshold = .6
            #New:  We need an expanded cutout if contouring.  Push the cutout out by 2 in all directions (unless at boundary).
            if ((firstval == 'cvo') or (firstval == 'qcc')):
                newextent = self.expandcutout(extent, maxrange[0], maxrange[1], maxrange[2], overlap)
                contour = True                
        else:
            component = w[2] #There could be multiple components, so we will have to loop
            computation = ''
        #Split component into list and add them to the image

        #Check to see if we have a value for vorticity or q contour
        fieldlist = list(component)

        for field in fieldlist:
            print("Field = %s" % field)
            cursor.execute("{CALL turbdev.dbo.GetAnyCutout(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}",w[1], field, timestep, extent[0], extent[1], extent[2], xstep, ystep, zstep, 1,1,extent[3], extent[4], extent[5],filterwidth,1)
            #If data spans across multiple servers, we get multiple sets, so concatenate them.
            row = cursor.fetchone()
            raw = row[0]
            part = 0            
            print ("First part size is %d" % len(row[0]))
            while(cursor.nextset()):           
                row = cursor.fetchone()
                raw = raw + row[0]
                part = part +1
                print ("added part %d" % part)
                print ("Part size is %d" % len(row[0]))
            print ("Raw size is %d" % len(raw))
            data = np.frombuffer(raw, dtype=np.float32)
            conn.close()
            vtkdata = numpy_support.numpy_to_vtk(data, deep=True, array_type=vtk.VTK_FLOAT)
            components = self.numcomponents(field)
            vtkdata.SetNumberOfComponents(components)
            vtkdata.SetName(self.componentname(field))
            image = vtk.vtkImageData()
            if (step):
                xes = int(extent[3])/int(xstep)-1
                yes = int(extent[4])/int(ystep)-1
                zes = int(extent[5])/int(zstep)-1
                image.SetExtent(extent[0], extent[0]+extent[3], extent[1], extent[1]+extent[4], extent[2], extenet[2]+extenet[5])
                print("Step extent=" +str(xes))
                print("xs=" + str(xstep) + " ys = "+ str(ystep) +" zs = " + str(zstep))
            else:
                image.SetExtent(extent[0], extent[0]+extent[3]-1, extent[1], extent[1]+extent[4]-1, extent[2], extent[2]+extent[5]-1)
            image.GetPointData().SetVectors(vtkdata)

            if (step): #Magnify to original size
                image.SetSpacing(xstep,ystep,zstep)

        #Check if we need a rectilinear grid, and set it up if so.
        if (w[1] == 'channel'):
            ygrid = self.getygrid()
            #print("Ygrid: ")
            #print (ygrid)
            rg = vtk.vtkRectilinearGrid()
            #Not sure about contouring channel yet, so we are going back to original variables at this point.
            rg.SetExtent(xs, xs+xe-1, ys, ys+ye-1, zs, zs+ze-1)
            rg.GetPointData().SetVectors(vtkdata)

            xg = np.arange(float(xs),float(xe))
            zg = np.arange(float(zs),float(ze))
            for x in xg:
                    xg[x] = 8*3.141592654/2048*x
            for z in zg:
                    zg[z] = 3*3.141592654/2048*z
            vtkxgrid=numpy_support.numpy_to_vtk(xg, deep=True,
                array_type=vtk.VTK_FLOAT)
            vtkzgrid=numpy_support.numpy_to_vtk(zg, deep=True,
                array_type=vtk.VTK_FLOAT)
            vtkygrid=numpy_support.numpy_to_vtk(ygrid,
                deep=True, array_type=vtk.VTK_FLOAT)
            rg.SetXCoordinates(vtkxgrid)
            rg.SetZCoordinates(vtkzgrid)
            rg.SetYCoordinates(vtkygrid)
            image = rg #we rewrite the image since we may be doing a
                       #computation below
        #See if we are doing a computation
        if (computation == 'vo'):
            vorticity = vtk.vtkCellDerivatives()
            vorticity.SetVectorModeToComputeVorticity()
            vorticity.SetTensorModeToPassTensors()
            vorticity.SetInputData(image)
            print("Computing Vorticity")
            vorticity.Update()
        elif (computation == 'cvo'):
            vorticity = vtk.vtkCellDerivatives()
            vorticity.SetVectorModeToComputeVorticity()
            vorticity.SetTensorModeToPassTensors()
            vorticity.SetInputData(image)
            print("Computing Voricity")
            vorticity.Update()
            mag = vtk.vtkImageMagnitude()
            cp = vtk.vtkCellDataToPointData()
            cp.SetInputData(vorticity.GetOutput())
            print("Computing magnitude")
            cp.Update()
            image.GetPointData().SetScalars(cp.GetOutput().GetPointData().GetVectors())
            mag.SetInputData(image)
            mag.Update()
            c = vtk.vtkContourFilter()
            c.SetValue(0,threshold)
            c.SetInputData(mag.GetOutput())
            print("Computing Contour")
            c.Update()
            #Now we need to clip out the overlap
            box = vtk.vtkBox()    
            #set box to requested size
            box.SetBounds(xs, xs+xe-1, ys, ys+ye-1, zs,zs+ze-1)
            clip = vtk.vtkClipPolyData()       
            clip.SetClipFunction(box)
            clip.GenerateClippedOutputOn()
            clip.SetInputData(c.GetOutput())
            clip.InsideOutOn()
            clip.Update()
            cropdata = clip.GetOutput()
            return cropdata

        elif (computation == 'qcc'):
            q = vtk.vtkGradientFilter()
            q.SetInputData(image)
            q.SetInputScalars(image.FIELD_ASSOCIATION_POINTS,"Velocity")
            q.ComputeQCriterionOn()
            q.Update()
            #newimage = vtk.vtkImageData()
            image.GetPointData().SetScalars(q.GetOutput().GetPointData().GetVectors("Q-criterion"))
            mag = vtk.vtkImageMagnitude()
            mag.SetInputData(image)
            mag.Update()
            c = vtk.vtkContourFilter()
            c.SetValue(0,threshold)
            c.SetInputData(mag.GetOutput())
            c.Update()
            #clip out the overlap here
            box = vtk.vtkBox()    
            #set box to requested size
            box.SetBounds(xs, xs+xe-1, ys, ys+ye-1, zs,zs+ze-1)
            clip = vtk.vtkClipPolyData()       
            clip.SetClipFunction(box)
            clip.GenerateClippedOutputOn()
            clip.SetInputData(c.GetOutput())
            clip.InsideOutOn()
            clip.Update()
            cropdata = clip.GetOutput()
            return cropdata
        else:
            return image
Ejemplo n.º 25
0
    def getvtkdata(self, ci, timestep):
        PI= 3.141592654
        contour=False
        firstval = ci.datafields.split(',')[0]
        #print ("First: ", firstval)
        if ((firstval == 'vo') or (firstval == 'qc') or (firstval == 'cvo') or (firstval == 'pcvo') or (firstval == 'qcc')):
            datafields = 'u'
            computation = firstval #We are doing a computation, so we need to know which one.
            if ((firstval == 'cvo') or (firstval == 'qcc') or (firstval == 'pcvo')):
                overlap = 3 #This was 2, but due to rounding because of the spacing, 3 is required.
                #Save a copy of the original request
                oci = jhtdblib.CutoutInfo()
                oci.xstart = ci.xstart
                oci.ystart = ci.ystart
                oci.zstart = ci.zstart
                oci.xlen = ci.xlen
                oci.ylen = ci.ylen
                oci.zlen = ci.zlen
                ci = self.expandcutout(ci, overlap) #Expand the cutout by the overlap
                contour = True               
        else:
            datafields = ci.datafields.split(',') #There could be multiple components, so we will have to loop
            computation = ''
        #Split component into list and add them to the image

        #Check to see if we have a value for vorticity or q contour
        fieldlist = list(datafields)
        image = vtk.vtkImageData()
        rg = vtk.vtkRectilinearGrid()              
        for field in fieldlist:
            if (ci.xlen > 61 and ci.ylen > +61 and ci.zlen > 61 and ci.xstep ==1 and ci.ystep ==1 and ci.zstep ==1 and not contour):
                #Do this if cutout is too large
                #Note: we don't want to get cubed data if we are doing cubes for contouring.
                data=GetData().getcubedrawdata(ci, timestep, field)
            else:
                data=GetData().getrawdata(ci, timestep, field)                  
            vtkdata = numpy_support.numpy_to_vtk(data.flat, deep=True, array_type=vtk.VTK_FLOAT)            
            components = Datafield.objects.get(shortname=field).components
            vtkdata.SetNumberOfComponents(components)
            vtkdata.SetName(Datafield.objects.get(shortname=field).longname)  
            
            #We need to see if we need to subtract one on end of extent edges.
            image.SetExtent(ci.xstart, ci.xstart+((ci.xlen+ci.xstep-1)/ci.xstep)-1, ci.ystart, ci.ystart+((ci.ylen+ci.ystep-1)/ci.ystep)-1, ci.zstart, ci.zstart+((ci.zlen+ci.zstep-1)/ci.zstep)-1)
            #image.SetExtent(ci.xstart, ci.xstart+int(ci.xlen)-1, ci.ystart, ci.ystart+int(ci.ylen)-1, ci.zstart, ci.zstart+int(ci.zlen)-1)
            image.GetPointData().AddArray(vtkdata)
            if (Datafield.objects.get(shortname=field).longname == "Velocity"):
                #Set the Velocity Array as vectors in the image.
                image.GetPointData().SetVectors(image.GetPointData().GetArray("Velocity"))
#Get spacing from database and multiply it by the step.  Don't do this on the contour--it is performed later on.
            #if (contour):
                #We need to scale the threshold to the spacing of the dataset.  This is because we build the cubes
                #on a 1 spacing cube in order to get proper overlap on the contours.  
                #ci.threshold = ci.threshold*Dataset.objects.get(dbname_text=ci.dataset).xspacing
            #else:
            xspacing = Dataset.objects.get(dbname_text=ci.dataset).xspacing
            yspacing = Dataset.objects.get(dbname_text=ci.dataset).yspacing
            zspacing = Dataset.objects.get(dbname_text=ci.dataset).zspacing  


            #Check if we need a rectilinear grid, and set it up if so.
            if (ci.dataset == 'channel'):
                ygrid = jhtdblib.JHTDBLib().getygrid()
                #print("Ygrid: ")
                #print (ygrid)                
                #Not sure about contouring channel yet, so we are going back to original variables at this point.
                rg.SetExtent(ci.xstart, ci.xstart+((ci.xlen+ci.xstep-1)/ci.xstep)-1, ci.ystart, ci.ystart+((ci.ylen+ci.ystep-1)/ci.ystep)-1, ci.zstart, ci.zstart+((ci.zlen+ci.zstep-1)/ci.zstep)-1)
                #components = Datafield.objects.get(shortname=field).components
                #vtkdata.SetNumberOfComponents(components)
                #vtkdata.SetName(Datafield.objects.get(shortname=field).longname)
                rg.GetPointData().AddArray(vtkdata)
                #import pdb;pdb.set_trace()
                #This isn't possible--we will have to do something about this in the future.
                #rg.SetSpacing(ci.xstep,ci.ystep,ci.zstep)
                xg = np.arange(0,2047.0)
                zg = np.arange(0,1535.0)
                for x in xg:
                        xg[x] = 8*PI/2048*x
                for z in zg:
                        zg[z] = 3*PI/2048*z
                vtkxgrid=numpy_support.numpy_to_vtk(xg, deep=True,
                    array_type=vtk.VTK_FLOAT)
                vtkzgrid=numpy_support.numpy_to_vtk(zg, deep=True,
                    array_type=vtk.VTK_FLOAT)
                vtkygrid=numpy_support.numpy_to_vtk(ygrid,
                    deep=True, array_type=vtk.VTK_FLOAT)
                rg.SetXCoordinates(vtkxgrid)
                rg.SetZCoordinates(vtkzgrid)
                rg.SetYCoordinates(vtkygrid)
                image = rg #we rewrite the image since we may be doing a
                           #computation below
            else:
                image.SetSpacing(xspacing*ci.xstep,yspacing*ci.ystep,zspacing*ci.zstep)
        #See if we are doing a computation
        if (computation == 'vo'):
            start = time.time()
            vorticity = vtk.vtkCellDerivatives()
            vorticity.SetVectorModeToComputeVorticity()
            vorticity.SetTensorModeToPassTensors()
            vorticity.SetInputData(image)
            #print("Computing Vorticity")
            vorticity.Update()
            end = time.time()
            comptime = end-start
            print("Vorticity Computation time: " + str(comptime) + "s")
            return image
        elif (computation == 'cvo' or computation == 'pcvo'):
            start = time.time()
            
            vorticity = vtk.vtkCellDerivatives()
            vorticity.SetVectorModeToComputeVorticity()
            vorticity.SetTensorModeToPassTensors()
            
            vorticity.SetInputData(image)
            #print("Computing Voricity")
            vorticity.Update()
            vend = time.time()
            comptime = vend-start
            print("Vorticity Computation time: " + str(comptime) + "s")
            mag = vtk.vtkImageMagnitude()
            cp = vtk.vtkCellDataToPointData()
            cp.SetInputData(vorticity.GetOutput())
            #print("Computing magnitude")
            cp.Update()
            mend = time.time()
            image.GetPointData().SetScalars(cp.GetOutput().GetPointData().GetVectors())
            mag.SetInputData(image)
            mag.Update()
            comptime = mend-vend
            print("Magnitude Computation time: " + str(comptime) + "s")
            c = vtk.vtkContourFilter()
            c.SetValue(0,ci.threshold)
            c.SetInputData(mag.GetOutput())
            print("Computing Contour with threshold", ci.threshold)
            c.Update()
            cend = time.time()
            comptime = cend-mend
            print("Contour Computation time: " + str(comptime) + "s")
            #Now we need to clip out the overlap
            box = vtk.vtkBox()    
            #set box to requested size
            #The OCI deepcopy didn't seem to work.  Manually taking the overlap again.
            box.SetBounds(oci.xstart*xspacing, (oci.xstart+oci.xlen)*xspacing, oci.ystart*yspacing, (oci.ystart+oci.ylen)*yspacing, oci.zstart*yspacing,(oci.zstart+oci.zlen)*yspacing)
            clip = vtk.vtkClipPolyData()       
            clip.SetClipFunction(box)
            clip.GenerateClippedOutputOn()
            clip.SetInputData(c.GetOutput())
            clip.InsideOutOn()
            clip.Update()
            #import pdb;pdb.set_trace()
            cropdata = clip.GetOutput()
            #Cleanup
            image.ReleaseData()
            #mag.ReleaseData()
            #box.ReleaseData()
            #clip.ReleaseData()
            #image.Delete()
            #box.Delete()
            #vorticity.Delete()
            end = time.time()
            comptime = end-start
            print("Total Computation time: " + str(comptime) + "s")
            #return cropdata
            #We need the output port for appending, so return the clip instead
            return clip

        elif (computation == 'qcc'):
            start = time.time()
            q = vtk.vtkGradientFilter()
            q.SetInputData(image)
            q.SetInputScalars(image.FIELD_ASSOCIATION_POINTS,"Velocity")
            q.ComputeQCriterionOn()
            q.Update()
            image.GetPointData().SetScalars(q.GetOutput().GetPointData().GetVectors("Q-criterion"))
            #mag = vtk.vtkImageMagnitude()
            #mag.SetInputData(image)
            #mag.Update()
            mend = time.time()
            comptime = mend-start
            #print("Magnitude Computation time: " + str(comptime) + "s")
            c = vtk.vtkContourFilter()
            c.SetValue(0,ci.threshold)
            c.SetInputData(image)
            print("Computing Contour with threshold", ci.threshold)
            c.Update()
            cend = time.time()
            comptime = cend-mend
            print("Q Contour Computation time: " + str(comptime) + "s")
            #clip out the overlap here
            box = vtk.vtkBox()    
            #set box to requested size
            box.SetBounds(oci.xstart, oci.xstart+oci.xlen-1, oci.ystart, oci.ystart+oci.ylen-1, oci.zstart,oci.zstart+oci.zlen-1)
            clip = vtk.vtkClipPolyData()       
            clip.SetClipFunction(box)
            clip.GenerateClippedOutputOn()
            clip.SetInputData(c.GetOutput())
            clip.InsideOutOn()
            clip.Update()
            cropdata = clip.GetOutput()
            end = time.time()
            comptime = end-start
            print("Computation time: " + str(comptime) + "s")
            #return cropdata
            return clip
        else:
            return image
def compute_vonMisesStress_for_MV(inputfilename, outputfilename):
	# ======================================================================
	# get system arguments -------------------------------------------------
	# Path to input file and name of the output file
	#inputfilename = sys.argv[1]
	#outputfilename = sys.argv[2]
	
	print " "
	print "=================================================================================================="
	print "=== Execute Python script to analyze MV geometry in order for the HiFlow3-based MVR-Simulation ==="
	print "=================================================================================================="
	print " "
	
	# ======================================================================
	# Read file
	if inputfilename[-4] == 'p':
		reader = vtk.vtkXMLPUnstructuredGridReader()
		reader.SetFileName(inputfilename)
		reader.Update()
	else:
		reader = vtk.vtkXMLUnstructuredGridReader()
		reader.SetFileName(inputfilename)
		reader.Update()
	
	print "Reading input files: DONE."
	
	# ======================================================================
	# Compute displacement vector
	calc = vtk.vtkArrayCalculator()
	calc.SetInput(reader.GetOutput())
	calc.SetAttributeModeToUsePointData()
	calc.AddScalarVariable('x', 'u0', 0)
	calc.AddScalarVariable('y', 'u1', 0)
	calc.AddScalarVariable('z', 'u2', 0)
	calc.SetFunction('x*iHat+y*jHat+z*kHat')
	calc.SetResultArrayName('DisplacementSolutionVector')
	calc.Update()
	
	# ======================================================================
	# Compute strain tensor
	derivative = vtk.vtkCellDerivatives()
	derivative.SetInput(calc.GetOutput())
	derivative.SetTensorModeToComputeStrain()
	derivative.Update()
	
	# ======================================================================
	# Compute von Mises stress
	calc = vtk.vtkArrayCalculator()
	calc.SetInput(derivative.GetOutput())
	calc.SetAttributeModeToUseCellData()
	calc.AddScalarVariable('Strain_0', 'Strain', 0)
	calc.AddScalarVariable('Strain_1', 'Strain', 1)
	calc.AddScalarVariable('Strain_2', 'Strain', 2)
	calc.AddScalarVariable('Strain_3', 'Strain', 3)
	calc.AddScalarVariable('Strain_4', 'Strain', 4)
	calc.AddScalarVariable('Strain_5', 'Strain', 5)
	calc.AddScalarVariable('Strain_6', 'Strain', 6)
	calc.AddScalarVariable('Strain_7', 'Strain', 7)
	calc.AddScalarVariable('Strain_8', 'Strain', 8)
	calc.SetFunction('sqrt( (2*700*Strain_0 + 28466*(Strain_0+Strain_4+Strain_8))^2 + (2*700*Strain_4 + 28466*(Strain_0+Strain_4+Strain_8))^2 + (2*700*Strain_8 + 28466*(Strain_0+Strain_4+Strain_8))^2 - ( (2*700*Strain_0 + 28466*(Strain_0+Strain_4+Strain_8))*(2*700*Strain_4 + 28466*(Strain_0+Strain_4+Strain_8)) ) - ( (2*700*Strain_0 + 28466*(Strain_0+Strain_4+Strain_8))*(2*700*Strain_8 + 28466*(Strain_0+Strain_4+Strain_8)) ) - ( (2*700*Strain_4 + 28466*(Strain_0+Strain_4+Strain_8))*(2*700*Strain_8 + 28466*(Strain_0+Strain_4+Strain_8)) ) + 3 * ((2*700*Strain_3)^2 + (2*700*Strain_6)^2 + (2*700*Strain_7)^2) )')
	calc.SetResultArrayName('vonMisesStress_forMV_mu700_lambda28466')
	calc.Update()
	
	print "Computation of displacement vectors, Cauchy strain and vom Mises stress: DONE."
	
	# ======================================================================
	# Define dummy variable; get output of calc filter
	dummy = calc.GetOutput()
	
	# Get point data arrays u0, u1 and u2
	pointData_u0 = dummy.GetPointData().GetArray('u0')
	pointData_u1 = dummy.GetPointData().GetArray('u1')
	pointData_u2 = dummy.GetPointData().GetArray('u2')
	
	# Set scalars
	dummy.GetPointData().SetScalars(pointData_u0)
	
	# ======================================================================
	# Warp by scalar u0
	warpScalar = vtk.vtkWarpScalar()
	warpScalar.SetInput(dummy)
	warpScalar.SetNormal(1.0,0.0,0.0)
	warpScalar.SetScaleFactor(1.0)
	warpScalar.SetUseNormal(1)
	warpScalar.Update()
	
	# Get output and set scalars
	dummy = warpScalar.GetOutput()
	dummy.GetPointData().SetScalars(pointData_u1)
	
	# ======================================================================
	# Warp by scalar u1
	warpScalar = vtk.vtkWarpScalar()
	warpScalar.SetInput(dummy)
	warpScalar.SetNormal(0.0,1.0,0.0)
	warpScalar.SetScaleFactor(1.0)
	warpScalar.SetUseNormal(1)
	warpScalar.Update()
	
	# Get output and set scalars
	dummy = warpScalar.GetOutput()
	dummy.GetPointData().SetScalars(pointData_u2)
	
	# ======================================================================
	# Warp by scalar u2
	warpScalar = vtk.vtkWarpScalar()
	warpScalar.SetInput(dummy)
	warpScalar.SetNormal(0.0,0.0,1.0)
	warpScalar.SetScaleFactor(1.0)
	warpScalar.SetUseNormal(1)
	warpScalar.Update()
	
	# Get ouput and add point data arrays that got deleted earlier
	dummy = warpScalar.GetOutput()
	dummy.GetPointData().AddArray(pointData_u0)
	dummy.GetPointData().AddArray(pointData_u1)
	
	# ======================================================================
	# Write output to vtu
	writer = vtk.vtkXMLUnstructuredGridWriter()
	writer.SetDataModeToAscii()
	writer.SetFileName(outputfilename)
	writer.SetInput(dummy)
	writer.Write()
	
	# ======================================================================
	print "Writing Extended VTU incl. von Mises Stress information: DONE."
	print "=============================================================="
	print " "
Ejemplo n.º 27
0
import vtk
print vtk.VTK_VERSION
r = vtk.vtkXMLImageDataReader()
r.SetFileName("iso0_67.vti")
r.Update()

image = r.GetOutput()

vorticity = vtk.vtkCellDerivatives()
vorticity.SetVectorModeToComputeVorticity()
vorticity.SetTensorModeToPassTensors()

vorticity.SetInputData(image)
vorticity.Update()
mag = vtk.vtkImageMagnitude()
cp = vtk.vtkCellDataToPointData()
cp.SetInputData(vorticity.GetOutput())

cp.Update()
image.GetPointData().SetScalars(cp.GetOutput().GetPointData().GetVectors())
mag.SetInputData(image)
mag.Update()

#Remove velocity field
#m = mag.GetOutput()
#m.GetPointData().RemoveArray("Velocity")

t = vtk.vtkImageThreshold()
t.SetInputData(mag.GetOutput())
t.SetInputArrayToProcess(0,0,0, mag.GetOutput().FIELD_ASSOCIATION_POINTS, "Magnitude")
#t.ThresholdByUpper(44.79)
def computeStrainsFromDisplacements(
        mesh,
        disp_array_name="displacement",
        ref_mesh=None,
        verbose=0):

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

    myVTK.myPrint(min(verbose,1), "*** Warning: at some point the ordering of vector gradient components has changed, and uses C ordering instead of F. ***")
    if   (vtk.vtkVersion.GetVTKMajorVersion() >= 8):
        ordering = "C"
    elif (vtk.vtkVersion.GetVTKMajorVersion() == 7) and ((vtk.vtkVersion.GetVTKMinorVersion() > 0) or (vtk.vtkVersion.GetVTKBuildVersion() > 0)):
        ordering = "C"
    else:
        ordering = "F"

    n_points = mesh.GetNumberOfPoints()
    n_cells = mesh.GetNumberOfCells()

    assert (mesh.GetPointData().HasArray(disp_array_name))
    mesh.GetPointData().SetActiveVectors(disp_array_name)
    cell_derivatives = vtk.vtkCellDerivatives()
    cell_derivatives.SetVectorModeToPassVectors()
    cell_derivatives.SetTensorModeToComputeGradient()
    if (vtk.vtkVersion.GetVTKMajorVersion() >= 6):
        cell_derivatives.SetInputData(mesh)
    else:
        cell_derivatives.SetInput(mesh)
    cell_derivatives.Update()
    farray_gu = cell_derivatives.GetOutput().GetCellData().GetArray("VectorGradient")

    if (ref_mesh is not None):
        farray_strain = myVTK.createFloatArray(
            name="Strain_CAR",
            n_components=6,
            n_tuples=n_cells)
    else:
        farray_strain = myVTK.createFloatArray(
            name="Strain",
            n_components=6,
            n_tuples=n_cells)
    mesh.GetCellData().AddArray(farray_strain)
    I = numpy.eye(3)
    E_vec = numpy.empty(6)
    #e_vec = numpy.empty(6)
    for k_cell in range(n_cells):
        GU = numpy.reshape(farray_gu.GetTuple(k_cell), (3,3), ordering)
        F = I + GU
        C = numpy.dot(numpy.transpose(F), F)
        E = (C - I)/2
        mat_sym33_to_vec_col6(E, E_vec)
        farray_strain.SetTuple(k_cell, E_vec)
        #if (add_almansi_strain):
            #Finv = numpy.linalg.inv(F)
            #c = numpy.dot(numpy.transpose(Finv), Finv)
            #e = (I - c)/2
            #mat_sym33_to_vec_col6(e, e_vec)
            #farray_almansi.SetTuple(k_cell, e_vec)

    if (ref_mesh is not None) and (ref_mesh.GetCellData().HasArray("eR")) and (ref_mesh.GetCellData().HasArray("eC")) and (ref_mesh.GetCellData().HasArray("eL")):
        farray_strain_cyl = myVTK.rotateMatrix(
            old_array=mesh.GetCellData().GetArray("Strain_CAR"),
            out_vecs=[ref_mesh.GetCellData().GetArray("eR"),
                      ref_mesh.GetCellData().GetArray("eC"),
                      ref_mesh.GetCellData().GetArray("eL")],
            verbose=0)
        farray_strain_cyl.SetName("Strain_CYL")
        mesh.GetCellData().AddArray(farray_strain_cyl)

    if (ref_mesh is not None) and (ref_mesh.GetCellData().HasArray("eRR")) and (ref_mesh.GetCellData().HasArray("eCC")) and (ref_mesh.GetCellData().HasArray("eLL")):
        farray_strain_pps = myVTK.rotateMatrix(
            old_array=mesh.GetCellData().GetArray("Strain_CAR"),
            out_vecs=[ref_mesh.GetCellData().GetArray("eRR"),
                      ref_mesh.GetCellData().GetArray("eCC"),
                      ref_mesh.GetCellData().GetArray("eLL")],
            verbose=0)
        farray_strain_pps.SetName("Strain_PPS")
        mesh.GetCellData().AddArray(farray_strain_pps)
Ejemplo n.º 29
0
def getthresh(args):
    inputfile = args[0] 
    outputfile = args[1]
    sx = args[2]
    ex = args[3]
    sy = args[4]
    ey = args[5]
    sz = args[6]
    ez = args[7]
    dataset = args[8]
    comptype = args[9]
    print ("Loading file, %s" % inputfile)
    #Determine if file is h5 or numpy
    if (inputfile.split(".")[1] == "npy"):
        rs = timeit.default_timer()
        vel = np.load(inputfile)
        re = timeit.default_timer()
    else:
        #read in file
        rs = timeit.default_timer()
        data_file = h5py.File(inputfile, 'r')
        vel = np.array(data_file[dataset])
        data_file.close()
        re = timeit.default_timer()

    cs = timeit.default_timer()
    #convert numpy array to vtk
    vtkdata = numpy_support.numpy_to_vtk(vel.flat, deep=True, array_type=vtk.VTK_FLOAT)
    vtkdata.SetNumberOfComponents(3)
    vtkdata.SetName("Velocity")
    image = vtk.vtkImageData()
    image.GetPointData().SetVectors(vtkdata)
    image.SetExtent(sx,ex,sy,ey,sz,ez)
    #NOTE: Hardcoding Spacing

    image.SetSpacing(.006135923, .006135923, .006135923)
    print ("Doing computation")
    ce = timeit.default_timer()
    vs = timeit.default_timer()
    if (comptype == "v"):
        vorticity = vtk.vtkCellDerivatives()
        vorticity.SetVectorModeToComputeVorticity()
        vorticity.SetTensorModeToPassTensors()
        vorticity.SetInputData(image)
        vorticity.Update()
    elif (comptype == "q"):
        vorticity = vtk.vtkGradientFilter()
        vorticity.SetInputData(image)
        vorticity.SetInputScalars(image.FIELD_ASSOCIATION_POINTS,"Velocity")
        vorticity.ComputeQCriterionOn()
        vorticity.SetComputeGradient(0)
        vorticity.Update()
    ve = timeit.default_timer()
    #Generate contour for comparison
    c = vtk.vtkContourFilter()
    c.SetValue(0,1128)
    if (comptype == "q"):
        image.GetPointData().SetScalars(vorticity.GetOutput().GetPointData().GetVectors("Q-criterion"))
    else:
        image.GetPointData().SetScalars(vorticity.GetOutput().GetPointData().GetVectors())
        
    c.SetInputData(image)
    
    c.Update()
    w = vtk.vtkXMLPolyDataWriter()
    w.SetEncodeAppendedData(0) #turn of base 64 encoding for fast write
    w.SetFileName("contour.vtp")
    w.SetInputData(c.GetOutput())
    ws = timeit.default_timer()
    w.Write()


    ms = timeit.default_timer()
    if (comptype == "v"):
        mag = vtk.vtkImageMagnitude()
        cp = vtk.vtkCellDataToPointData()
        cp.SetInputData(vorticity.GetOutput())
        cp.Update()
        image.GetPointData().SetScalars(cp.GetOutput().GetPointData().GetVectors())
        mag.SetInputData(image)
        mag.Update()
        m = mag.GetOutput()
        m.GetPointData().RemoveArray("Velocity")
    else:
        image.GetPointData().SetScalars(vorticity.GetOutput().GetPointData().GetVectors("Q-criterion"))
    me = timeit.default_timer()
    print ("Thresholding.")
    ts = timeit.default_timer()
    t = vtk.vtkImageThreshold()
    #t = vtk.vtkThreshold() #sparse representation

    if (comptype == "q"):
        t.SetInputData(image)
        t.ThresholdByUpper(783.3) #.25*67.17^2 = 1127
        #t.SetInputArrayToProcess(0,0,0, vorticity.GetOutput().FIELD_ASSOCIATION_POINTS, "Q-criterion")
        print("q criterion")
    else:
        t.SetInputData(m)
        t.SetInputArrayToProcess(0,0,0, mag.GetOutput().FIELD_ASSOCIATION_POINTS, "Magnitude")
        t.ThresholdByUpper(44.79) #44.79)
    #Set values in range to 1 and values out of range to 0
    t.SetInValue(1)
    t.SetOutValue(0)
    #t.ReplaceInOn()
    #t.ReplaceOutOn()
    print("Update thresh")
    t.Update()
    #wt = vtk.vtkXMLImageDataWriter()
    #wt.SetInputData(t.GetOutput())
    #wt.SetFileName("thresh.vti")
    #wt.Write()

    d = vtk.vtkImageDilateErode3D()
    d.SetInputData(t.GetOutput())
    d.SetKernelSize(3,3,3)
    d.SetDilateValue(1)
    d.SetErodeValue(0)
    print ("Update dilate")
    d.Update()

    iis = vtk.vtkImageToImageStencil()
    iis.SetInputData(d.GetOutput())
    iis.ThresholdByUpper(1)
    stencil = vtk.vtkImageStencil()
    stencil.SetInputConnection(2, iis.GetOutputPort())
    stencil.SetBackgroundValue(0)
    #image.GetPointData().RemoveArray("Vorticity")
    #Set scalars to velocity so it can be cut by the stencil
    image.GetPointData().SetScalars(image.GetPointData().GetVectors())
    #if (comptype == "q"):  #Use this to get just q-criterion data instead of velocity data.  Do we need both?
    #    image.GetPointData().SetScalars(vorticity.GetOutput().GetPointData().GetScalars("Q-criterion"))
    stencil.SetInputData(image)
    print ("Update stencil")    
    stencil.Update()
    te = timeit.default_timer()
    print("Setting up write")
    ws = timeit.default_timer()
    #Make velocity a vector again
    velarray = stencil.GetOutput().GetPointData().GetScalars()
    image.GetPointData().RemoveArray("Velocity")
    image.GetPointData().SetVectors(velarray)
    w = vtk.vtkXMLImageDataWriter()
    w.SetCompressorTypeToZLib()
    #w.SetCompressorTypeToNone() Need to figure out why this fails.
    w.SetEncodeAppendedData(0) #turn of base 64 encoding for fast write
    w.SetFileName(outputfile)
    w.SetInputData(image)
    if (0):
        w.SetCompressorTypeToZfp()
        w.GetCompressor().SetNx(ex-sx+1)
        w.GetCompressor().SetNy(ey-sy+1)
        w.GetCompressor().SetNz(ez-sz+1)
        w.GetCompressor().SetTolerance(1e-1)
        w.GetCompressor().SetNumComponents(3)

    w.Write()
    we = timeit.default_timer()

    print("Results:")
    print("Read time: %s" % str(re-rs))
    print ("Convert to vtk: %s" % str(ce-cs))
    if (comptype == "q"):
        print ("Q Computation: %s" % str(ve-vs))
        print ("Q Magnitude: %s" % str(me-ms))
    else:
        print ("Vorticity Computation: %s" % str(ve-vs))
        print ("Vorticity Magnitude: %s" % str(me-ms))
    print ("Threshold: %s" % str(te-ts))
    print ("Write %s" % str(we-ws))
    print ("Total time: %s" % str(we-rs))
Ejemplo n.º 30
0
def vortmesh(args):
  
    p = args[0]
    cubenum = args[1]
    print("Cube", cubenum)
    #Check for additonal parameters
    if (p["param1"] != ''):
        comptype = p["param1"]
    else:
        comptype = "q" #Default to q criterion
    if (p["param2"] != ''):
        thresh = float(p["param2"])
    else:
        thresh = 783.3 #Default for q threshold on isotropic data

    inputfile = p["inputfile"] +str(cubenum) + ".npy" #Used so we can set either npy input or h5 input
    outputfile = p["outputfile"] + str(cubenum) + ".vtp" #always VTK Image Data for this.
    sx = p["sx"]
    sy = p["sy"]
    sz = p["sz"]
    ex = p["ex"]
    ey = p["ey"]
    ez = p["ez"]
        
    print ("Loading file, %s" % inputfile)
    #Determine if file is h5 or numpy
    rs = timeit.default_timer()
    #In case file isn't here, catch this.
    try:
        vel = np.load(inputfile)
    except:
        p["message"] = "Failed to find file"
        return p
    re = timeit.default_timer()
    #convert numpy array to vtk
    cs = timeit.default_timer()
    #convert numpy array to vtk
    vtkdata = numpy_support.numpy_to_vtk(vel.flat, deep=True, array_type=vtk.VTK_FLOAT)
    vtkdata.SetNumberOfComponents(3)
    vtkdata.SetName("Velocity")
    image = vtk.vtkImageData()
    image.GetPointData().SetVectors(vtkdata)
    image.SetExtent(sx,ex,sy,ey,sz,ez)
    #NOTE: Hardcoding Spacing TODO: Add to parameters

    image.SetSpacing(.006135923, .006135923, .006135923)
    ce = timeit.default_timer()
    vs = timeit.default_timer()
    if (comptype == "v"):
        vorticity = vtk.vtkCellDerivatives()
        vorticity.SetVectorModeToComputeVorticity()
        vorticity.SetTensorModeToPassTensors()
        vorticity.SetInputData(image)
        vorticity.Update()
    elif (comptype == "q"):
        vorticity = vtk.vtkGradientFilter()
        vorticity.SetInputData(image)
        vorticity.SetInputScalars(image.FIELD_ASSOCIATION_POINTS,"Velocity")
        vorticity.ComputeQCriterionOn()
        vorticity.SetComputeGradient(0)
        vorticity.Update()
    ve = timeit.default_timer()
    #Generate contour for comparison
    c = vtk.vtkContourFilter()
    c.SetValue(0,thresh)
    if (comptype == "q"):
        image.GetPointData().SetScalars(vorticity.GetOutput().GetPointData().GetVectors("Q-criterion"))
    else:
        image.GetPointData().SetScalars(vorticity.GetOutput().GetPointData().GetVectors())
        
    c.SetInputData(image)
    
    c.Update()

    w = vtk.vtkXMLPolyDataWriter()
    w.SetEncodeAppendedData(0) #turn of base 64 encoding for fast write
    w.SetFileName(outputfile)
    w.SetInputData(c.GetOutput())
    ws = timeit.default_timer()
    result = w.Write()
    we = timeit.default_timer()

    print("Read time: %s" % str(re-rs))
    print ("Convert to vtk: %s" % str(ce-cs))
    if (comptype == "q"):
        print ("Q Computation: %s" % str(ve-vs))
    else:
        print ("Vorticity Computation: %s" % str(ve-vs))
    print ("Write %s" % str(we-ws))
    print ("Total time: %s" % str(we-rs))
    if (result):
        p["message"] = "Success"
        p["computetime"] = str(we-rs)
    return p #return the packet
Ejemplo n.º 31
0
def vortvelvolume(args):
    #inputfile, outputfile, sx, ex, sy, ey, sz, ez, dataset):
    p = args[0]
    cubenum = args[1]
    print("Cube", cubenum)
    #Check for additonal parameters
    if (p["param1"] != ''):
        comptype = p["param1"]
    else:
        comptype = "q" #Default to q criterion
    if (p["param2"] != ''):
        thresh = float(p["param2"])
    else:
        thresh = 783.3 #Default for q threshold on isotropic data
    #We use 0 for structured grid (vti) and 1 for unstructured grid (vtu)
    if (p["param3"] != ''):
        grid = 0
    else:
        grid = 1
    if (p["param4"] != ''):
        kernelsize = int(p["param4"])
    else:
        kernelsize = 3
    inputfile = p["inputfile"] +str(cubenum) + ".npy" 
    outputfile = p["outputfile"] + str(cubenum) + ".vti" #always VTK Image Data for this.
    sx = p["sx"]
    sy = p["sy"]
    sz = p["sz"]
    ex = p["ex"]
    ey = p["ey"]
    ez = p["ez"]
        
    print ("Loading file, %s" % inputfile)
    #Determine if file is h5 or numpy
    rs = timeit.default_timer()
    vel = np.load(inputfile)
    re = timeit.default_timer()
    #convert numpy array to vtk
    cs = timeit.default_timer()
    #convert numpy array to vtk
    vtkdata = numpy_support.numpy_to_vtk(vel.flat, deep=True, array_type=vtk.VTK_FLOAT)
    vtkdata.SetNumberOfComponents(3)
    vtkdata.SetName("Velocity")
    image = vtk.vtkImageData()
    image.GetPointData().SetVectors(vtkdata)
    image.SetExtent(sx,ex,sy,ey,sz,ez)
    #NOTE: Hardcoding Spacing

    image.SetSpacing(.006135923, .006135923, .006135923)
    ce = timeit.default_timer()
    vs = timeit.default_timer()
    if (comptype == "v"):
        vorticity = vtk.vtkCellDerivatives()
        vorticity.SetVectorModeToComputeVorticity()
        vorticity.SetTensorModeToPassTensors()
        vorticity.SetInputData(image)
        vorticity.Update()
    elif (comptype == "q"):
        vorticity = vtk.vtkGradientFilter()
        vorticity.SetInputData(image)
        vorticity.SetInputScalars(image.FIELD_ASSOCIATION_POINTS,"Velocity")
        vorticity.ComputeQCriterionOn()
        vorticity.SetComputeGradient(0)
        vorticity.Update()
    ve = timeit.default_timer()

    ms = timeit.default_timer()
    if (comptype == "v"):
        mag = vtk.vtkImageMagnitude()
        cp = vtk.vtkCellDataToPointData()
        cp.SetInputData(vorticity.GetOutput())
        cp.Update()
        image.GetPointData().SetScalars(cp.GetOutput().GetPointData().GetVectors())
        mag.SetInputData(image)
        mag.Update()
        m = mag.GetOutput()
        m.GetPointData().RemoveArray("Velocity")
    else:
        image.GetPointData().SetScalars(vorticity.GetOutput().GetPointData().GetVectors("Q-criterion"))
    me = timeit.default_timer()
    print ("Thresholding.")
    ts = timeit.default_timer()
    t = vtk.vtkImageThreshold()
    #t = vtk.vtkThreshold() #sparse representation

    if (comptype == "q"):
        t.SetInputData(image)
        t.ThresholdByUpper(thresh) #.25*67.17^2 = 1127
        #t.SetInputArrayToProcess(0,0,0, vorticity.GetOutput().FIELD_ASSOCIATION_POINTS, "Q-criterion")
        print("q criterion")
    else:
        t.SetInputData(m)
        t.SetInputArrayToProcess(0,0,0, mag.GetOutput().FIELD_ASSOCIATION_POINTS, "Magnitude")
        t.ThresholdByUpper(thresh) #44.79)
    #Set values in range to 1 and values out of range to 0
    t.SetInValue(1)
    t.SetOutValue(0)
    #t.ReplaceInOn()
    #t.ReplaceOutOn()
    print("Update thresh")
    t.Update()
    #wt = vtk.vtkXMLImageDataWriter()
    #wt.SetInputData(t.GetOutput())
    #wt.SetFileName("thresh.vti")
    #wt.Write()

    d = vtk.vtkImageDilateErode3D()
    d.SetInputData(t.GetOutput())
    d.SetKernelSize(kernelsize,kernelsize,kernelsize)
    d.SetDilateValue(1)
    d.SetErodeValue(0)
    print ("Update dilate")
    d.Update()

    iis = vtk.vtkImageToImageStencil()
    iis.SetInputData(d.GetOutput())
    iis.ThresholdByUpper(1)
    stencil = vtk.vtkImageStencil()
    stencil.SetInputConnection(2, iis.GetOutputPort())
    stencil.SetBackgroundValue(0)
    #image.GetPointData().RemoveArray("Vorticity")
    #Set scalars to velocity so it can be cut by the stencil
    image.GetPointData().SetScalars(image.GetPointData().GetVectors())
    #if (comptype == "q"):  #Use this to get just q-criterion data instead of velocity data.  Do we need both?
    #    image.GetPointData().SetScalars(vorticity.GetOutput().GetPointData().GetScalars("Q-criterion"))
    stencil.SetInputData(image)
    print ("Update stencil")    
    stencil.Update()
    te = timeit.default_timer()
    print("Setting up write")
    ws = timeit.default_timer()
    #Make velocity a vector again
    velarray = stencil.GetOutput().GetPointData().GetScalars()
    image.GetPointData().RemoveArray("Velocity")
    image.GetPointData().SetVectors(velarray)
    if (grid == 0):
        w = vtk.vtkXMLImageDataWriter()
    else:
        w = vtk.vtkXMLUnstructuredGridWriter()
    w.SetCompressorTypeToZLib()
    #w.SetCompressorTypeToNone() Need to figure out why this fails.
    w.SetEncodeAppendedData(0) #turn of base 64 encoding for fast write
    w.SetFileName(outputfile)
    w.SetInputData(image)
    if (0):
        w.SetCompressorTypeToZfp()
        w.GetCompressor().SetNx(ex-sx+1)
        w.GetCompressor().SetNy(ey-sy+1)
        w.GetCompressor().SetNz(ez-sz+1)
        w.GetCompressor().SetTolerance(1e-2)
        w.GetCompressor().SetNumComponents(3)

    result = w.Write()
    result = 1 #don't write for benchmarking
    we = timeit.default_timer()

    print("Results:")
    print("Read time: %s" % str(re-rs))
    print ("Convert to vtk: %s" % str(ce-cs))
    if (comptype == "q"):
        print ("Q Computation: %s" % str(ve-vs))
        print ("Q Magnitude: %s" % str(me-ms))
    else:
        print ("Vorticity Computation: %s" % str(ve-vs))
        print ("Vorticity Magnitude: %s" % str(me-ms))
    print ("Threshold: %s" % str(te-ts))
    print ("Write %s" % str(we-ws))
    print ("Total time: %s" % str(we-rs))
    if (result):
        p["message"] = "Success"
        p["computetime"] = str(we-rs)
    return p #return the packet
Ejemplo n.º 32
0
def vortvelvolumei(args):
    #inputfile, outputfile, sx, ex, sy, ey, sz, ez, dataset):
    p = args[0]
    cubenum = args[1]
    print("Cube", cubenum)
    #Check for additonal parameters
    if (p["param1"] != ''):
        comptype = p["param1"]
    else:
        comptype = "q" #Default to q criterion
    if (p["param2"] != ''):
        thresh = float(p["param2"])
    else:
        thresh = 783.3 #Default for q threshold on isotropic data

    inputfile = p["inputfile"] +str(cubenum) + ".npy" 
    outputfile = p["outputfile"] + str(cubenum) + ".vti" #always VTK Image Data for this.
    sx = p["sx"]
    sy = p["sy"]
    sz = p["sz"]
    ex = p["ex"]
    ey = p["ey"]
    ez = p["ez"]
        
    print ("Loading file, %s" % inputfile)
    #Determine if file is h5 or numpy
    rs = timeit.default_timer()
    vel = np.load(inputfile)
    print ("File Loaded")
    re = timeit.default_timer()
    #convert numpy array to vtk
    cs = timeit.default_timer()
    #convert numpy array to vtk
    vtkdata = numpy_support.numpy_to_vtk(vel.flat, deep=True, array_type=vtk.VTK_FLOAT)
    vtkdata.SetNumberOfComponents(3)
    vtkdata.SetName("Velocity")
    image = vtk.vtkImageData()
    image.GetPointData().SetVectors(vtkdata)
    image.SetExtent(sx,ex,sy,ey,sz,ez)
    #NOTE: Hardcoding Spacing

    image.SetSpacing(.006135923, .006135923, .006135923)
    ce = timeit.default_timer()
    vs = timeit.default_timer()
    print ("Beginning computation: " + comptype)
    if (comptype == "v"):
        vorticity = vtk.vtkCellDerivatives()
        vorticity.SetVectorModeToComputeVorticity()
        vorticity.SetTensorModeToPassTensors()
        vorticity.SetInputData(image)
        vorticity.Update()
    elif (comptype == "q"):
        vorticity = vtk.vtkGradientFilter()
        vorticity.SetInputData(image)
        vorticity.SetInputScalars(image.FIELD_ASSOCIATION_POINTS,"Velocity")
        vorticity.ComputeQCriterionOn()
        vorticity.SetComputeGradient(0)
        vorticity.Update()
    ve = timeit.default_timer()
    print("Initial calculation done")
    ms = timeit.default_timer()
    if (comptype == "v"):
        mag = vtk.vtkImageMagnitude()
        cp = vtk.vtkCellDataToPointData()
        cp.SetInputData(vorticity.GetOutput())
        cp.Update()
        image.GetPointData().SetScalars(cp.GetOutput().GetPointData().GetVectors())
        mag.SetInputData(image)
        mag.Update()
        m = mag.GetOutput()
        m.GetPointData().RemoveArray("Velocity")
    else:
        image.GetPointData().SetScalars(vorticity.GetOutput().GetPointData().GetVectors("Q-criterion"))
    me = timeit.default_timer()
    print("Generating screenshot")
    c = vtk.vtkContourFilter()
    c.SetValue(0,thresh)
    c.SetInputData(image)
    c.Update()
    contour = c.GetOutput()
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputData(contour)
    mapper.ScalarVisibilityOn()
    mapper.SetScalarRange(-1,1)
    mapper.SetScalarModeToUsePointFieldData()
    mapper.ColorByArrayComponent("Velocity", 0)
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    
    ren = vtk.vtkRenderer()
    ren.AddActor(actor)
    ren.SetBackground(1,1,1)
    camera = vtk.vtkCamera()
    ren.SetActiveCamera(camera)
    ren.ResetCamera()
    camera.Zoom(1.5) #This reduces the whitespace around the image

    renWin = vtk.vtkRenderWindow()
    renWin.SetSize(1024,1024)
    renWin.AddRenderer(ren)
    renWin.SetOffScreenRendering(1)

    windowToImageFilter = vtk.vtkWindowToImageFilter()
    windowToImageFilter.SetInput(renWin)
    windowToImageFilter.Update()
    
    w = vtk.vtkPNGWriter()
    pngfilename = p["outputfile"] + str(cubenum) + ".png"
    w.SetFileName(pngfilename)
    w.SetInputConnection(windowToImageFilter.GetOutputPort())
    w.Write()

    #Shift camera angle and take snapshots around the cube.
    for aznum in range(4):
        camera.Azimuth(90)
        windowToImageFilter = vtk.vtkWindowToImageFilter()
        windowToImageFilter.SetInput(renWin)
        windowToImageFilter.Update()
        pngfilename = p["outputfile"] + str(cubenum) + "-r" + str(aznum)+ ".png"
        w.SetFileName(pngfilename)
        w.SetInputConnection(windowToImageFilter.GetOutputPort())
        w.Write()

    camera.Elevation(90) #Rotate camera to top
    windowToImageFilter = vtk.vtkWindowToImageFilter()
    windowToImageFilter.SetInput(renWin)
    windowToImageFilter.Update()
    pngfilename = p["outputfile"] + str(cubenum) + "-t1.png"
    w.SetFileName(pngfilename)
    w.SetInputConnection(windowToImageFilter.GetOutputPort())
    w.Write()

    camera.Elevation(180) #Rotate camera to bottom
    windowToImageFilter = vtk.vtkWindowToImageFilter()
    windowToImageFilter.SetInput(renWin)
    windowToImageFilter.Update()
    pngfilename = p["outputfile"] + str(cubenum) + "-b1.png"
    w.SetFileName(pngfilename)
    w.SetInputConnection(windowToImageFilter.GetOutputPort())
    w.Write()

    print ("Thresholding.")
    ts = timeit.default_timer()
    t = vtk.vtkImageThreshold() #Dense represenation (0's included, structured grid)
    #t = vtk.vtkThreshold() #sparse representation

    if (comptype == "q"):
        t.SetInputData(image)
        t.ThresholdByUpper(thresh) #.25*67.17^2 = 1127
        #t.SetInputArrayToProcess(0,0,0, vorticity.GetOutput().FIELD_ASSOCIATION_POINTS, "Q-criterion")
        print("q criterion")
    else:
        t.SetInputData(m)
        t.SetInputArrayToProcess(0,0,0, mag.GetOutput().FIELD_ASSOCIATION_POINTS, "Magnitude")
        t.ThresholdByUpper(thresh) #44.79)
    #Set values in range to 1 and values out of range to 0
    t.SetInValue(1)
    t.SetOutValue(0)
    #t.ReplaceInOn()
    #t.ReplaceOutOn()
    print("Update thresh")
    t.Update()
    #wt = vtk.vtkXMLImageDataWriter()
    #wt.SetInputData(t.GetOutput())
    #wt.SetFileName("thresh.vti")
    #wt.Write()

    d = vtk.vtkImageDilateErode3D()
    d.SetInputData(t.GetOutput())
    d.SetKernelSize(4,4,4)
    d.SetDilateValue(1)
    d.SetErodeValue(0)
    print ("Update dilate")
    d.Update()

    iis = vtk.vtkImageToImageStencil()
    iis.SetInputData(d.GetOutput())
    iis.ThresholdByUpper(1)
    stencil = vtk.vtkImageStencil()
    stencil.SetInputConnection(2, iis.GetOutputPort())
    stencil.SetBackgroundValue(0)
    #image.GetPointData().RemoveArray("Vorticity")
    #Set scalars to velocity so it can be cut by the stencil
    image.GetPointData().SetScalars(image.GetPointData().GetVectors())
    #if (comptype == "q"):  #Use this to get just q-criterion data instead of velocity data.  Do we need both?
    #    image.GetPointData().SetScalars(vorticity.GetOutput().GetPointData().GetScalars("Q-criterion"))
    stencil.SetInputData(image)
    print ("Update stencil")    
    stencil.Update()
    te = timeit.default_timer()
    print("Setting up write")
    ws = timeit.default_timer()
    #Make velocity a vector again
    velarray = stencil.GetOutput().GetPointData().GetScalars()
    image.GetPointData().RemoveArray("Velocity")
    image.GetPointData().SetVectors(velarray)
    w = vtk.vtkXMLImageDataWriter()
    w.SetCompressorTypeToZLib()
    #w.SetCompressorTypeToNone() Need to figure out why this fails.
    w.SetEncodeAppendedData(0) #turn of base 64 encoding for fast write
    w.SetFileName(outputfile)
    w.SetInputData(image)
    if (0):
        w.SetCompressorTypeToZfp()
        w.GetCompressor().SetNx(ex-sx+1)
        w.GetCompressor().SetNy(ey-sy+1)
        w.GetCompressor().SetNz(ez-sz+1)
        w.GetCompressor().SetTolerance(1e-2)
        w.GetCompressor().SetNumComponents(3)

    #result = w.Write()
    result = 1 #don't write for benchmarking
    we = timeit.default_timer()

    print("Results:")
    print("Read time: %s" % str(re-rs))
    print ("Convert to vtk: %s" % str(ce-cs))
    if (comptype == "q"):
        print ("Q Computation: %s" % str(ve-vs))
        print ("Q Magnitude: %s" % str(me-ms))
    else:
        print ("Vorticity Computation: %s" % str(ve-vs))
        print ("Vorticity Magnitude: %s" % str(me-ms))
    print ("Threshold: %s" % str(te-ts))
    print ("Write %s" % str(we-ws))
    print ("Total time: %s" % str(we-rs))
    if (result):
        p["message"] = "Success"
        p["computetime"] = str(we-rs)
    return p #return the packet
Ejemplo n.º 33
0
    print("GU = " + str(GU))

    for k_point in range(8):
        farray_disp.SetTuple(k_point, numpy.dot(GU, points.GetPoint(k_point)))
        #print farray_disp.GetTuple(k_point)

    # Compute the small (linearized) strain tensor: e = (GU)_sym = (GU+GU^T)/2
    e = (GU + numpy.transpose(GU)) / 2
    print("e = " + str(e))

    # Compute the Green-Lagrange strain tensor: E = (F.F^T-1)/2 = (GU+GU^T+GU^T.GU)/2 = e + GU^T.GU/2
    E = e + numpy.dot(numpy.transpose(GU), GU) / 2
    print("E = " + str(E))

    # Compute displacement gradient using vtkCellDerivatives
    cell_derivatives = vtk.vtkCellDerivatives()
    cell_derivatives.SetVectorModeToPassVectors()
    cell_derivatives.SetTensorModeToComputeGradient()
    cell_derivatives.SetInputData(ugrid_hex)
    cell_derivatives.Update()
    vector_gradient = numpy.reshape(
        cell_derivatives.GetOutput().GetCellData().GetArray(
            "VectorGradient").GetTuple(0), (3, 3))
    print("VectorGradient = " + str(vector_gradient))
    assert numpy.allclose(vector_gradient, GU)

    # Compute small strain tensor using vtkCellDerivatives
    cell_derivatives = vtk.vtkCellDerivatives()
    cell_derivatives.SetVectorModeToPassVectors()
    cell_derivatives.SetTensorModeToComputeStrain()
    cell_derivatives.SetInputData(ugrid_hex)
Ejemplo n.º 34
0
def computeStrainsFromDisplacements(mesh,
                                    disp_array_name="displacement",
                                    ref_mesh=None,
                                    verbose=0):

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

    myVTK.myPrint(
        min(verbose, 1),
        "*** Warning: at some point the ordering of vector gradient components has changed, and uses C ordering instead of F. ***"
    )
    if (vtk.vtkVersion.GetVTKMajorVersion() >= 8):
        ordering = "C"
    elif (vtk.vtkVersion.GetVTKMajorVersion()
          == 7) and ((vtk.vtkVersion.GetVTKMinorVersion() > 0) or
                     (vtk.vtkVersion.GetVTKBuildVersion() > 0)):
        ordering = "C"
    else:
        ordering = "F"

    n_points = mesh.GetNumberOfPoints()
    n_cells = mesh.GetNumberOfCells()

    assert (mesh.GetPointData().HasArray(disp_array_name))
    mesh.GetPointData().SetActiveVectors(disp_array_name)
    cell_derivatives = vtk.vtkCellDerivatives()
    cell_derivatives.SetVectorModeToPassVectors()
    cell_derivatives.SetTensorModeToComputeGradient()
    if (vtk.vtkVersion.GetVTKMajorVersion() >= 6):
        cell_derivatives.SetInputData(mesh)
    else:
        cell_derivatives.SetInput(mesh)
    cell_derivatives.Update()
    farray_gu = cell_derivatives.GetOutput().GetCellData().GetArray(
        "VectorGradient")

    if (ref_mesh is not None):
        farray_strain = myVTK.createFloatArray(name="Strain_CAR",
                                               n_components=6,
                                               n_tuples=n_cells)
    else:
        farray_strain = myVTK.createFloatArray(name="Strain",
                                               n_components=6,
                                               n_tuples=n_cells)
    mesh.GetCellData().AddArray(farray_strain)
    I = numpy.eye(3)
    E_vec = numpy.empty(6)
    #e_vec = numpy.empty(6)
    for k_cell in range(n_cells):
        GU = numpy.reshape(farray_gu.GetTuple(k_cell), (3, 3), ordering)
        F = I + GU
        C = numpy.dot(numpy.transpose(F), F)
        E = (C - I) / 2
        mat_sym33_to_vec_col6(E, E_vec)
        farray_strain.SetTuple(k_cell, E_vec)
        #if (add_almansi_strain):
        #Finv = numpy.linalg.inv(F)
        #c = numpy.dot(numpy.transpose(Finv), Finv)
        #e = (I - c)/2
        #mat_sym33_to_vec_col6(e, e_vec)
        #farray_almansi.SetTuple(k_cell, e_vec)

    if (ref_mesh is not None) and (ref_mesh.GetCellData().HasArray("eR")) and (
            ref_mesh.GetCellData().HasArray("eC")) and (
                ref_mesh.GetCellData().HasArray("eL")):
        farray_strain_cyl = myVTK.rotateMatrix(
            old_array=mesh.GetCellData().GetArray("Strain_CAR"),
            out_vecs=[
                ref_mesh.GetCellData().GetArray("eR"),
                ref_mesh.GetCellData().GetArray("eC"),
                ref_mesh.GetCellData().GetArray("eL")
            ],
            verbose=0)
        farray_strain_cyl.SetName("Strain_CYL")
        mesh.GetCellData().AddArray(farray_strain_cyl)

    if (ref_mesh
            is not None) and (ref_mesh.GetCellData().HasArray("eRR")) and (
                ref_mesh.GetCellData().HasArray("eCC")) and (
                    ref_mesh.GetCellData().HasArray("eLL")):
        farray_strain_pps = myVTK.rotateMatrix(
            old_array=mesh.GetCellData().GetArray("Strain_CAR"),
            out_vecs=[
                ref_mesh.GetCellData().GetArray("eRR"),
                ref_mesh.GetCellData().GetArray("eCC"),
                ref_mesh.GetCellData().GetArray("eLL")
            ],
            verbose=0)
        farray_strain_pps.SetName("Strain_PPS")
        mesh.GetCellData().AddArray(farray_strain_pps)
Ejemplo n.º 35
0
def getthresh(args):
    inputfile = args[0]
    outputfile = args[1]
    sx = args[2]
    ex = args[3]
    sy = args[4]
    ey = args[5]
    sz = args[6]
    ez = args[7]
    dataset = args[8]
    comptype = args[9]
    print("Loading file, %s" % inputfile)
    #Determine if file is h5 or numpy
    if (inputfile.split(".")[1] == "npy"):
        rs = timeit.default_timer()
        vel = np.load(inputfile)
        re = timeit.default_timer()
    else:
        #read in file
        rs = timeit.default_timer()
        data_file = h5py.File(inputfile, 'r')
        vel = np.array(data_file[dataset])
        data_file.close()
        re = timeit.default_timer()

    cs = timeit.default_timer()
    #convert numpy array to vtk
    vtkdata = numpy_support.numpy_to_vtk(vel.flat,
                                         deep=True,
                                         array_type=vtk.VTK_FLOAT)
    vtkdata.SetNumberOfComponents(3)
    vtkdata.SetName("Velocity")
    image = vtk.vtkImageData()
    image.GetPointData().SetVectors(vtkdata)
    image.SetExtent(sx, ex, sy, ey, sz, ez)
    #NOTE: Hardcoding Spacing

    image.SetSpacing(.006135923, .006135923, .006135923)
    print("Doing computation")
    ce = timeit.default_timer()
    vs = timeit.default_timer()
    if (comptype == "v"):
        vorticity = vtk.vtkCellDerivatives()
        vorticity.SetVectorModeToComputeVorticity()
        vorticity.SetTensorModeToPassTensors()
        vorticity.SetInputData(image)
        vorticity.Update()
    elif (comptype == "q"):
        vorticity = vtk.vtkGradientFilter()
        vorticity.SetInputData(image)
        vorticity.SetInputScalars(image.FIELD_ASSOCIATION_POINTS, "Velocity")
        vorticity.ComputeQCriterionOn()
        vorticity.SetComputeGradient(0)
        vorticity.Update()
    ve = timeit.default_timer()
    #Generate contour for comparison
    c = vtk.vtkContourFilter()
    c.SetValue(0, 1128)
    if (comptype == "q"):
        image.GetPointData().SetScalars(
            vorticity.GetOutput().GetPointData().GetVectors("Q-criterion"))
    else:
        image.GetPointData().SetScalars(
            vorticity.GetOutput().GetPointData().GetVectors())

    c.SetInputData(image)

    c.Update()
    w = vtk.vtkXMLPolyDataWriter()
    w.SetEncodeAppendedData(0)  #turn of base 64 encoding for fast write
    w.SetFileName("contour.vtp")
    w.SetInputData(c.GetOutput())
    ws = timeit.default_timer()
    w.Write()

    ms = timeit.default_timer()
    if (comptype == "v"):
        mag = vtk.vtkImageMagnitude()
        cp = vtk.vtkCellDataToPointData()
        cp.SetInputData(vorticity.GetOutput())
        cp.Update()
        image.GetPointData().SetScalars(
            cp.GetOutput().GetPointData().GetVectors())
        mag.SetInputData(image)
        mag.Update()
        m = mag.GetOutput()
        m.GetPointData().RemoveArray("Velocity")
    else:
        image.GetPointData().SetScalars(
            vorticity.GetOutput().GetPointData().GetVectors("Q-criterion"))
    me = timeit.default_timer()
    print("Thresholding.")
    ts = timeit.default_timer()
    t = vtk.vtkImageThreshold()
    #t = vtk.vtkThreshold() #sparse representation

    if (comptype == "q"):
        t.SetInputData(image)
        t.ThresholdByUpper(783.3)  #.25*67.17^2 = 1127
        #t.SetInputArrayToProcess(0,0,0, vorticity.GetOutput().FIELD_ASSOCIATION_POINTS, "Q-criterion")
        print("q criterion")
    else:
        t.SetInputData(m)
        t.SetInputArrayToProcess(0, 0, 0,
                                 mag.GetOutput().FIELD_ASSOCIATION_POINTS,
                                 "Magnitude")
        t.ThresholdByUpper(44.79)  #44.79)
    #Set values in range to 1 and values out of range to 0
    t.SetInValue(1)
    t.SetOutValue(0)
    #t.ReplaceInOn()
    #t.ReplaceOutOn()
    print("Update thresh")
    t.Update()
    #wt = vtk.vtkXMLImageDataWriter()
    #wt.SetInputData(t.GetOutput())
    #wt.SetFileName("thresh.vti")
    #wt.Write()

    d = vtk.vtkImageDilateErode3D()
    d.SetInputData(t.GetOutput())
    d.SetKernelSize(3, 3, 3)
    d.SetDilateValue(1)
    d.SetErodeValue(0)
    print("Update dilate")
    d.Update()

    iis = vtk.vtkImageToImageStencil()
    iis.SetInputData(d.GetOutput())
    iis.ThresholdByUpper(1)
    stencil = vtk.vtkImageStencil()
    stencil.SetInputConnection(2, iis.GetOutputPort())
    stencil.SetBackgroundValue(0)
    #image.GetPointData().RemoveArray("Vorticity")
    #Set scalars to velocity so it can be cut by the stencil
    image.GetPointData().SetScalars(image.GetPointData().GetVectors())
    #if (comptype == "q"):  #Use this to get just q-criterion data instead of velocity data.  Do we need both?
    #    image.GetPointData().SetScalars(vorticity.GetOutput().GetPointData().GetScalars("Q-criterion"))
    stencil.SetInputData(image)
    print("Update stencil")
    stencil.Update()
    te = timeit.default_timer()
    print("Setting up write")
    ws = timeit.default_timer()
    #Make velocity a vector again
    velarray = stencil.GetOutput().GetPointData().GetScalars()
    image.GetPointData().RemoveArray("Velocity")
    image.GetPointData().SetVectors(velarray)
    w = vtk.vtkXMLImageDataWriter()
    w.SetCompressorTypeToZLib()
    #w.SetCompressorTypeToNone() Need to figure out why this fails.
    w.SetEncodeAppendedData(0)  #turn of base 64 encoding for fast write
    w.SetFileName(outputfile)
    w.SetInputData(image)
    if (0):
        w.SetCompressorTypeToZfp()
        w.GetCompressor().SetNx(ex - sx + 1)
        w.GetCompressor().SetNy(ey - sy + 1)
        w.GetCompressor().SetNz(ez - sz + 1)
        w.GetCompressor().SetTolerance(1e-1)
        w.GetCompressor().SetNumComponents(3)

    w.Write()
    we = timeit.default_timer()

    print("Results:")
    print("Read time: %s" % str(re - rs))
    print("Convert to vtk: %s" % str(ce - cs))
    if (comptype == "q"):
        print("Q Computation: %s" % str(ve - vs))
        print("Q Magnitude: %s" % str(me - ms))
    else:
        print("Vorticity Computation: %s" % str(ve - vs))
        print("Vorticity Magnitude: %s" % str(me - ms))
    print("Threshold: %s" % str(te - ts))
    print("Write %s" % str(we - ws))
    print("Total time: %s" % str(we - rs))
Ejemplo n.º 36
0
def main(argv):
    try:
        opts, args = getopt.getopt(argv, "hi:o:x:a:y:b:z:c:d:u:", [
            "ifile=", "ofile=", "sx=", "ex=", "sy=", "ez=", "dataset=", "comp="
        ])
    except getopt.GetoptError as err:
        print 'getmultithresh.py -i <inputfile.h5> -o <outputfile.vti> -sx -ex -sy -ey -sz -ez -dataset -comptype'
        print(str(err))
    for opt, arg in opts:
        if opt == '-h':
            print 'getmultithresh.py -i <inputfile.h5> -o <outputfile.vti> -sx -ex -sy -ey -sz -ez -dataset'
            sys.exit()
        elif opt in ("-i", "--ifile"):
            inputfile = arg
        elif opt in ("-o", "--ofile"):
            outputfile = arg
        elif opt in ("-x", "--sx"):
            sx = int(arg)
        elif opt in ("-a", "--ex"):
            ex = int(arg)
        elif opt in ("-y", "--sy"):
            sy = int(arg)
        elif opt in ("-b", "--ey"):
            ey = int(arg)
        elif opt in ("-z", "--sz"):
            sz = int(arg)
        elif opt in ("-c", "--ez"):
            ez = int(arg)
        elif opt in ("-d", "--dataset"):
            dataset = str(arg)
        elif opt in ("-u", "--du"):
            comptype = str(arg)
    print("Loading file, %s" % inputfile)
    #Determine if file is h5 or numpy
    if (inputfile.split(".")[1] == "npy"):
        rs = timeit.default_timer()
        vel = np.load(inputfile)
        re = timeit.default_timer()
    else:
        #read in file
        rs = timeit.default_timer()
        data_file = h5py.File(inputfile, 'r')
        vel = np.array(data_file[dataset])
        data_file.close()
        re = timeit.default_timer()

    cs = timeit.default_timer()
    #convert numpy array to vtk
    vtkdata = numpy_support.numpy_to_vtk(vel.flat,
                                         deep=True,
                                         array_type=vtk.VTK_FLOAT)
    vtkdata.SetNumberOfComponents(3)
    vtkdata.SetName("Velocity")
    image = vtk.vtkImageData()
    image.GetPointData().SetVectors(vtkdata)
    image.SetExtent(sx, ex, sy, ey, sz, ez)
    #NOTE: Hardcoding Spacing

    image.SetSpacing(.006135923, .006135923, .006135923)
    print("Doing computation")
    ce = timeit.default_timer()
    vs = timeit.default_timer()
    ve = timeit.default_timer()
    print("Generating contour")
    ms = timeit.default_timer()
    mag = vtk.vtkImageMagnitude()

    for x in range(0, 1):
        start = timeit.default_timer()
        threshold = (22.39 * (2.5))
        if (comptype == "q"):
            threshold = (783.3)
            vort = vtk.vtkGradientFilter()
            vort.SetInputData(image)
            vort.SetInputScalars(image.FIELD_ASSOCIATION_POINTS, "Velocity")
            vort.ComputeQCriterionOn()
            vort.Update()
            image.GetPointData().SetScalars(
                vort.GetOutput().GetPointData().GetVectors("Q-criterion"))
        else:
            v = vtk.vtkCellDerivatives()
            v.SetVectorModeToComputeVorticity()
            v.SetTensorModeToPassTensors()
            v.SetInputData(image)
            v.Update()
            vort = vtk.vtkImageMagnitude()
            cp = vtk.vtkCellDataToPointData()
            cp.SetInputData(v.GetOutput())
            cp.Update()
            image.GetPointData().SetScalars(
                cp.GetOutput().GetPointData().GetVectors())
            vort.SetInputData(image)
            vort.Update()
        #ni = vtk.vtkImageData()
        #ni.SetSpacing(.006135923, .006135923, .006135923)
        #ni.SetExtent(sx,ex,sy,ey,sz,ez)
        #ni.GetPointData().SetScalars(q.GetOutput().GetPointData().GetVectors("Q-criterion"))
        mend = timeit.default_timer()
        me = mend
        comptime = mend - start
        print("Magnitude Computation time: " + str(comptime) + "s")
        c = vtk.vtkContourFilter()
        c.SetValue(0, threshold)
        if (comptype == "q"):
            c.SetInputData(image)
        else:
            c.SetInputData(vort.GetOutput())

        print("Computing Contour with threshold", threshold)
        c.Update()
        w = vtk.vtkXMLPolyDataWriter()
        w.SetEncodeAppendedData(0)  #turn of base 64 encoding for fast write
        w.SetFileName(outputfile + str(x) + ".vtp	")
        w.SetInputData(c.GetOutput())
        ws = timeit.default_timer()
        w.Write()
        we = timeit.default_timer()

        print("Results:")
        print("Read time: %s" % str(re - rs))
        print("Convert to vtk: %s" % str(ce - cs))
        if (comptype == "q"):
            print("Q Computation: %s" % str(ve - vs))
            print("Q Magnitude: %s" % str(me - ms))
        else:
            print("Vorticity Computation: %s" % str(ve - vs))
            print("Vorticity Magnitude: %s" % str(me - ms))
        #print ("Threshold: %s" % str(te-ts))
        print("Write %s" % str(we - ws))
        print("Total time: %s" % str(we - rs))
Ejemplo n.º 37
0
    print("GU = " + str(GU))

    for k_point in xrange(8):
        farray_disp.SetTuple(k_point, numpy.dot(GU, points.GetPoint(k_point)))
        # print farray_disp.GetTuple(k_point)

    # Compute the small (linearized) strain tensor: e = (GU)_sym = (GU+GU^T)/2
    e = (GU + numpy.transpose(GU)) / 2
    print("e = " + str(e))

    # Compute the Green-Lagrange strain tensor: E = (F.F^T-1)/2 = (GU+GU^T+GU^T.GU)/2 = e + GU^T.GU/2
    E = e + numpy.dot(numpy.transpose(GU), GU) / 2
    print("E = " + str(E))

    # Compute displacement gradient using vtkCellDerivatives
    cell_derivatives = vtk.vtkCellDerivatives()
    cell_derivatives.SetVectorModeToPassVectors()
    cell_derivatives.SetTensorModeToComputeGradient()
    cell_derivatives.SetInputData(ugrid_hex)
    cell_derivatives.Update()
    vector_gradient = numpy.reshape(
        cell_derivatives.GetOutput().GetCellData().GetArray("VectorGradient").GetTuple(0), (3, 3)
    )
    print("VectorGradient = " + str(vector_gradient))
    assert numpy.allclose(vector_gradient, GU)

    # Compute small strain tensor using vtkCellDerivatives
    cell_derivatives = vtk.vtkCellDerivatives()
    cell_derivatives.SetVectorModeToPassVectors()
    cell_derivatives.SetTensorModeToComputeStrain()
    cell_derivatives.SetInputData(ugrid_hex)
Ejemplo n.º 38
0
    def deformableRegistration(self):
        """
        Performs deformable image registration on images reconstructed from polygonal surfaces at a user-specified precision.
        If **animate** parameter is *True*, this also spawns a VTK interative rendering that can animate the deformation. 

        Returns
        -------
        cell_fields
        """
        for r, mesh in enumerate(self.rmeshes):
            print(("Performing deformable image registration for object {:d}".
                   format(r + 1)))
            rimg, dimg, rpoly = self._poly2img(r)
            origin = rimg.GetOrigin()
            rimg.SetOrigin((0, 0, 0))
            dimg.SetOrigin((0, 0, 0))

            steplength = np.min(dimg.GetSpacing()) * 5.0
            rimg = sitk.AntiAliasBinary(rimg)
            dimg = sitk.AntiAliasBinary(dimg)

            #peform the deformable registration
            register = sitk.FastSymmetricForcesDemonsRegistrationFilter()
            register.SetNumberOfIterations(
                self.deformableSettings['Iterations'])
            register.SetMaximumRMSError(self.deformableSettings['Maximum RMS'])
            register.SmoothDisplacementFieldOn()
            register.SetStandardDeviations(
                self.deformableSettings['Displacement Smoothing'])
            register.SmoothUpdateFieldOff()
            register.UseImageSpacingOn()
            register.SetMaximumUpdateStepLength(steplength)
            register.SetUseGradientType(0)
            disp_field = register.Execute(rimg, dimg)
            print(("...Elapsed iterations: {:d}".format(
                register.GetElapsedIterations())))
            print(("...Change in RMS error: {:6.3f}".format(
                register.GetRMSChange())))

            disp_field.SetOrigin(origin)

            #translate displacement field to VTK regular grid
            a = sitk.GetArrayFromImage(disp_field)
            disp = vtk.vtkImageData()
            disp.SetOrigin(disp_field.GetOrigin())
            disp.SetSpacing(disp_field.GetSpacing())
            disp.SetDimensions(disp_field.GetSize())
            arr = numpy_to_vtk(a.ravel(), deep=True, array_type=vtk.VTK_DOUBLE)
            arr.SetNumberOfComponents(3)
            arr.SetName("Displacement")
            disp.GetPointData().SetVectors(arr)

            #calculate the strain from displacement field
            getStrain = vtk.vtkCellDerivatives()
            getStrain.SetInputData(disp)
            getStrain.SetTensorModeToComputeStrain()
            getStrain.Update()
            #add the strain tensor to the displacement field structured grid
            strains = getStrain.GetOutput()
            c2p = vtk.vtkCellDataToPointData()
            c2p.PassCellDataOff()
            c2p.SetInputData(strains)
            c2p.Update()
            disp = c2p.GetOutput()

            #use VTK probe filter to interpolate displacements and strains
            #to 3D meshes of cells and save as UnstructuredGrid (.vtu)
            # to visualize in ParaView; this is a linear interpolation
            print("...Interpolating displacements to 3D mesh.")
            if self.rigidInitial:
                #transform 3D Mesh
                tf = vtk.vtkTransformFilter()
                tf.SetInputData(mesh)
                tf.SetTransform(self.rigidTransforms[r])
                tf.Update()
                mesh = tf.GetOutput()
            probe = vtk.vtkProbeFilter()
            probe.SetInputData(mesh)
            probe.SetSourceData(disp)
            probe.Update()
            field = probe.GetOutput()
            if self.display:
                probe2 = vtk.vtkProbeFilter()
                probe2.SetInputData(rpoly)
                probe2.SetSourceData(disp)
                probe2.Update()

            self.cell_fields.append(field)
            if self.saveFEA:
                idisp = field.GetPointData().GetVectors()
                bcs = np.zeros((len(self._snodes[r]), 3), float)
                for j, node in enumerate(self._snodes[r]):
                    d = idisp.GetTuple3(node - 1)
                    bcs[j, 0] = d[0]
                    bcs[j, 1] = d[1]
                    bcs[j, 2] = d[2]
                self._bcs.append(bcs)
            idWriter = vtk.vtkXMLUnstructuredGridWriter()
            idWriter.SetFileName(
                str(
                    os.path.normpath(self._def_dir + os.sep +
                                     'cell{:04d}.vtu'.format(r + 1))))
            idWriter.SetInputData(self.cell_fields[r])
            idWriter.Write()
            if self.display:
                self.animate(probe2.GetOutput(), r)
        print("Registration completed.")
Ejemplo n.º 39
0
def vortmesh(args):

    p = args[0]
    cubenum = args[1]
    print("Cube", cubenum)
    #Check for additonal parameters
    if (p["param1"] != ''):
        comptype = p["param1"]
    else:
        comptype = "q"  #Default to q criterion
    if (p["param2"] != ''):
        thresh = float(p["param2"])
    else:
        thresh = 783.3  #Default for q threshold on isotropic data

    inputfile = p["inputfile"] + str(
        cubenum) + ".npy"  #Used so we can set either npy input or h5 input
    outputfile = p["outputfile"] + str(
        cubenum) + ".vtp"  #always VTK Image Data for this.
    sx = p["sx"]
    sy = p["sy"]
    sz = p["sz"]
    ex = p["ex"]
    ey = p["ey"]
    ez = p["ez"]

    print("Loading file, %s" % inputfile)
    #Determine if file is h5 or numpy
    rs = timeit.default_timer()
    #In case file isn't here, catch this.
    try:
        vel = np.load(inputfile)
    except:
        p["message"] = "Failed to find file"
        return p
    re = timeit.default_timer()
    #convert numpy array to vtk
    cs = timeit.default_timer()
    #convert numpy array to vtk
    vtkdata = numpy_support.numpy_to_vtk(vel.flat,
                                         deep=True,
                                         array_type=vtk.VTK_FLOAT)
    vtkdata.SetNumberOfComponents(3)
    vtkdata.SetName("Velocity")
    image = vtk.vtkImageData()
    image.GetPointData().SetVectors(vtkdata)
    image.SetExtent(sx, ex, sy, ey, sz, ez)
    #NOTE: Hardcoding Spacing TODO: Add to parameters

    image.SetSpacing(.006135923, .006135923, .006135923)
    ce = timeit.default_timer()
    vs = timeit.default_timer()
    if (comptype == "v"):
        vorticity = vtk.vtkCellDerivatives()
        vorticity.SetVectorModeToComputeVorticity()
        vorticity.SetTensorModeToPassTensors()
        vorticity.SetInputData(image)
        vorticity.Update()
    elif (comptype == "q"):
        vorticity = vtk.vtkGradientFilter()
        vorticity.SetInputData(image)
        vorticity.SetInputScalars(image.FIELD_ASSOCIATION_POINTS, "Velocity")
        vorticity.ComputeQCriterionOn()
        vorticity.SetComputeGradient(0)
        vorticity.Update()
    ve = timeit.default_timer()
    #Generate contour for comparison
    c = vtk.vtkContourFilter()
    c.SetValue(0, thresh)
    if (comptype == "q"):
        image.GetPointData().SetScalars(
            vorticity.GetOutput().GetPointData().GetVectors("Q-criterion"))
    else:
        image.GetPointData().SetScalars(
            vorticity.GetOutput().GetPointData().GetVectors())

    c.SetInputData(image)

    c.Update()

    w = vtk.vtkXMLPolyDataWriter()
    w.SetEncodeAppendedData(0)  #turn of base 64 encoding for fast write
    w.SetFileName(outputfile)
    w.SetInputData(c.GetOutput())
    ws = timeit.default_timer()
    result = w.Write()
    we = timeit.default_timer()

    print("Read time: %s" % str(re - rs))
    print("Convert to vtk: %s" % str(ce - cs))
    if (comptype == "q"):
        print("Q Computation: %s" % str(ve - vs))
    else:
        print("Vorticity Computation: %s" % str(ve - vs))
    print("Write %s" % str(we - ws))
    print("Total time: %s" % str(we - rs))
    if (result):
        p["message"] = "Success"
        p["computetime"] = str(we - rs)
    return p  #return the packet