def __init__(self,data_reader,main_renderer,main_interactor,chart_points):
        
        self.poly_data=vtk.vtkPolyData()
        self.lw=Line_Widget(data_reader,main_renderer,main_interactor,self,chart_points)
        
        self.probe_filter=vtk.vtkProbeFilter()
        self.probe_filter.SetInput(self.poly_data)
        
        self.probe_filter.SetSource(data_reader.get_data_set())
        self.actor=vtk.vtkXYPlotActor()
        self.actor.AddInput(self.probe_filter.GetOutput())
        self.actor.GetPositionCoordinate().SetValue(0.05,0.05,0)
        self.actor.GetPosition2Coordinate().SetValue(0.95,0.95,0)

        self.actor.SetYRange(data_reader.get_scalar_range())
        self.actor.SetXValuesToArcLength()
        self.actor.SetNumberOfXLabels(6)
        self.actor.SetTitle("Data")
        self.actor.SetXTitle("s")
        self.actor.SetYTitle("f(s)")
        self.actor.GetProperty().SetColor(0,0,0)
        self.actor.GetProperty().SetLineWidth(2)
        self.actor.SetLabelFormat("%g")
        self.actor.GetTitleTextProperty().SetFontFamilyToArial()
        #main_renderer.AddActor2D(self.actor)
         
        #main_renderer.Render()
        # tu wystartuje nowy watek z wykresem w nowym oknie
        newwin = New_Render_Widget_Package(self.actor)
        #newwin.widget.add_actor(actor)
        newwin.start()
예제 #2
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(
         self, module_manager,
         vtk.vtkProbeFilter(), 'Processing.',
         ('vtkDataSet', 'vtkDataSet'), ('vtkDataSet',),
         replaceDoc=True,
         inputFunctions=None, outputFunctions=None)
예제 #3
0
def RemappedVtu(inputVtu, targetVtu):
  """
  Remap (via probing) the input vtu onto the mesh of the target vtu
  """
      
  coordinates = targetVtu.GetLocations()
      
  ### The following is lifted from vtu.ProbeData in tools/vtktools.py (with 
  ### self -> inputVtu and invalid node remapping rather than repositioning)
  # Initialise locator
  locator = vtk.vtkPointLocator()
  locator.SetDataSet(inputVtu.ugrid)
  locator.SetTolerance(10.0)
  locator.Update()

  # Initialise probe
  points = vtk.vtkPoints()
  ilen, jlen = coordinates.shape
  for i in range(ilen):
    points.InsertNextPoint(coordinates[i][0], coordinates[i][1], coordinates[i][2])
  polydata = vtk.vtkPolyData()
  polydata.SetPoints(points)
  probe = vtk.vtkProbeFilter()
  if vtk.vtkVersion.GetVTKMajorVersion() <= 5:
    probe.SetInput(polydata)
    probe.SetSource(inputVtu.ugrid)
  else:
    probe.SetInputData(polydata)
    probe.SetSourceData(inputVtu.ugrid)
  probe.Update()

  # Generate a list invalidNodes, containing a map from invalid nodes in the
  # result to their closest nodes in the input
  valid_ids = probe.GetValidPoints()
  valid_loc = 0
  invalidNodes = []
  for i in range(ilen):
    if valid_ids.GetTuple1(valid_loc) == i:
      valid_loc += 1
    else:
      nearest = locator.FindClosestPoint([coordinates[i][0], coordinates[i][1], coordinates[i][2]])
      invalidNodes.append((i, nearest))
  ### End of code from vtktools.py

  # Construct output  
  result = vtu()
  result.ugrid = PolyDataToUnstructuredGrid(probe.GetOutput())
  # Add the cells
  result.ugrid.SetCells(targetVtu.ugrid.GetCellTypesArray(), targetVtu.ugrid.GetCellLocationsArray(), targetVtu.ugrid.GetCells())
  # Fix the point data at invalid nodes
  if len(invalidNodes) > 0:
    for i in range(inputVtu.ugrid.GetPointData().GetNumberOfArrays()):
      oldField = inputVtu.ugrid.GetPointData().GetArray(i)
      newField = result.ugrid.GetPointData().GetArray(i)      
      components = oldField.GetNumberOfComponents()
      for invalidNode, nearest in invalidNodes:
        for comp in range(components):
          newField.SetValue(invalidNode * components + comp, oldField.GetValue(nearest * components + comp))
            
  return result
예제 #4
0
    def StructuredPointProbe(self, nx, ny, nz, bounding_box=None):
        """ Probe the unstructured grid dataset using a structured points dataset. """

        probe = vtk.vtkProbeFilter()
        if vtk.vtkVersion.GetVTKMajorVersion() <= 5:
            probe.SetSource(self.ugrid)
        else:
            probe.SetSourceData(self.ugrid)

        sgrid = vtk.vtkStructuredPoints()

        bbox = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
        if bounding_box == None:
            bbox = self.ugrid.GetBounds()
        else:
            bbox = bounding_box

        sgrid.SetOrigin([bbox[0], bbox[2], bbox[4]])

        sgrid.SetDimensions(nx, ny, nz)

        spacing = [0.0, 0.0, 0.0]
        if nx > 1: spacing[0] = (bbox[1] - bbox[0]) / (nx - 1.0)
        if ny > 1: spacing[1] = (bbox[3] - bbox[2]) / (ny - 1.0)
        if nz > 1: spacing[2] = (bbox[5] - bbox[4]) / (nz - 1.0)

        sgrid.SetSpacing(spacing)

        if vtk.vtkVersion.GetVTKMajorVersion() <= 5:
            probe.SetInput(sgrid)
        else:
            probe.SetInputData(sgrid)
        probe.Update()

        return probe.GetOutput()
예제 #5
0
    def __init__(self):
        super(ParticleAdvection,
              self).__init__(nInputPorts=1,
                             inputType='vtkDataSet',
                             nOutputPorts=1,
                             outputType='vtkUnstructuredGrid')
        self.Cache = None
        # Seed for the particles
        self.Source = vtk.vtkLineSource()
        self.Source.SetPoint1(3, 0, 0)
        self.Source.SetPoint2(3, 6, 0)
        self.Source.SetResolution(20)
        self.Source.Update()
        self.NumPts = self.Source.GetOutput().GetNumberOfPoints()
        # We use the probe filter to sample the input
        # field at particle locations.
        self.Probe = vtk.vtkProbeFilter()

        # Create a polydata to represent the particle locations
        # at which we will sample the velocity fields.
        self.ProbePoints = vtk.vtkPolyData()
        pts = vtk.vtkPoints()
        self.ProbePoints.SetPoints(pts)

        self.Probe.SetInputData(self.ProbePoints)

        self.UpdateTimeIndex = 0
예제 #6
0
def interpolate_over_line(line, reader):

    # Interpolate the data from the VTK-file on the created line.

    # vtkProbeFilter, the probe line is the input, and the underlying dataset
    # is the source.
    probe = vtk.vtkProbeFilter()
    probe.SetInputConnection(line.GetOutputPort())
    probe.SetSourceData(reader.GetOutput())
    probe.Update()

    # Get the data from the VTK-object (probe) to an numpy array
    q = vtk_to_numpy(probe.GetOutput().GetPointData().GetArray(displacement))

    samples_on_line = probe.GetOutput().GetNumberOfPoints()

    # Initialise the points on the line
    x = np.zeros(samples_on_line)
    y = np.zeros(samples_on_line)
    z = np.zeros(samples_on_line)
    points = np.zeros((samples_on_line , 3))

    # Get the coordinates of the points on the line
    for i in range(samples_on_line):
        x[i], y[i], z[i] = probe.GetOutput().GetPoint(i)
        points[i, 0] = x[i]
        points[i, 1] = y[i]
        points[i, 2] = z[i]
    return points,q
예제 #7
0
    def __init__(self, module_manager):
        # initialise our base class
        ModuleBase.__init__(self, module_manager)

        self._reslicer = vtk.vtkImageReslice()
        self._probefilter = vtk.vtkProbeFilter()

        self._config.paddingValue = 0.0
        
        #This is retarded - we (sometimes, see below) need the padder 
        #to get the image extent big enough to satisfy the probe filter. 
        #No apparent logical reason, but it throws an exception if we don't.
        self._padder = vtk.vtkImageConstantPad()

        configList = [
            ('Padding value:', 'paddingValue', 'base:float', 'text',
             'The value used to pad regions that are outside the supplied volume.')]        
        
        # initialise any mixins we might have
        ScriptedConfigModuleMixin.__init__(
            self, configList,
            {'Module (self)': self,
             'vtkImageReslice': self._reslicer,
             'vtkProbeFilter': self._probefilter,
             'vtkImageConstantPad': self._padder})

        module_utils.setup_vtk_object_progress(self, self._reslicer,
                                               'Transforming image (Image Reslice)')
        module_utils.setup_vtk_object_progress(self, self._probefilter,
                                               'Performing remapping (Probe Filter)')

        self.sync_module_logic_with_config()
예제 #8
0
    def get_xyz(self, xyz):

        # FIXME: I actually do have to implement this. Sigh.  I have to use point probes to get the values,
        # FIXME: But I can do them all at once to save time. (this is needed during the resample)

        # 1) define point
        # 2) apply filter
        # 3) return point
        point = vtk.vtkPointSource()
        point.SetCenter(xyz)
        point.SetNumberOfPoints(1)
        point.SetRadius(1e-12)
        point.Update()

        output = self.reader.GetOutput()
        b_field = output.GetPointData().GetArray(self.array)
        output.GetPointData().SetVectors(b_field)
        probe = vtk.vtkProbeFilter()
        probe.SetInputConnection(point.GetOutputPort())
        probe.SetSourceData(output)
        probe.Update()

        pointN = dsa.WrapDataObject(probe.GetOutput())
        pVal = pointN.GetPointData().GetArray(self.array)
        # print ("Value: {}".format(pVal.flatten()))

        return pVal.flatten()
예제 #9
0
  def __init__(self, ugrid, coordinates):
    # Initialise locator
    locator = vtk.vtkPointLocator()
    locator.SetDataSet(ugrid)
    locator.SetTolerance(10.0)
    locator.Update()

    # Initialise probe
    points = vtk.vtkPoints()
    points.SetDataTypeToDouble()
    ilen, jlen = coordinates.shape
    for i in range(ilen):
      points.InsertNextPoint(coordinates[i][0], coordinates[i][1], coordinates[i][2])
    polydata = vtk.vtkPolyData()
    polydata.SetPoints(points)
    self.probe = vtk.vtkProbeFilter()
    self.probe.SetInput(polydata)
    self.probe.SetSource(ugrid)
    self.probe.Update()

    # Generate a list invalidNodes, containing a map from invalid nodes in the
    # result to their closest nodes in the input
    valid_ids = self.probe.GetValidPoints()
    valid_loc = 0
    self.invalidNodes = []
    for i in range(ilen):
      if valid_ids.GetTuple1(valid_loc) == i:
        valid_loc += 1
      else:
        nearest = locator.FindClosestPoint([coordinates[i][0], coordinates[i][1], coordinates[i][2]])
        self.invalidNodes.append((i, nearest))
    self.ugrid = ugrid
예제 #10
0
    def GetIntensities(self,selector):
        probe = vtk.vtkProbeFilter()
        volume = Globals.imagePipeline.volume
        
        m = vtk.vtkMatrix4x4()
        # populate the matrix
        m.DeepCopy( selector.GetDirectionCosines() )
        axesOrigin = selector.GetAxesOrigin()
        m.SetElement(0,3, axesOrigin[0])
        m.SetElement(1,3, axesOrigin[1])
        m.SetElement(2,3, axesOrigin[2])
        
        # use the selector to project points in the right spatial position
        volSpline = PlaneSpline()
        for pt in self.points:
            wpt = m.MultiplyPoint( [pt[0],pt[1],0,1] )
            volSpline.AddPoint(wpt[0:3])

        polyData = volSpline.GetVtkPolyData()
        probe.SetInput(polyData)
        probe.SetSource(volume)
        probe.Update()
        
        lstValues = []
        vtkValues = probe.GetOutput().GetPointData().GetScalars()
        for i in range(vtkValues.GetNumberOfTuples()):
            lstValues.append( vtkValues.GetComponent(i,0) )
            
        return str(lstValues)[1:-1]
예제 #11
0
    def extractData(self):

        names = []
        for key in self.profiles.keys():
            names.append(key)

        for file in self.vtpFileNames:
            print('Extracting profiles from: %s' % file)
            reader = self.readVTK(file)  # read the VTKfile
            data = reader.GetOutput()

            #slice data on plane
            for count, plane in enumerate(self.planes):

                cutEdges = vtk.vtkCutter()
                cutEdges.SetInputConnection(reader.GetOutputPort())
                cutEdges.SetCutFunction(plane)
                cutEdges.Update()

                probe = vtk.vtkProbeFilter()
                probe.SetInputConnection(cutEdges.GetOutputPort())
                probe.SetSourceData(data)
                probe.Update()

                scalar = VN.vtk_to_numpy(
                    probe.GetOutput().GetPointData().GetArray('s'))
                points = self.returnPoints(probe)

                self.profiles[names[count]].append(
                    np.stack(
                        (points[:, 0], points[:, 1], points[:, 2], scalar),
                        axis=1))
예제 #12
0
def extract_probe_data(case_name='windfarm',
                       wind_direction_start=0,
                       wind_direction_end=360,
                       wind_direction_step=10,
                       num_processes=16,
                       probe_location_file='name_x_y_z.txt',
                       offset=0.0,
                       **kwargs):
    import vtk
    from vtk.util import numpy_support as VN
    probe_location_array = np.genfromtxt(probe_location_file, dtype=None)
    probe = vtk.vtkProbeFilter()
    point = vtk.vtkPointSource()
    for wd in range(wind_direction_start, wind_direction_end, wind_direction_step):
        directory = case_name + '_' + str(int(wd)) + '_P' + str(num_processes) + '_OUTPUT'
        filename = case_name + '_' + str(int(wd)) + '.pvd'
        reader = OpenDataFile('./' + directory + '/' + filename)
        local_volume = servermanager.Fetch(reader)
        for location in probe_location_array:
            name = location[0]
            easting = location[1]
            northing = location[2]
            height = location[3] + offset
            point.SetNumberOfPoints(1)
            point.SetCenter([easting, northing, height])
            probe.SetInputConnection(point.GetOutputPort())
            probe.SetSourceData(local_volume)
            probe.Update()
            V = VN.vtk_to_numpy(probe.GetOutput().GetPointData().GetArray('V'))
            ti = VN.vtk_to_numpy(probe.GetOutput().GetPointData().GetArray('ti'))
            print str(wd) + ' ' + name + '_zoffset_' + str(offset) + '_V_x ' + str(V[0][0])
            print str(wd) + ' ' + name + '_zoffset_' + str(offset) + '_V_y ' + str(V[0][1])
            print str(wd) + ' ' + name + '_zoffset_' + str(offset) + '_V_z ' + str(V[0][2])
            print str(wd) + ' ' + name + '_zoffset_' + str(offset) + '_ti ' + str(ti[0] + 0.1)
예제 #13
0
def line_query(output,q1,q2,numPoints,component):
    """
    Interpolate the data from output over q1 to q2 (list of x,y,z)
    """
    query_point = [q1,q2]
    line = vtk.vtkLineSource()
    line.SetResolution(numPoints)
    line.SetPoint1(q1)
    line.SetPoint2(q2)
    line.Update()
    
    probe = vtk.vtkProbeFilter()
    probe.SetInputConnection(line.GetOutputPort())
    probe.SetSourceData(output)
    
    probe.Update() 
    
    #initialize numpy array - number of points in probe potentially != numPoints
    line_pts = np.empty((probe.GetOutput().GetNumberOfPoints(),3)) #x,y,z
    
    #get all points: could also iterate over probe.GetOutput().GetNumberOfPoints()
    for i in range(numPoints):
        line_pts[i,:] = probe.GetOutput().GetPoint(i)
    #stack probe value on end column of line_pts
    line_pts = np.hstack((line_pts, \
            np.array([v2n(probe.GetOutput().GetPointData().GetArray(component))]).T))
    

    return line_pts
예제 #14
0
파일: postprocess.py 프로젝트: majroy/pyCM
	def probeOverLine(self, line):
		"""
		Interpolate the data from the VTK-file on the created line.
		"""
		data = self.mesh_reader_output
		
		probe = vtk.vtkProbeFilter()
		#probe.SetInputConnection(line.GetOutputPort())
		probe.SetInputConnection(line.GetOutputPort())
		probe.SetSourceData(data)

		probe.Update()

		# get the data from the VTK-object (probe) to an numpy array
		q = v2n(probe.GetOutput().GetPointData().GetArray(self.active_scalar_field))
		numPoints = probe.GetOutput().GetNumberOfPoints() # get the number of points on the line
		
		# intialise the points on the line    
		x = np.zeros(numPoints)
		y = np.zeros(numPoints)
		z = np.zeros(numPoints)
		points = np.zeros((numPoints , 3))
		
		# get the coordinates of the points on the line
		for i in range(numPoints):
			x[i], y[i], z[i] = probe.GetOutput().GetPoint(i)
			points[i, 0] = x[i]
			points[i, 1] = y[i]
			points[i, 2] = z[i]
		return points, q
예제 #15
0
  def StructuredPointProbe(self, nx, ny, nz, bounding_box=None):
    """ Probe the unstructured grid dataset using a structured points dataset. """

    probe = vtk.vtkProbeFilter ()
    probe.SetSource (self.ugrid)

    sgrid = vtk.vtkStructuredPoints()

    bbox = [0.0,0.0, 0.0,0.0, 0.0,0.0]
    if bounding_box==None:
      bbox = self.ugrid.GetBounds()
    else:
      bbox = bounding_box

    sgrid.SetOrigin([bbox[0], bbox[2], bbox[4]])

    sgrid.SetDimensions(nx, ny, nz)

    spacing = [0.0, 0.0, 0.0]
    if nx>1: spacing[0] = (bbox[1]-bbox[0])/(nx-1.0)
    if ny>1: spacing[1] = (bbox[3]-bbox[2])/(ny-1.0)
    if nz>1: spacing[2] = (bbox[5]-bbox[4])/(nz-1.0)

    sgrid.SetSpacing(spacing)

    probe.SetInput (sgrid)
    probe.Update ()

    return probe.GetOutput()
예제 #16
0
def InterpolatePoints(data, source):
    probe = vtk.vtkProbeFilter()
    probe.SetInputData(data)
    probe.SetSourceData(source)
    probe.Update()
    
    return probe
예제 #17
0
def probe_grid(data, resolution=(250, 250, 250)):
    x0, x1, y0, y1, z0, z1 = data.GetBounds()

    if hasattr(data, "GetDimensions"):
        nx, ny, nz = data.GetDimensions()
        log.warning(
            "The data has specific dimensions ({}, {}, {}): ignoring the provided resolution."
            .format(nx, ny, nz))
    else:
        nx, ny, nz = resolution

    struct_p = vtk.vtkStructuredPoints()
    struct_p.SetOrigin(x0, y0, z0)

    struct_p.SetDimensions(nx, ny, nz)
    struct_p.SetSpacing((x1 - x0) / nx, (y1 - y0) / ny, (z1 - z0) / nz)

    probe = vtk.vtkProbeFilter()
    probe.SetInputData(struct_p)
    probe.SetSourceData(data)
    log.warning("Starting probe. The process may take a long time.",
                draw_win=False)
    probe.Update()
    log.warning("Probe complete.", draw_win=False)

    probe_out = probe.GetOutput()

    return probe_out
    def __init__(self, data_reader, main_renderer, main_interactor,
                 chart_points):

        self.poly_data = vtk.vtkPolyData()
        self.lw = Line_Widget(data_reader, main_renderer, main_interactor,
                              self, chart_points)

        self.probe_filter = vtk.vtkProbeFilter()
        self.probe_filter.SetInput(self.poly_data)

        self.probe_filter.SetSource(data_reader.get_data_set())
        self.actor = vtk.vtkXYPlotActor()
        self.actor.AddInput(self.probe_filter.GetOutput())
        self.actor.GetPositionCoordinate().SetValue(0.05, 0.05, 0)
        self.actor.GetPosition2Coordinate().SetValue(0.95, 0.95, 0)

        self.actor.SetYRange(data_reader.get_scalar_range())
        self.actor.SetXValuesToArcLength()
        self.actor.SetNumberOfXLabels(6)
        self.actor.SetTitle("Data")
        self.actor.SetXTitle("s")
        self.actor.SetYTitle("f(s)")
        self.actor.GetProperty().SetColor(0, 0, 0)
        self.actor.GetProperty().SetLineWidth(2)
        self.actor.SetLabelFormat("%g")
        self.actor.GetTitleTextProperty().SetFontFamilyToArial()
        #main_renderer.AddActor2D(self.actor)

        #main_renderer.Render()
        # tu wystartuje nowy watek z wykresem w nowym oknie
        newwin = New_Render_Widget_Package(self.actor)
        #newwin.widget.add_actor(actor)
        newwin.start()
예제 #19
0
def probeOverLine(line, reader):
    #Interpolate the data from the VTK-file on the created line.
    data = reader.GetOutput()
    # vtkProbeFilter, the probe line is the input, and the underlying dataset is the source.
    probe = vtk.vtkProbeFilter()
    probe.SetInputConnection(line.GetOutputPort())
    probe.SetSource(data)
    probe.Update()
    #get the data from the VTK-object (probe) to an numpy array
    q = numpy_support.vtk_to_numpy(
        probe.GetOutput().GetPointData().GetArray('scalars'))
    numPoints = probe.GetOutput().GetNumberOfPoints(
    )  # get the number of points on the line
    #intialise the points on the line
    x = np.zeros(numPoints)
    y = np.zeros(numPoints)
    z = np.zeros(numPoints)
    points = np.zeros((numPoints, 3))
    #get the coordinates of the points on the line
    for i in range(numPoints):
        x[i], y[i], z[i] = probe.GetOutput().GetPoint(i)
        points[i, 0] = x[i]
        points[i, 1] = y[i]
        points[i, 2] = z[i]
    return points, q
예제 #20
0
def probe(image, mesh):
    """Sample image with mesh"""
    prober = vtk.vtkProbeFilter()
    prober.SetInput(mesh)
    prober.SetSource(image)
    prober.Update()
    return prober.GetOutput()
예제 #21
0
    def __init__(self, module_manager):
        # initialise our base class
        ModuleBase.__init__(self, module_manager)

        # what a lame-assed filter, we have to make dummy inputs!
        # if we don't have a dummy input (but instead a None input) it
        # bitterly complains when we do a GetOutput() (it needs the input
        # to know the type of the output) - and GetPolyDataOutput() also
        # doesn't work.
        # NB: this does mean that our probeFilter NEEDS a PolyData as
        # probe geometry!
        ss = vtk.vtkSphereSource()
        ss.SetRadius(0)
        self._dummyInput = ss.GetOutput()

        #This is also retarded - we (sometimes, see below) need the "padder"
        #to get the image extent big enough to satisfy the probe filter. 
        #No apparent logical reason, but it throws an exception if we don't.
        self._padder = vtk.vtkImageConstantPad()
        self._source = None
        self._input = None
        
        self._probeFilter = vtk.vtkProbeFilter()
        self._probeFilter.SetInput(self._dummyInput)

        NoConfigModuleMixin.__init__(
            self,
            {'Module (self)' : self,
             'vtkProbeFilter' : self._probeFilter})

        module_utils.setup_vtk_object_progress(self, self._probeFilter,
                                           'Mapping source on input')
        
        self.sync_module_logic_with_config()
예제 #22
0
    def create_cut_acto_plane(self,xpos,ypos,zpos,plane_id):
        #vtk plane
        plane=vtk.vtkPlane()
        plane.SetOrigin(xpos,ypos,zpos)

        if plane_id==0:
            plane.SetNormal(1,0,0)
        if plane_id==1:
            plane.SetNormal(0,1,0)
        if plane_id==2:
            plane.SetNormal(0.0,0.0,1)

        #create cutter
        cutter=vtk.vtkCutter()
        cutter.SetCutFunction(plane)
        cutter.SetInputConnection(self.dti_reader.GetOutputPort())
        cutter.Update()


        #probe filter for the cutting plane
        probe_filter=vtk.vtkProbeFilter()
        probe_filter.SetInputConnection(cutter.GetOutputPort())
        probe_filter.SetSourceConnection(self.dti_reader.GetOutputPort())


        self.plane1=plane

        return probe_filter
예제 #23
0
    def GetIntensities(self, selector):
        probe = vtk.vtkProbeFilter()
        volume = Globals.imagePipeline.volume

        m = vtk.vtkMatrix4x4()
        # populate the matrix
        m.DeepCopy(selector.GetDirectionCosines())
        axesOrigin = selector.GetAxesOrigin()
        m.SetElement(0, 3, axesOrigin[0])
        m.SetElement(1, 3, axesOrigin[1])
        m.SetElement(2, 3, axesOrigin[2])

        # use the selector to project points in the right spatial position
        volSpline = PlaneSpline()
        for pt in self.points:
            wpt = m.MultiplyPoint([pt[0], pt[1], 0, 1])
            volSpline.AddPoint(wpt[0:3])

        polyData = volSpline.GetVtkPolyData()
        probe.SetInput(polyData)
        probe.SetSource(volume)
        probe.Update()

        lstValues = []
        vtkValues = probe.GetOutput().GetPointData().GetScalars()
        for i in range(vtkValues.GetNumberOfTuples()):
            lstValues.append(vtkValues.GetComponent(i, 0))

        return str(lstValues)[1:-1]
예제 #24
0
  def ProbeData(self, coordinates, name):
    """Interpolate field values at these coordinates."""

    # Initialise locator
    locator = vtk.vtkPointLocator()
    locator.SetDataSet(self.ugrid)
    locator.SetTolerance(10.0)
    locator.Update()

    # Initialise probe
    points = vtk.vtkPoints()
    points.SetDataTypeToDouble()
    ilen, jlen = coordinates.shape
    for i in range(ilen):
      points.InsertNextPoint(coordinates[i][0], coordinates[i][1], coordinates[i][2])
    polydata = vtk.vtkPolyData()
    polydata.SetPoints(points)
    probe = vtk.vtkProbeFilter()
    probe.SetInputData(polydata)
    probe.setSourceData(self.ugrid)
    probe.Update()

    # Generate a list invalidNodes, containing a map from invalid nodes in the
    # result to their closest nodes in the input
    valid_ids = probe.GetValidPoints()
    valid_loc = 0
    invalidNodes = []
    for i in range(ilen):
      if valid_ids.GetTuple1(valid_loc) == i:
        valid_loc += 1
      else:
        nearest = locator.FindClosestPoint([coordinates[i][0], coordinates[i][1], coordinates[i][2]])
        invalidNodes.append((i, nearest))

    # Get final updated values
    pointdata=probe.GetOutput().GetPointData()
    vtkdata=pointdata.GetArray(name)
    nc=vtkdata.GetNumberOfComponents()
    nt=vtkdata.GetNumberOfTuples()
    array = arr([vtkdata.GetValue(i) for i in range(nt * nc)])

    # Fix the point data at invalid nodes
    if len(invalidNodes) > 0:
      try:
        oldField = self.ugrid.GetPointData().GetArray(name)
        components = oldField.GetNumberOfComponents()
      except:
        try:
          oldField = self.ugrid.GetCellData().GetArray(name)
          components = oldField.GetNumberOfComponents()
        except:
          raise Exception("ERROR: couldn't find point or cell field data with name "+name+" in file "+self.filename+".")
      for invalidNode, nearest in invalidNodes:
        for comp in range(nc):
          array[invalidNode * nc + comp] = oldField.GetValue(nearest * nc + comp)

    valShape = self.GetField(name)[0].shape
    array.shape = tuple([nt] + list(valShape))

    return array
예제 #25
0
def sample(dataset, grid):
    probe = vtk.vtkProbeFilter()
    probe.SetInputData(grid)
    probe.SetSourceData(dataset)
    probe.Update()
    probe.GetOutput().GetPointData().RemoveArray("vtkValidPointMask")
    return probe.GetOutput()
예제 #26
0
def samplepiv(piv, xyslice):
    """Sample piv image with xyslice"""
    prober = vtk.vtkProbeFilter()
    prober.SetInput(xyslice)
    prober.SetSource(piv)
    prober.Update()
    return prober.GetOutput()
예제 #27
0
def samplepiv(piv, xyslice):
    """Sample piv image with xyslice"""
    prober = vtk.vtkProbeFilter()
    prober.SetInput(xyslice)
    prober.SetSource(piv)
    prober.Update()
    return prober.GetOutput()
예제 #28
0
    def __init__ (self, mod_m):
        debug ("In Locator::__init__ ()")
        Common.state.busy ()
        Base.Objects.Module.__init__ (self, mod_m)

        self.root = None
	self.axesactor = None
        self.slider = []
	self.resoln_var = []
	self.maxlen=0.0
        self.plotline_var = Tkinter.IntVar ()
        self.tubesize_var = Tkinter.DoubleVar ()
        self.linelenres_var = Tkinter.DoubleVar ()
	self.npoints_var = Tkinter.IntVar ()
        self.data_out = self.mod_m.GetOutput ()        

        self.line=vtkpython.vtkLineSource()
	self.probe=vtkpython.vtkProbeFilter()
        self.plotline = self.actor = vtkpython.vtkXYPlotActor ()

	self.tuber = vtkpython.vtkTubeFilter()
	self.lineactor = vtkpython.vtkActor()
	self.mapper = vtkpython.vtkPolyDataMapper()
        self.axes=vtkpython.vtkAxes()
	self.trans = vtkpython.vtkTransform()
        self.axesactor = vtkpython.vtkActor()

        self._initialize ()

        self.renwin.add_actors (self.lineactor)
        self.renwin.add_actors (self.plotline)
        self.pipe_objs = self.plotline
        self.renwin.Render ()
        Common.state.idle ()
예제 #29
0
def extract__vtuData(inpFile=None, key=None, coord=None):

    # ------------------------------------------------- #
    # --- [1] Read vtu File                         --- #
    # ------------------------------------------------- #

    reader = vtk.vtkXMLUnstructuredGridReader()
    reader.SetFileName(inpFile)
    reader.Update()

    # ------------------------------------------------- #
    # --- [2] import points to be interpolated      --- #
    # ------------------------------------------------- #

    coordinates = nps.numpy_to_vtk(coord, deep=True)
    points = vtk.vtkPoints()
    points.SetData(coordinates)

    profile = vtk.vtkPolyData()
    profile.SetPoints(points)

    # ------------------------------------------------- #
    # --- [3] probing Data                          --- #
    # ------------------------------------------------- #

    probe = vtk.vtkProbeFilter()
    probe.SetInputData(profile)
    probe.SetSourceConnection(reader.GetOutputPort())
    probe.Update()

    Data = nps.vtk_to_numpy(probe.GetOutput().GetPointData().GetArray(key))
    ret = np.concatenate([coord, Data], axis=-1)
    return (ret)
예제 #30
0
    def __init__(self, module_manager):
        # initialise our base class
        ModuleBase.__init__(self, module_manager)

        self._reslicer = vtk.vtkImageReslice()
        self._probefilter = vtk.vtkProbeFilter()

        self._config.paddingValue = 0.0

        #This is retarded - we (sometimes, see below) need the padder
        #to get the image extent big enough to satisfy the probe filter.
        #No apparent logical reason, but it throws an exception if we don't.
        self._padder = vtk.vtkImageConstantPad()

        configList = [(
            'Padding value:', 'paddingValue', 'base:float', 'text',
            'The value used to pad regions that are outside the supplied volume.'
        )]

        # initialise any mixins we might have
        ScriptedConfigModuleMixin.__init__(
            self, configList, {
                'Module (self)': self,
                'vtkImageReslice': self._reslicer,
                'vtkProbeFilter': self._probefilter,
                'vtkImageConstantPad': self._padder
            })

        module_utils.setup_vtk_object_progress(
            self, self._reslicer, 'Transforming image (Image Reslice)')
        module_utils.setup_vtk_object_progress(
            self, self._probefilter, 'Performing remapping (Probe Filter)')

        self.sync_module_logic_with_config()
예제 #31
0
  def ProbeData(self, coordinates, name):
    """Interpolate field values at these coordinates."""

    # Initialise locator
    locator = vtk.vtkPointLocator()
    locator.SetDataSet(self.ugrid)
    locator.SetTolerance(10.0)
    locator.Update()

    # Initialise probe
    points = vtk.vtkPoints()
    points.SetDataTypeToDouble()
    ilen, jlen = coordinates.shape
    for i in range(ilen):
      points.InsertNextPoint(coordinates[i][0], coordinates[i][1], coordinates[i][2])
    polydata = vtk.vtkPolyData()
    polydata.SetPoints(points)
    probe = vtk.vtkProbeFilter()
    probe.SetInput(polydata)
    probe.SetSource(self.ugrid)
    probe.Update()

    # Generate a list invalidNodes, containing a map from invalid nodes in the
    # result to their closest nodes in the input
    valid_ids = probe.GetValidPoints()
    valid_loc = 0
    invalidNodes = []
    for i in range(ilen):
      if valid_ids.GetTuple1(valid_loc) == i:
        valid_loc += 1
      else:
        nearest = locator.FindClosestPoint([coordinates[i][0], coordinates[i][1], coordinates[i][2]])
        invalidNodes.append((i, nearest))

    # Get final updated values
    pointdata=probe.GetOutput().GetPointData()
    vtkdata=pointdata.GetArray(name)
    nc=vtkdata.GetNumberOfComponents()
    nt=vtkdata.GetNumberOfTuples()
    array = arr([vtkdata.GetValue(i) for i in range(nt * nc)])
    
    # Fix the point data at invalid nodes
    if len(invalidNodes) > 0:
      try:
        oldField = self.ugrid.GetPointData().GetArray(name)
        components = oldField.GetNumberOfComponents()
      except:
        try:
          oldField = self.ugrid.GetCellData().GetArray(name)
          components = oldField.GetNumberOfComponents()
        except:
          raise Exception("ERROR: couldn't find point or cell field data with name "+name+" in file "+self.filename+".")
      for invalidNode, nearest in invalidNodes:
        for comp in range(nc):
          array[invalidNode * nc + comp] = oldField.GetValue(nearest * nc + comp)
          
    valShape = self.GetField(name)[0].shape
    array.shape = tuple([nt] + list(valShape))
          
    return array
예제 #32
0
    def probeVolume(self, volumeNode, rulerNode):

        #Get ruler endpoint coordinates in RAS
        p0ras = rulerNode.GetPolyData().GetPoint(0) + (1, )
        p1ras = rulerNode.GetPolyData().GetPoint(1) + (1, )

        #convert RAS to IJK coordinates of the vtkImageData
        ras2ijk = vtk.vtkMatrix4x4()
        volumeNode.GetRASToIJKMatrix(ras2ijk)
        p0ijk = [int(round(c)) for c in ras2ijk.MultiplyPoint(p0ras)[:3]]
        p1ijk = [int(round(c)) for c in ras2ijk.MultiplyPoint(p1ras)[:3]]

        #create VTK line that will be used for sampling
        line = vtk.vtkLineSource()
        line.SetResolution(100)
        line.SetPoint1(p0ijk[0], p0ijk[1], p0ijk[2])
        line.SetPoint2(p1ijk[0], p1ijk[1], p1ijk[2])

        #Create VTK probe filter and sample the image
        probe = vtk.vtkProbeFilter()
        probe.SetInputConnection(line.GetOutputPort())
        probe.SetSourceData(volumeNode.GetImageData())
        probe.Update()

        #Return VTK array
        return probe.GetOutput().GetPointData().GetArray('ImageScalars')
예제 #33
0
    def createVTKisocontour(self, dataVTK, isovalue, filename, poidsVTK, s):
        "Creation des isocontours"

        # Creation des contours
        contours = vtk.vtkContourFilter()
        contours.SetInput(dataVTK)
        #~ contours.GenerateValues(nb_isocontour, values.min(), values.max())
        contours.SetValue(0, isovalue)
        contours.Update()

        # Gestion des contours
        connectFilter = vtk.vtkPolyDataConnectivityFilter()
        connectFilter.SetInputConnection(contours.GetOutputPort())
        connectFilter.ScalarConnectivityOff()
        connectFilter.ColorRegionsOn()
        connectFilter.SetExtractionModeToSpecifiedRegions()
        connectFilter.AddSpecifiedRegion(0)
        connectFilter.Update()

        if connectFilter.GetNumberOfExtractedRegions() == 1:

            # Recuperation des ponderations
            probe = vtk.vtkProbeFilter()
            probe.SetInputConnection(connectFilter.GetOutputPort())
            probe.SetSource(poidsVTK)
            probe.Update()
            ponderation = VN.vtk_to_numpy(
                probe.GetOutput().GetPointData().GetArray('Value'))

            numPoints = probe.GetOutput().GetNumberOfPoints(
            )  # get the number of points on the line
            #intialise the points on the line
            x = np.zeros(numPoints)
            y = np.zeros(numPoints)
            z = np.zeros(numPoints)
            pts = np.zeros((numPoints, 3))
            #get the coordinates of the points on the line
            for i in range(numPoints):
                x[i], y[i], z[i] = probe.GetOutput().GetPoint(i)
            pts[:, 0] = x
            pts[:, 1] = y
            pts[:, 2] = z

            # Organisation des noeuds
            pts, ponderation = self.orderingNodesOnLine(pts, ponderation)
            #~ plot3Dcontour(pts)

            # scaling ponderation
            ponderation, seuil = self.seuilMass(ponderation, s)

            # Estimation du centre de gravite
            center = self.getCdGfromContour(pts, ponderation, seuil)

            # Ecriture du contour pour post traitement
            #~ self.writeVTKContour(pts, filename)

        else:
            center = np.array([0.0, 0.0, 0.0, -1.0, 0.0, 0.0, 0.0])

        return center, connectFilter.GetOutput()
예제 #34
0
    def probeVolume(self, volumeNode, rulerNode):

        # get ruler ednpoints coordinates in RAS
        p0ras = rulerNode.GetPolyData().GetPoint(0) + (1,)
        p1ras = rulerNode.GetPolyData().GetPoint(1) + (1,)

        # RAS --> IJK
        ras2ijk = vtk.vtkMatrix4x4()
        volumeNode.GetRASToIJKMatrix(ras2ijk)
        p0ijk = [int(round(c)) for c in ras2ijk.MultiplyPoint(p0ras)[:3]]
        p1ijk = [int(round(c)) for c in ras2ijk.MultiplyPoint(p1ras)[:3]]

        # Create VTK line that will be used for sampling
        line = vtk.vtkLineSource()
        line.SetResolution(100)
        line.SetPoint1(p0ijk)
        line.SetPoint2(p1ijk)

        # Create VTK probe filter and sample the image
        probe = vtk.vtkProbeFilter()
        probe .SetInputConnection(line.GetOutputPort())
        probe.SetSourceData(volumeNode.GetImageData())
        probe.Update()

        # Return VTK array
        return probe.GetOutput().GetPointData().GetArray('ImageScalars')
예제 #35
0
파일: verify.py 프로젝트: dbeurle/neon
def interpolate_over_line(line, reader):

    # Interpolate the data from the VTK-file on the created line.

    # vtkProbeFilter, the probe line is the input, and the underlying dataset
    # is the source.
    probe = vtk.vtkProbeFilter()
    probe.SetInputConnection(line.GetOutputPort())
    probe.SetSourceData(reader.GetOutput())
    probe.Update()

    # Get the data from the VTK-object (probe) to an numpy array
    q = vtk_to_numpy(probe.GetOutput().GetPointData().GetArray(displacement))

    samples_on_line = probe.GetOutput().GetNumberOfPoints()

    # initialise the points on the line
    x = np.zeros(samples_on_line)
    y = np.zeros(samples_on_line)
    z = np.zeros(samples_on_line)
    points = np.zeros((samples_on_line , 3))

    # Get the coordinates of the points on the line
    for i in range(samples_on_line):
        x[i], y[i], z[i] = probe.GetOutput().GetPoint(i)
        points[i, 0] = x[i]
        points[i, 1] = y[i]
        points[i, 2] = z[i]
    return points,q
예제 #36
0
파일: __main__.py 프로젝트: TheBB/ramos
def interpolate(source, target, out):
    """Interpolate a data source on a common mesh."""
    if not target:
        target = source

    # Interpolation only works on VTK type sources currently
    assert isinstance(source, (io.VTKFilesSource, io.VTKTimeDirsSource))
    assert isinstance(target, (io.VTKFilesSource, io.VTKTimeDirsSource))
    sink = source.sink(out)
    for i in source.levels():
        sink.add_level(i)

    probefilter = vtkProbeFilter()
    _, dataset = next(target.datasets())
    probefilter.SetInputData(dataset)
    # Depending on the source type, a dataset may or may not correspond to a
    # time level. However, the data sets make up all the information in a
    # source, so dealing with all of them will create a complete copy.
    for ind, ds in tqdm(source.datasets()):
        probefilter.SetSourceData(ds)
        probefilter.Update()
        output = probefilter.GetUnstructuredGridOutput()
        if not output:
            output = probefilter.GetPolyDataOutput()
        if not output:
            raise TypeError('Unsupported dataset type')
        write_to_file(output, sink.filename(*ind))
예제 #37
0
def DoLineSampling(file_path, domain, pc):

    reader = vtk.vtkXMLUnstructuredGridReader()
    reader.SetFileName(file_path)
    reader.Update()

    sample_spacing = 60.0
    height = pc.get_parameter("PelletHeight").value
    height = height.Convert(1.0e-6 * metres)
    radius = pc.get_parameter("CorneaRadius").value
    radius = radius.Convert(1.0e-6 * metres)
    width = 2.0 * np.pi * radius

    num_samples = int(height / sample_spacing)
    points = vtk.vtkPoints()
    for idx in range(num_samples):
        points.InsertNextPoint(width / 2.0, float(idx * sample_spacing), 0.0)
    poly = vtk.vtkPolyData()
    poly.SetPoints(points)

    probe = vtk.vtkProbeFilter()
    probe.SetSourceData(reader.GetOutput())
    probe.SetInputData(poly)
    probe.Update()

    results = probe.GetOutput().GetPointData().GetArray("Line Density")
    for idx in range(results.GetNumberOfTuples()):
        print "y", points.GetPoint(idx)[1], " rho ", results.GetTuple1(idx)
예제 #38
0
def sample_vtk(file,
               p1=None,
               p2=None,
               x_c=0,
               N_points=101,
               solver=None,
               verbose=True):
    """
    Samples velocity field in a given VTK file, along a line defined with p1 and p2, or x_c.
    :param file: Path to the VTK file
    :type file: str
    :param p1: Coordinates of the starting point of the sample line. Can be either 2D or 3D [x, y] or [x, y, z]
    :type p1: list
    :param p2: Coordinates of the ending point of the sample line. Can be either 2D or 3D [x, y] or [x, y, z]
    :type p2: list
    :param x_c: If p1 and p2 are not provided, this parameter serves the x coordinate of the vertical line.
    :type x_c: float
    :param N_points: The number of points to sample the velocity in.
    :type N_points: int
    """
    if verbose:
        print 'Sampling a VTK file: {}'.format(file)

    solver = solver or postprocess.determineSolver(file)
    if type(file) == str:
        vtkFile = vtkextract.vtkFile()
        vtkFile.solver = solver
        vtkFile.readFile(file, verbose=False)
    else:
        vtkFile = file

    centers = vtkFile.getCenters()
    vtkFile.getVolumes()
    bounds = vtkFile.bounds

    p1 = p1 or [x_c, 0, -1]
    p2 = p2 or [x_c, 0, np.max(bounds[:, 4:])]

    if len(p1) == 2: p1.insert(1, 0)  #if 2D data is provided
    if len(p2) == 2: p2.insert(1, 0)

    line = vtk.vtkLineSource()
    line.SetResolution(N_points - 1)
    line.SetPoint1(p1)
    line.SetPoint2(p2)

    probe = vtk.vtkProbeFilter()
    probe.SetInputConnection(line.GetOutputPort())
    probe.SetSourceConnection(vtkFile.outputPort)

    probe.Update()
    probe = probe.GetOutput()

    vel = probe.GetPointData().GetArray(vtkFile.velArray[solver])
    vel = np.array([vel.GetTuple(j) for j in range(probe.GetNumberOfPoints())])
    line = np.array(
        [probe.GetPoint(j) for j in range(probe.GetNumberOfPoints())])

    return line, vel
예제 #39
0
파일: vtklib.py 프로젝트: sheep-z/utils
def probe(source, probe):
    """Compute point attributes (e.g. scalars, vectors, etc.) at all points of
    the probe object by interpolating the source data."""
    prober = vtk.vtkProbeFilter()
    prober.SetInput(probe)
    prober.SetSource(source)
    prober.Update()
    return prober.GetOutput()
예제 #40
0
파일: compos2d.py 프로젝트: pletzer/compos
    def starInterpolation(self, data, xy, h):
        """
        Interpolate along a star stencil 
        @param data either self.refData or self.spcData
        @param xy x and y coordinates at center of stencil
        @param h excursion from the center
        @return {'w': value, 'e': value, 'n': value, 's': value}
        """
        
        lineX = vtk.vtkLineSource()
        lineX.SetPoint1(xy[0] - h, xy[1], 0.0)
        lineX.SetPoint2(xy[0] + h, xy[1], 0.0)
        lineX.SetResolution(1)

        lineY = vtk.vtkLineSource()
        lineY.SetPoint1(xy[0], xy[1] - h, 0.0)
        lineY.SetPoint2(xy[0], xy[1] + h, 0.0)
        lineY.SetResolution(1)

        probeX = vtk.vtkProbeFilter()
        if vtk.VTK_MAJOR_VERSION >= 6:
            probeX.SetSourceData(data['polydata'])
        else:
            probeX.SetSource(data['polydata'])
        probeX.SetInputConnection(lineX.GetOutputPort())
        probeX.Update()

        probeY = vtk.vtkProbeFilter()
        if vtk.VTK_MAJOR_VERSION >= 6:
            probeY.SetSourceData(data['polydata'])
        else:
            probeY.SetSource(data['polydata'])
        probeY.SetInputConnection(lineY.GetOutputPort())
        probeY.Update()
        
        res = {}
        
        # west and east
        res['w'] = probeX.GetOutput().GetPointData().GetArray(0).GetTuple(0)
        res['e'] = probeX.GetOutput().GetPointData().GetArray(0).GetTuple(1)
        
        # south and north
        res['s'] = probeY.GetOutput().GetPointData().GetArray(0).GetTuple(0)
        res['n'] = probeY.GetOutput().GetPointData().GetArray(0).GetTuple(1)
        
        return res
예제 #41
0
파일: compos2d.py 프로젝트: pletzer/compos
    def starInterpolation(self, data, xy, h):
        """
        Interpolate along a star stencil 
        @param data either self.refData or self.spcData
        @param xy x and y coordinates at center of stencil
        @param h excursion from the center
        @return {'w': value, 'e': value, 'n': value, 's': value}
        """

        lineX = vtk.vtkLineSource()
        lineX.SetPoint1(xy[0] - h, xy[1], 0.0)
        lineX.SetPoint2(xy[0] + h, xy[1], 0.0)
        lineX.SetResolution(1)

        lineY = vtk.vtkLineSource()
        lineY.SetPoint1(xy[0], xy[1] - h, 0.0)
        lineY.SetPoint2(xy[0], xy[1] + h, 0.0)
        lineY.SetResolution(1)

        probeX = vtk.vtkProbeFilter()
        if vtk.VTK_MAJOR_VERSION >= 6:
            probeX.SetSourceData(data['polydata'])
        else:
            probeX.SetSource(data['polydata'])
        probeX.SetInputConnection(lineX.GetOutputPort())
        probeX.Update()

        probeY = vtk.vtkProbeFilter()
        if vtk.VTK_MAJOR_VERSION >= 6:
            probeY.SetSourceData(data['polydata'])
        else:
            probeY.SetSource(data['polydata'])
        probeY.SetInputConnection(lineY.GetOutputPort())
        probeY.Update()

        res = {}

        # west and east
        res['w'] = probeX.GetOutput().GetPointData().GetArray(0).GetTuple(0)
        res['e'] = probeX.GetOutput().GetPointData().GetArray(0).GetTuple(1)

        # south and north
        res['s'] = probeY.GetOutput().GetPointData().GetArray(0).GetTuple(0)
        res['n'] = probeY.GetOutput().GetPointData().GetArray(0).GetTuple(1)

        return res
예제 #42
0
파일: vtklib.py 프로젝트: ajgeers/utils
def probe(source, probe):
    """Compute point attributes (e.g. scalars, vectors, etc.) at all points of
    the probe object by interpolating the source data."""
    prober = vtk.vtkProbeFilter()
    prober.SetInput(probe)
    prober.SetSource(source)
    prober.Update()
    return prober.GetOutput()
예제 #43
0
파일: sfi_viewer.py 프로젝트: ggoret/mudra
    def init_plane_widget(self):
        self.scalar_bar = vtk.vtkScalarBarActor()
        # Must add this to avoid vtkTextActor error
        self.scalar_bar.SetTitle("Number of counts")
        self.scalar_bar.SetWidth(0.1)
        self.scalar_bar.SetHeight(0.9)
        self.scalar_bar.SetLookupTable(self.lut)

        # The image plane widget are used to probe the dataset.
        self.plane_widget = vtk.vtkPlaneWidget()
        if vtk.vtkVersion.GetVTKMajorVersion() < 6:
            self.plane_widget.SetInput(self.data)
        else:
            self.plane_widget.SetInputData(self.data)  #VTK6

        self.plane_widget.NormalToXAxisOn()  #TODO
        self.plane_widget.SetRepresentationToOutline()
        self.plane_widget.PlaceWidget()
        self.plane_widget.SetResolution(350)  #TODO

        self.plane = vtk.vtkPolyData()
        self.plane_widget.GetPolyData(self.plane)

        self.implicit_plane = vtk.vtkPlane()
        self.plane_widget.GetPlane(self.implicit_plane)

        self.probe = vtk.vtkProbeFilter()
        if vtk.vtkVersion.GetVTKMajorVersion() < 6:
            self.probe.SetInput(self.plane)
            self.probe.SetSource(self.data)
        else:
            self.probe.SetInputData(self.plane)  #VTK6
            self.probe.SetSourceData(self.data)
        self.probe.Update()

        contour_mapper = vtk.vtkPolyDataMapper()
        contour_mapper.SetInputConnection(self.probe.GetOutputPort())
        contour_mapper.SetScalarRange(self.mi, self.ma)
        contour_mapper.SetLookupTable(self.lut)

        self.contour_actor = vtk.vtkActor()
        self.contour_actor.SetMapper(contour_mapper)
        self.contour_actor.GetProperty().ShadingOff()
        self.contour_actor.GetProperty().SetAmbient(0.6)
        self.contour_actor.GetProperty().SetDiffuse(0.4)

        self.plane_widget.AddObserver('InteractionEvent',
                                      self.update_interactive_plane_widget)
        self.plane_widget.AddObserver('StartInteractionEvent', self.on_pick)
        # Associate the widget with the interactor
        self.plane_widget.SetInteractor(self.iren)
        self.plane_widget.SetEnabled(1)
        self.disablation_mode = True

        self.renderer.AddActor(self.contour_actor)

        self.renderer.AddActor2D(self.scalar_bar)  #TODO
        self.renwin.Render()
예제 #44
0
def sample_vtk(file, p1=None, p2=None, x_c=0, N_points=101, solver=None, verbose=True):
    """
    Samples velocity field in a given VTK file, along a line defined with p1 and p2, or x_c.
    :param file: Path to the VTK file
    :type file: str
    :param p1: Coordinates of the starting point of the sample line. Can be either 2D or 3D [x, y] or [x, y, z]
    :type p1: list
    :param p2: Coordinates of the ending point of the sample line. Can be either 2D or 3D [x, y] or [x, y, z]
    :type p2: list
    :param x_c: If p1 and p2 are not provided, this parameter serves the x coordinate of the vertical line.
    :type x_c: float
    :param N_points: The number of points to sample the velocity in.
    :type N_points: int
    """
    if verbose:
        print 'Sampling a VTK file: {}'.format(file)

    solver=solver or postprocess.determineSolver(file)
    if type(file) == str:
        vtkFile = vtkextract.vtkFile()
        vtkFile.solver = solver
        vtkFile.readFile(file, verbose=False)
    else:
        vtkFile = file
    
    centers = vtkFile.getCenters()
    vtkFile.getVolumes()
    bounds = vtkFile.bounds
        
    p1 = p1 or [x_c, 0, -1]
    p2 = p2 or [x_c, 0, np.max(bounds[:, 4:])]
    
    if len(p1) == 2: p1.insert(1, 0)  #if 2D data is provided
    if len(p2) == 2: p2.insert(1, 0)

    line = vtk.vtkLineSource()
    line.SetResolution(N_points - 1)
    line.SetPoint1(p1)
    line.SetPoint2(p2)
    
    probe = vtk.vtkProbeFilter()
    probe.SetInputConnection(line.GetOutputPort())
    probe.SetSourceConnection(vtkFile.outputPort)
    
    probe.Update()
    probe = probe.GetOutput()
    
    vel=probe.GetPointData().GetArray(vtkFile.velArray[solver])
    vel=np.array([vel.GetTuple(j) for j in range(probe.GetNumberOfPoints())])
    line=np.array([probe.GetPoint(j) for j in range(probe.GetNumberOfPoints())])
    
    return line, vel
예제 #45
0
    def plot(self):
        """
        plot visualization of data
        """
        self.ren.RemoveAllViewProps()
        # self.marker_widget.EnabledOff()
        active_scalar = self.data.grid[self.current_timestep].GetPointData().GetScalars()
        # print 'active scalar is', active_scalar.GetName()

        line = vtk.vtkLineSource()
        line.SetResolution(30)
        line.SetPoint1(self.line_points[0])
        line.SetPoint2(self.line_points[1])
        probe = vtk.vtkProbeFilter()
        probe.SetInputConnection(line.GetOutputPort())
        probe.SetSourceData(self.data.grid[self.current_timestep])

        tuber = vtk.vtkTubeFilter()
        tuber.SetInputConnection(probe.GetOutputPort())
        tuber.SetRadius(0.02)
        line_mapper = vtk.vtkPolyDataMapper()
        line_mapper.SetInputConnection(tuber.GetOutputPort())
        line_actor = vtk.vtkActor()
        line_actor.SetMapper(line_mapper)
        # self.ren.AddActor(line_actor)

        xyplot = vtk.vtkXYPlotActor()
        if vtk.VTK_MAJOR_VERSION <= 5:
            xyplot.AddInput(probe.GetOutput())
        else:
            xyplot.AddDataSetInputConnection(probe.GetOutputPort())
        xyplot.GetPositionCoordinate().SetValue(0.05, 0.05, 0.0)
        xyplot.GetPosition2Coordinate().SetValue(0.9, 0.9, 0.0) #relative to Position
        xyplot.SetXValuesToArcLength()
        xyplot.SetNumberOfXLabels(6)
        xyplot.SetNumberOfYLabels(6)
        xyplot.SetTitle("title")
        xyplot.SetXTitle("length")
        xyplot.SetYTitle("var")
        # xyplot.SetXRange(.1, .35)
        # xyplot.SetYRange(.2, .4)
        # xyplot.GetProperty().SetColor(0, 0, 0)
        xyplot.GetProperty().SetLineWidth(2)
        self.ren.AddActor2D(xyplot)
        # self.xyplotWidget = vtk.vtkXYPlotWidget()
        # self.xyplotWidget.SetXYPlotActor(xyplot)
        # self.xyplotWidget.SetInteractor(self.iren)
        # self.xyplotWidget.EnabledOn()

        self.ren_win.Render()
예제 #46
0
 def initialize (self):
     debug ("In StructuredPointsProbe::__init__ ()")
     self.spacing_var = Tkinter.StringVar()
     self.dimension_var = Tkinter.StringVar()
     self.conv_scalar_var = Tkinter.IntVar()
     self.conv_scalar_var.set(1)
     self.p_data = vtk.vtkStructuredPoints()
     self.p_data_gui = None        
     self.init_p_data()
     self.fil = vtk.vtkProbeFilter ()
     self.fil.SetSource (self.prev_fil.GetOutput ())
     self.fil.SetInput(self.p_data)
     self.fil.Update ()
     self.set_scaled_scalars()
     self.pipe_objs = self.fil
예제 #47
0
파일: Picker.py 프로젝트: sldion/DNACC
    def pick_world (self, event=None):
        """ Picks a world point and probes for data there."""
        debug ("In Picker::pick_world ()")
        h = self.renwin.tkwidget.winfo_height() - 1 
        self.worldpicker.Pick( (float(event.x), float(h-event.y), \
                                float(0)), self.renwin.get_renderer())

        # use the cell picker to get the data that needs to be probed.
        self.cellpicker.Pick( (float(event.x), float(h-event.y), \
                                float(0)), self.renwin.get_renderer())

        wp = self.worldpicker
        cp = self.cellpicker
        coord = wp.GetPickPosition()
        self.probe_point.SetPoint(0, coord)

        if (cp.GetMapper()):
            self.write_pick ("Picked generic point.")            
            data = get_last_input(cp.GetMapper().GetInput())
            # I need to create the probe each time because otherwise
            # it does not seem to work properly.            
            probe = vtk.vtkProbeFilter()
            probe.SetSource(data)
            probe.SetInput(self.probe_data)
            probe.Update()
            out = probe.GetOutput().GetPointData()
            prn = format(coord, out, 0)
            self.write_pick(prn)

            bounds = cp.GetMapper().GetInput().GetBounds()

            dx = 0.3*(bounds[1]-bounds[0])
            dy = 0.3*(bounds[3]-bounds[2])
            dz = 0.3*(bounds[5]-bounds[4])

            scale = max(dx, dy, dz)

            self.p_source.SetOrigin (coord)
            self.p_source.SetScaleFactor (scale)

            self.p_actor.VisibilityOn()
        else:
            self.write_pick ("No valid data near picked point.")
            self.p_actor.VisibilityOff()

        self.renwin.Render()
        self.write_pick("\n")
예제 #48
0
def probe(pd, filename):
    if(verbose):
        print "Opening ", filename

    reader = vtk.vtkXMLUnstructuredGridReader()
    reader.SetFileName(filename)
    ugrid = reader.GetOutput()
    ugrid.Update()
    
    if(verbose):
        print "Probing"

    probe = vtk.vtkProbeFilter()
    probe.SetSource(ugrid)
    probe.SetInput(pd)
    probe.Update()

    return probe.GetOutput()
예제 #49
0
    def __init__(self, data, mesh, **kwargs):
        """
        Parameters
        ----------
        data : dict
            The output dictionary.
        mesh : Mesh
            The mesh.
        """

        Struct.__init__(self, name=mesh.name, **kwargs)

        self.mesh_name = mesh.name[mesh.name.rfind(osp.sep) + 1:]
        self.vtkdata = get_vtk_from_mesh(mesh, data, 'probe_')

        self.vtkprobe = vtk.vtkProbeFilter()
        self.vtkprobe.SetSource(self.vtkdata)

        self.probes = {}
        self.probes_png = {}
예제 #50
0
def Extract_VTK_data_over_line_to_numpyArray(inputFileName, point1, point2, resolution):

    reader = vtk.vtkXMLUnstructuredGridReader()
    reader.SetFileName(inputFileName)
    reader.Update()
    
    probeLine = vtk.vtkLineSource()
    probeLine.SetPoint1(point1)
    probeLine.SetPoint2(point2)
    probeLine.SetResolution(resolution)
    
    probe = vtk.vtkProbeFilter()
    probe.SetInputConnection(probeLine.GetOutputPort())
    probe.SetSourceData(reader.GetOutput())
    probe.Update()

    vtkarray = probe.GetOutput().GetPointData().GetArray(0) # or Slice1.GetCellData() # or Clip1.GetCellData()
    numpy_array = npvtk.vtk_to_numpy(vtkarray)

    return numpy_array
    def create_cut_acto_plane(self,xpos):
        #vtk plane
        plane=vtk.vtkPlane()
        plane.SetOrigin(xpos,0,0)
        plane.SetNormal(1,0,0)

        #create cutter
        cutter=vtk.vtkCutter()
        cutter.SetCutFunction(plane)
        cutter.SetInputConnection(self.vec_reader.GetOutputPort())
        cutter.Update()


        #probe filter for the cutting plane
        probe_filter=vtk.vtkProbeFilter()
        probe_filter.SetInputConnection(cutter.GetOutputPort())
        probe_filter.SetSourceConnection(self.vec_reader.GetOutputPort())

        if xpos>170 and xpos <220:
            self.plane1=plane

        return probe_filter
예제 #52
0
def probe(pd, filename):
    if(verbose):
        print "Opening ", filename

    reader = vtk.vtkXMLUnstructuredGridReader()
    reader.SetFileName(filename)
    ugrid = reader.GetOutput()
    ugrid.Update()
    
    if(verbose):
        print "Probing"

    probe = vtk.vtkProbeFilter()
    if vtk.vtkVersion.GetVTKMajorVersion() <= 5:
      probe.SetSource(ugrid)
      probe.SetInput(pd)
    else:
      probe.SetSourceData(ugrid)
      probe.SetInputData(pd)
    probe.Update()

    return probe.GetOutput()
예제 #53
0
 def buildPipeline(self):
     """ execute() -> None
     Dispatch the vtkRenderer to the actual rendering widget
     """ 
     self.probeFilter = vtk.vtkProbeFilter()
     textureInput = self.input()            
     textureRange = textureInput.GetScalarRange()
     self.probeFilter.SetSource( textureInput )             
     self.curtainMapper = vtk.vtkPolyDataMapper()
     self.curtainMapper.SetInputConnection( self.probeFilter.GetOutputPort() ) 
     self.curtainMapper.SetScalarRange( textureRange )
             
     colormapManager = self.getColormapManager( index=0 )     
     colormapManager.setAlphaRange ( [ 1.0, 1.0 ]  )
     self.curtainMapper.SetLookupTable( colormapManager.lut ) 
     self.curtainMapper.UseLookupTableScalarRangeOn()
           
     curtainActor = vtk.vtkActor() 
     curtainActor.SetMapper( self.curtainMapper )           
     self.renderer.AddActor( curtainActor )
     self.renderer.SetBackground( VTK_BACKGROUND_COLOR[0], VTK_BACKGROUND_COLOR[1], VTK_BACKGROUND_COLOR[2] )                                            
     self.set3DOutput()                                              
예제 #54
0
파일: probes_vtk.py 프로젝트: lokik/sfepy
    def __init__(self, filename, **kwargs):
        """
        Parameters
        ----------
        filename : dict
            The name of a VTK file.
        """

        bname = osp.splitext(osp.basename(filename))[0]
        Struct.__init__(self, name=bname, **kwargs)

        self.vtkdata = get_vtk_from_file(filename)
        self.mesh_name = bname
        self.dim = 3

        self.vtkprobe = vtk.vtkProbeFilter()
        if vtk_version < 6:
            self.vtkprobe.SetSource(self.vtkdata)
        else:
            self.vtkprobe.SetSourceData(self.vtkdata)

        self.probes = {}
        self.probes_png = {}
예제 #55
0
def probeOverLine(line,reader):
    #Interpolate the data from the VTK-file on the created line.
    data = reader.GetOutput()
    # vtkProbeFilter, the probe line is the input, and the underlying dataset is the source.
    probe = vtk.vtkProbeFilter()
    probe.SetInputConnection(line.GetOutputPort())
    probe.SetSource(data)
    probe.Update()
    #get the data from the VTK-object (probe) to an numpy array
    q=numpy_support.vtk_to_numpy(probe.GetOutput().GetPointData().GetArray('scalars'))
    numPoints = probe.GetOutput().GetNumberOfPoints() # get the number of points on the line
    #intialise the points on the line    
    x = np.zeros(numPoints)
    y = np.zeros(numPoints)
    z = np.zeros(numPoints)
    points = np.zeros((numPoints , 3))
    #get the coordinates of the points on the line
    for i in range(numPoints):
        x[i],y[i],z[i] = probe.GetOutput().GetPoint(i)
        points[i,0]=x[i]
        points[i,1]=y[i]
        points[i,2]=z[i]
    return points,q
예제 #56
0
def main(vector_file, magnitude_file):

    num_critical_points = 6
    CriticalPoints = vtk.vtkPoints()

    CriticalPoints.InsertNextPoint(35, 14, 20)
    CriticalPoints.InsertNextPoint(55, 15, 20)
    CriticalPoints.InsertNextPoint(65, 45, 19)
    CriticalPoints.InsertNextPoint(45, 44.8, 20)
    CriticalPoints.InsertNextPoint(20, 29.7, 19.8)
    CriticalPoints.InsertNextPoint(10, 32.2, 16.1)

    ColorRange = vtk.vtkLookupTable()
    ColorRange.SetTableRange(0, 1)
    ColorRange.SetHueRange(0, 1)
    ColorRange.SetSaturationRange(1, 1)
    ColorRange.SetAlphaRange(0.3, 0.5)
    ColorRange.Build()

    reader = vtk.vtkStructuredPointsReader()
    reader.SetFileName(vector_file)
    reader.Update()

    mags = reader.GetOutput()

    range1 = mags.GetScalarRange()
    v0 = range1[0]
    v1 = range1[1]

    reader_magnitude = vtk.vtkStructuredPointsReader()
    reader_magnitude.SetFileName(magnitude_file)
    reader_magnitude.Update()

    # All entities initialized equal to number of critical points
    sphere1, stream1, scalarSurface1, tube1, dataMapper1, dataActor1, criticalMarker1, criticalMapper1, criticalActor1, probe1, mask1, glyph1, glyphMapper1, glyphActor1, plane1 = (
        [],
        [],
        [],
        [],
        [],
        [],
        [],
        [],
        [],
        [],
        [],
        [],
        [],
        [],
        [],
    )
    for i in range(0, num_critical_points):
        sphere1.append(vtk.vtkSphereSource())
        stream1.append(vtk.vtkStreamLine())
        scalarSurface1.append(vtk.vtkRuledSurfaceFilter())
        tube1.append(vtk.vtkTubeFilter())
        dataMapper1.append(vtk.vtkPolyDataMapper())
        dataActor1.append(vtk.vtkActor())

        criticalMarker1.append(vtk.vtkSphereSource())
        criticalMapper1.append(vtk.vtkPolyDataMapper())
        criticalActor1.append(vtk.vtkActor())

        probe1.append(vtk.vtkProbeFilter())
        mask1.append(vtk.vtkMaskPoints())
        glyph1.append(vtk.vtkGlyph3D())
        glyphMapper1.append(vtk.vtkPolyDataMapper())
        glyphActor1.append(vtk.vtkActor())

        plane1.append(vtk.vtkPlaneSource())

    integ = vtk.vtkRungeKutta4()

    cone = vtk.vtkConeSource()
    cone.SetResolution(8)
    cone.SetHeight(1.0)
    cone.SetRadius(0.2)

    transform = vtk.vtkTransform()
    transform.Translate(0, 0, 0)

    transformFilter = vtk.vtkTransformPolyDataFilter()
    transformFilter.SetInput(cone.GetOutput())
    transformFilter.SetTransform(transform)

    outline = vtk.vtkOutlineFilter()
    outline.SetInput(reader.GetOutput())

    outlineMapper = vtk.vtkPolyDataMapper()
    outlineMapper.SetInput(outline.GetOutput())

    outlineActor = vtk.vtkActor()
    outlineActor.SetMapper(outlineMapper)
    outlineActor.GetProperty().SetColor(1, 1, 1)

    bar = vtk.vtkScalarBarActor()
    bar.SetLookupTable(ColorRange)

    renderer = vtk.vtkRenderer()

    for i in range(0, num_critical_points):
        sphere1[i].SetRadius(2)
        sphere1[i].SetCenter(
            CriticalPoints.GetPoint(i)[0], CriticalPoints.GetPoint(i)[1], CriticalPoints.GetPoint(i)[2]
        )
        sphere1[i].SetThetaResolution(1)
        stream1[i].SetInput(reader.GetOutput())
        stream1[i].SetSource(sphere1[i].GetOutput())
        stream1[i].SetIntegrator(integ)
        stream1[i].SetMaximumPropagationTime(500)
        stream1[i].SetIntegrationStepLength(0.1)
        stream1[i].SetIntegrationDirectionToIntegrateBothDirections()
        stream1[i].SetStepLength(0.1)

        scalarSurface1[i].SetInput(stream1[i].GetOutput())
        scalarSurface1[i].SetOffset(0)
        scalarSurface1[i].SetOnRatio(2)
        scalarSurface1[i].PassLinesOn()
        scalarSurface1[i].SetRuledModeToPointWalk()
        scalarSurface1[i].SetDistanceFactor(50)

        tube1[i].SetInput(scalarSurface1[i].GetOutput())
        tube1[i].SetRadius(0.1)
        tube1[i].SetNumberOfSides(6)

        dataMapper1[i].SetInput(tube1[i].GetOutput())
        dataMapper1[i].SetScalarRange(v0, v1)
        dataMapper1[i].SetLookupTable(ColorRange)

        dataActor1[i].SetMapper(dataMapper1[i])
        # renderer.AddActor(dataActor1[i])

        criticalMarker1[i].SetRadius(1.0)
        criticalMarker1[i].SetCenter(
            CriticalPoints.GetPoint(i)[0], CriticalPoints.GetPoint(i)[1], CriticalPoints.GetPoint(i)[2]
        )
        criticalMarker1[i].SetThetaResolution(10)
        criticalMapper1[i].SetInput(criticalMarker1[i].GetOutput())

        criticalActor1[i].SetMapper(criticalMapper1[i])
        criticalActor1[i].GetProperty().SetColor(1, 1, 0)
        criticalActor1[i].GetProperty().SetOpacity(0.5)
        # renderer.AddActor(criticalActor1[i])

        probe1[i].SetInput(stream1[i].GetOutput())
        probe1[i].SetSource(reader.GetOutput())

        mask1[i].SetInput(probe1[i].GetOutput())
        mask1[i].SetOnRatio(60)
        mask1[i].RandomModeOn()

        glyph1[i].SetInput(mask1[i].GetOutput())
        glyph1[i].SetSource(transformFilter.GetOutput())
        glyph1[i].SetScaleModeToScaleByVector()
        glyph1[i].SetScaleFactor(2)
        glyph1[i].SetVectorModeToUseVector()
        glyph1[i].SetColorModeToColorByVector()

        glyphMapper1[i].SetInput(glyph1[i].GetOutput())
        glyphMapper1[i].SetLookupTable(ColorRange)

        glyphActor1[i].SetMapper(glyphMapper1[i])
        # renderer.AddActor(glyphActor1[i])

    # removeActors1(renderer, dataActor, criticalActor, glyphActor, dataActor1, criticalActor1, glyphActor1)

    mags = reader.GetOutput()
    bounds = mags.GetBounds()
    x0 = bounds[0]
    x1 = bounds[1]
    y0 = bounds[2]
    y1 = bounds[3]
    z0 = bounds[4]
    z1 = bounds[5]

    range1 = mags.GetScalarRange()
    v0 = range1[0]
    v1 = range1[1]

    plane1[0].SetOrigin(x0, y0, z0)
    plane1[0].SetPoint1(x0, y1, z0)
    plane1[0].SetPoint2(x0, y0, z1)

    plane1[1].SetOrigin(x0, y0, z0)
    plane1[1].SetPoint1(x0, y1, z0)
    plane1[1].SetPoint2(x1, y0, z0)

    plane1[2].SetOrigin(x0, y0, z0)
    plane1[2].SetPoint1(x0, y0, z1)
    plane1[2].SetPoint2(x1, y0, z0)

    plane1[3].SetOrigin(x1, y1, z1)
    plane1[3].SetPoint1(x1, y1, z0)
    plane1[3].SetPoint2(x1, y0, z1)

    plane1[4].SetOrigin(x1, y1, z1)
    plane1[4].SetPoint1(x0, y1, z1)
    plane1[4].SetPoint2(x1, y1, z0)

    plane1[5].SetOrigin(x1, y1, z1)
    plane1[5].SetPoint1(x0, y1, z1)
    plane1[5].SetPoint2(x1, y1, z0)

    for i in range(0, num_critical_points):
        plane1[i].SetResolution(5, 5)
        stream1[i].SetSource(plane1[i].GetOutput())
        renderer.AddActor(dataActor1[i])
        renderer.AddActor(glyphActor1[i])
        glyph1[i].SetScaleFactor(4)

    renderer.AddActor(bar)
    renderer.AddActor(outlineActor)

    for i in range(0, num_critical_points):
        renderer.AddActor(criticalActor1[i])

    renderer_window = vtk.vtkRenderWindow()
    renderer_window.AddRenderer(renderer)
    renderer_window.SetSize(512, 512)

    interactor = vtk.vtkRenderWindowInteractor()
    interactor.SetRenderWindow(renderer_window)

    style = vtk.vtkInteractorStyleTrackballCamera()
    interactor.SetInteractorStyle(style)

    renderer.AddActor(bar)

    renderer.AddActor(outlineActor)

    renderer_window.Render()
    interactor.Start()
예제 #57
0
def streamplot(cfd, ofile='streamplot.pdf', zloc=0.0, xmin=0, xmax=1,
               ymin=0, ymax=1, gridspacing=1.0, streamlinedensity=1,
               hidelabels=False):
    """Contour plot with streamlines superimposed on the xy-slice at z = zloc

    Input: Unstructured grid with Vx_mm_s, Vy_mm_s and Vxy_mm_s pointdata
    Output: Plot saved as PDF

    To create the contourplot, the cfd dataset is sliced with the xy-plane at
    z = zloc. From this slice we extract the x- and y-coordinates, vxy, and a
    list with for each triangle the indices of the three points that make up the
    triangle, ordered in anticlockwise manner.

    To create the streamplot, the cfd dataset is probed with an evenly spaced
    grid. The argument 'gridspacing' controls the resolution. Note that
    undersampling might lead to non-zero vxy values outside the flow domain and,
    thus, to streamlines running outside of it. The argument streamlinedensity
    controls the closeness of streamlines. When streamlinedensity=1, the domain
    is divided into a 25x25 grid; density linearly scales this grid.

    In the paper, we also show plots of vxy vs. y along the y-axis. Therefore, a
    line corresponding to the y-axis is added to the streamplot.

    """

    #==========================================================================
    # Slice CFD dataset
    #==========================================================================

    # slice cfd dataset with xy-plane
    xyslice = vtklib.slicedataset(cfd, [0, 0, zloc], [0, 0, 1])
    xyslice = vtklib.triangulate(xyslice)
    numberofcells = xyslice.GetNumberOfCells()
    numberofpoints = xyslice.GetNumberOfPoints()

    #==========================================================================
    # Contour plot
    #==========================================================================

    # initialize figure
    fig = plt.figure()
    ax = fig.add_subplot(111)

    # nparrays for x, y, vxy
    x = np.empty(numberofpoints)
    y = np.empty(numberofpoints)
    vxy = np.empty(numberofpoints)
    vxyarray = xyslice.GetPointData().GetArray('Vxy_mm_s')
    for i in range(numberofpoints):
        x[i] = xyslice.GetPoint(i)[0]
        y[i] = xyslice.GetPoint(i)[1]
        vxy[i] = vxyarray.GetValue(i)

    # array defining pointids per triangle
    triangles = np.empty(shape=(numberofcells, 3))
    for i in range(numberofcells):
        cellpointids = xyslice.GetCell(i).GetPointIds()
        for j in range(cellpointids.GetNumberOfIds()):
            triangles[i, j] = cellpointids.GetId(j)

    # plot filled contours
    cplot = ax.tricontourf(x, y, triangles, vxy,
                           levels=np.linspace(0, 100, 101),
                           cmap='RdBu_r', extend='both', zorder=-1)

    #==========================================================================
    # Stream plot
    #==========================================================================

    # evenly spaced grid
    xgrid, ygrid = np.mgrid[xmin:xmax+gridspacing:gridspacing,
                            ymin:ymax+gridspacing:gridspacing]
    xsize, ysize = xgrid.shape

    # convert evenly spaced grid to vtkPoints object
    probepoints = vtk.vtkPoints()
    probepoints.SetNumberOfPoints(xsize * ysize)
    probepointid = 0
    for i in range(xsize):
        for j in range(ysize):
            probepointx = xgrid[i, j]
            probepointy = ygrid[i, j]
            probepointz = zloc
            probepoint = (probepointx, probepointy, probepointz)
            probepoints.SetPoint(probepointid, probepoint)
            probepointid += 1
    probe = vtk.vtkPolyData()
    probe.SetPoints(probepoints)

    # probe the cfd result with evenly spaced grid
    prober = vtk.vtkProbeFilter()
    prober.SetInput(probe)
    prober.SetSource(cfd)
    prober.Update()
    xyslicegrid = prober.GetOutput()

    # create nparrays for vx and vy with same shape as xgrid and ygrid
    vxarray = xyslicegrid.GetPointData().GetArray('Vx_mm_s')
    vyarray = xyslicegrid.GetPointData().GetArray('Vy_mm_s')
    vx = np.empty(shape=(xsize, ysize))
    vy = np.empty(shape=(xsize, ysize))
    pointid = 0
    for i in range(xsize):
        for j in range(ysize):
            vx[i, j] = vxarray.GetValue(pointid)
            vy[i, j] = vyarray.GetValue(pointid)
            pointid += 1

    # streamline width is a function of vxy magnitude
    speed = np.sqrt(vx*vx + vy*vy)
    lw = 5 * speed / speed.max()

    # plot streamlines; arrays need to be transposed
    ax.streamplot(xgrid.T, ygrid.T, vx.T, vy.T, density=streamlinedensity,
                  color='.5', linewidth=lw.T)

    # draw y-axis
    ax.axvline(0, ymin, ymax, color='w', ls='-', lw=2, zorder=10)

    #==========================================================================
    # Set plot properties and write plot
    #==========================================================================

    # set axes labels and ticks
    ax.set_xlim(xmin, xmax)
    ax.set_ylim(ymin, ymax)
    ax.set_xlabel('x [mm]', fontsize=36)
    ax.set_ylabel('y [mm]', fontsize=36)
    plt.setp(ax.get_xticklabels(), fontsize=32)
    plt.setp(ax.get_yticklabels(), fontsize=32)
    if hidelabels:
        # do not show axes labels and ticks
        ax.get_xaxis().set_visible(False)
        ax.get_yaxis().set_visible(False)

    # write figure
    ax.set_aspect('equal')
    ax.set_rasterization_zorder(0)  # raster contourplot, vector rest
    fig.savefig(ofile, bbox_inches="tight", dpi=200)
    plt.close()