def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(
         self, module_manager,
         vtk.vtkProgrammableGlyphFilter(), 'Processing.',
         ('vtkDataSet', 'vtkPolyData'), ('vtkPolyData',),
         replaceDoc=True,
         inputFunctions=None, outputFunctions=None)
Exemplo n.º 2
0
def main():
    res = 6
    plane = vtk.vtkPlaneSource()
    plane.SetResolution(res, res)
    colors = vtk.vtkElevationFilter()
    colors.SetInputConnection(plane.GetOutputPort())
    colors.SetLowPoint(-0.25, -0.25, -0.25)
    colors.SetHighPoint(0.25, 0.25, 0.25)
    planeMapper = vtk.vtkPolyDataMapper()
    planeMapper.SetInputData(colors.GetPolyDataOutput())
    planeActor = vtk.vtkActor()
    planeActor.SetMapper(planeMapper)
    planeActor.GetProperty().SetRepresentationToWireframe()

    # create simple poly data so we can apply glyph
    squad = vtk.vtkSuperquadricSource()

    def Glyph():
        """
        # procedure for generating glyphs
        :return:
        """
        xyz = glypher.GetPoint()
        x = xyz[0]
        y = xyz[1]
        length = glypher.GetInput(0).GetLength()
        scale = length / (2.0 * res)

        squad.SetScale(scale, scale, scale)
        squad.SetCenter(xyz)
        squad.SetPhiRoundness(abs(x) * 5.0)
        squad.SetThetaRoundness(abs(y) * 5.0)

    glypher = vtk.vtkProgrammableGlyphFilter()
    glypher.SetInputConnection(colors.GetOutputPort())
    glypher.SetSourceConnection(squad.GetOutputPort())
    glypher.SetGlyphMethod(Glyph)
    glyphMapper = vtk.vtkPolyDataMapper()
    glyphMapper.SetInputConnection(glypher.GetOutputPort())
    glyphActor = vtk.vtkActor()
    glyphActor.SetMapper(glyphMapper)

    colors = vtk.vtkNamedColors()

    # Create the rendering stuff
    ren1 = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.SetMultiSamples(0)
    renWin.AddRenderer(ren1)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)
    ren1.AddActor(planeActor)
    ren1.AddActor(glyphActor)
    ren1.SetBackground(colors.GetColor3d('White'))
    renWin.SetSize(450, 450)
    renWin.Render()

    iren.Start()
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(self,
                                       module_manager,
                                       vtk.vtkProgrammableGlyphFilter(),
                                       'Processing.',
                                       ('vtkDataSet', 'vtkPolyData'),
                                       ('vtkPolyData', ),
                                       replaceDoc=True,
                                       inputFunctions=None,
                                       outputFunctions=None)
Exemplo n.º 4
0
    def __init__(self, centers, radii, alpha=1, color=(1,1,1)):
        self.polydata = vtk.vtkPolyData()
        self.polydata.SetPoints(self.pointArray(centers))
        self.radii = np.atleast_2d(radii)
        self.update()

        self.sphere_source = vtk.vtkSphereSource()
        self.glypher = vtk.vtkProgrammableGlyphFilter()
        self.glypher.SetInput(self.polydata)
        self.glypher.SetSource(self.sphere_source.GetOutput())
        self.glypher.SetGlyphMethod(self.glyph_method)

        self.mapper = vtk.vtkPolyDataMapper()
        self.mapper.SetInputConnection(self.glypher.GetOutputPort())
        self.SetMapper(self.mapper)

        self.GetProperty().SetOpacity(alpha)
        r,g,b = color
        self.mapper.SetScalarVisibility(False)
        self.GetProperty().SetColor(r,g,b)
Exemplo n.º 5
0
def renderBonds(visibleAtoms, mainWindow, pipelinePage, actorsDict,
                colouringOptions, povfile, scalarsDict, bondArray, NBondsArray,
                bondVectorArray, bondsOptions):
    """
    Render bonds.
    
    """
    renderBondsTime = time.time()
    logger = logging.getLogger(__name__)

    # SETTINGS
    bondThicknessVTK = bondsOptions.bondThicknessVTK
    bondThicknessPOV = bondsOptions.bondThicknessPOV
    bondNumSides = bondsOptions.bondNumSides
    # END SETTINGS

    # scalar type
    scalarType = getScalarsType(colouringOptions)

    # scalars array
    if scalarType == 5:
        scalars = scalarsDict[colouringOptions.colourBy]
    else:
        scalars = np.array([], dtype=np.float64)

    NVisible = len(visibleAtoms)

    NBondsHalf = np.sum(NBondsArray)
    NBonds = NBondsHalf * 2

    # povray file
    povFilePath = os.path.join(mainWindow.tmpDirectory, povfile)
    fpov = open(povFilePath, "w")

    lattice = pipelinePage.inputState

    # make LUT
    lut = setupLUT(lattice.specieList, lattice.specieRGB, colouringOptions)

    # number of species
    NSpecies = len(lattice.specieList)

    # vtk array storing coords of bonds
    bondCoords = vtk.vtkFloatArray()
    bondCoords.SetNumberOfComponents(3)
    bondCoords.SetNumberOfTuples(NBonds)

    # vtk array storing scalars (for lut)
    bondScalars = vtk.vtkFloatArray()
    bondScalars.SetNumberOfComponents(1)
    bondScalars.SetNumberOfTuples(NBonds)

    # vtk array storing vectors (for tube)
    bondVectors = vtk.vtkFloatArray()
    bondVectors.SetNumberOfComponents(3)
    bondVectors.SetNumberOfTuples(NBonds)

    # construct vtk bond arrays
    pov_rgb = np.empty(3, np.float64)
    pov_rgb2 = np.empty(3, np.float64)
    count = 0
    bcount = 0
    for i in range(NVisible):
        index = visibleAtoms[i]

        # scalar
        scalar = getScalarValue(lattice, index, scalars, i, colouringOptions)

        # colour for povray
        lut.GetColor(scalar, pov_rgb)

        # pos
        xpos = lattice.pos[3 * index]
        ypos = lattice.pos[3 * index + 1]
        zpos = lattice.pos[3 * index + 2]

        for _ in range(NBondsArray[i]):
            bondCoords.SetTuple3(bcount, xpos, ypos, zpos)
            bondVectors.SetTuple3(bcount, bondVectorArray[3 * count],
                                  bondVectorArray[3 * count + 1],
                                  bondVectorArray[3 * count + 2])
            bondScalars.SetTuple1(bcount, scalar)

            # povray bond
            fpov.write(
                povrayBond(
                    lattice.pos[3 * index:3 * index + 3],
                    lattice.pos[3 * index:3 * index + 3] +
                    bondVectorArray[3 * count:3 * count + 3], bondThicknessPOV,
                    pov_rgb, 0.0))

            bcount += 1

            # second half
            visIndex = bondArray[count]
            index2 = visibleAtoms[visIndex]

            scalar2 = getScalarValue(lattice, index2, scalars, visIndex,
                                     colouringOptions)

            bondCoords.SetTuple3(bcount, lattice.pos[3 * index2],
                                 lattice.pos[3 * index2 + 1],
                                 lattice.pos[3 * index2 + 2])
            bondVectors.SetTuple3(bcount, -1 * bondVectorArray[3 * count],
                                  -1 * bondVectorArray[3 * count + 1],
                                  -1 * bondVectorArray[3 * count + 2])
            bondScalars.SetTuple1(bcount, scalar2)

            # colour for povray
            lut.GetColor(scalar2, pov_rgb2)

            # povray bond
            fpov.write(
                povrayBond(
                    lattice.pos[3 * index2:3 * index2 + 3],
                    lattice.pos[3 * index2:3 * index2 + 3] -
                    bondVectorArray[3 * count:3 * count + 3], bondThicknessPOV,
                    pov_rgb2, 0.0))

            bcount += 1

            count += 1

    # points
    bondPoints = vtk.vtkPoints()
    bondPoints.SetData(bondCoords)

    # poly data
    bondPolyData = vtk.vtkPolyData()
    bondPolyData.SetPoints(bondPoints)
    bondPolyData.GetPointData().SetScalars(bondScalars)
    bondPolyData.GetPointData().SetVectors(bondVectors)

    # line source
    lineSource = vtk.vtkLineSource()

    # tubes
    tubes = vtk.vtkTubeFilter()
    tubes.SetInputConnection(lineSource.GetOutputPort())
    tubes.SetRadius(bondThicknessVTK)
    tubes.SetNumberOfSides(bondNumSides)
    tubes.SetCapping(1)

    # glyph filter
    bondGlyphFilter = vtk.vtkProgrammableGlyphFilter()
    bondGlyphFilter.SetGlyphMethod(
        functools.partial(bondGlyphMethod, bondGlyphFilter, lineSource))
    if vtk.vtkVersion.GetVTKMajorVersion() <= 5:
        bondGlyphFilter.SetSource(tubes.GetOutput())
        bondGlyphFilter.SetInput(bondPolyData)
    else:
        bondGlyphFilter.SetSourceConnection(tubes.GetOutputPort())
        bondGlyphFilter.SetInputData(bondPolyData)

    # mapper
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(bondGlyphFilter.GetOutputPort())
    mapper.SetLookupTable(lut)
    setMapperScalarRange(mapper, colouringOptions, NSpecies)

    # actor
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetOpacity(1)
    actor.GetProperty().SetLineWidth(bondThicknessVTK)

    # add to actors collection
    actorsDict["Bonds"] = utils.ActorObject(actor)

    # close pov file
    fpov.close()

    # time taken
    renderBondsTime = time.time() - renderBondsTime
    logger.debug("Render bonds time: %f s", renderBondsTime)
Exemplo n.º 6
0
def renderTraceVectors(visibleAtoms, mainWindow, pipelinePage, actorsDict,
                       colouringOptions, povfile, scalarsDict, numBonds,
                       bondVectorArray, drawBondVector, bondsOptions,
                       traceDict):
    """
    Render trace vectors
    
    """
    renderBondsTime = time.time()
    logger = logging.getLogger(__name__)
    logger.debug("Rendering trace vectors...")

    # SETTINGS
    bondThicknessVTK = bondsOptions.bondThicknessVTK
    bondThicknessPOV = bondsOptions.bondThicknessPOV
    bondNumSides = bondsOptions.bondNumSides
    # END SETTINGS

    # scalar type
    scalarType = getScalarsType(colouringOptions)

    # scalars array
    if scalarType == 5:
        scalars = scalarsDict[colouringOptions.colourBy]
    else:
        scalars = np.array([], dtype=np.float64)

    NVisible = len(visibleAtoms)

    # povray file
    povFilePath = os.path.join(mainWindow.tmpDirectory, povfile)
    fpov = open(povFilePath, "w")

    inputState = pipelinePage.inputState

    # make LUT
    lut = setupLUT(inputState.specieList, inputState.specieRGB,
                   colouringOptions)

    # number of species
    NSpecies = len(inputState.specieList)

    # update trace dict with latest bond vectors
    newd = {}
    for i in range(NVisible):
        index = visibleAtoms[i]

        if index in traceDict:
            newd[index] = traceDict[index]

        # do we add a new vector for this atom
        if drawBondVector[i]:
            mypos = copy.deepcopy(inputState.pos[3 * index:3 * index + 3])
            mybvect = copy.deepcopy(bondVectorArray[3 * i:3 * i + 3])
            myscal = getScalarValue(inputState, index, scalars, i,
                                    colouringOptions)

            if index in newd:
                newd[index].append((mypos, mybvect, myscal))

            else:
                newd[index] = [(mypos, mybvect, myscal)]

    # first pass to get size of arrays
    size = 0
    for key in list(newd.keys()):
        size += len(newd[key])

    logger.debug("Size of trace arrays = %d", size)

    # return if nothing to do
    if size == 0:
        return newd

    # make trace arrays
    traceCoords = np.empty((size, 3), np.float64)
    traceVectors = np.empty((size, 3), np.float64)
    traceScalars = np.empty(size, np.float64)
    pov_rgb = np.empty(3, np.float64)
    count = 0
    for key in list(newd.keys()):
        for mypos, mybvect, myscal in newd[key]:
            traceCoords[count][:] = mypos[:]
            traceVectors[count][:] = mybvect[:]
            traceScalars[count] = myscal

            count += 1

            # write POV-Ray vector
            lut.GetColor(myscal, pov_rgb)
            fpov.write(
                povrayBond(mypos, mypos + mybvect, bondThicknessPOV, pov_rgb,
                           0.0))

    # points
    points = vtk.vtkPoints()
    points.SetData(numpy_support.numpy_to_vtk(traceCoords, deep=1))

    # poly data
    polyData = vtk.vtkPolyData()
    polyData.SetPoints(points)
    polyData.GetPointData().SetScalars(
        numpy_support.numpy_to_vtk(traceScalars, deep=1))
    polyData.GetPointData().SetVectors(
        numpy_support.numpy_to_vtk(traceVectors, deep=1))

    # line source
    lineSource = vtk.vtkLineSource()

    # tubes
    tubes = vtk.vtkTubeFilter()
    tubes.SetInputConnection(lineSource.GetOutputPort())
    tubes.SetRadius(bondThicknessVTK)
    tubes.SetNumberOfSides(bondNumSides)
    tubes.SetCapping(1)

    # glyph filter
    glyphFilter = vtk.vtkProgrammableGlyphFilter()
    glyphFilter.SetGlyphMethod(
        functools.partial(bondGlyphMethod, glyphFilter, lineSource))
    if vtk.vtkVersion.GetVTKMajorVersion() <= 5:
        glyphFilter.SetSource(tubes.GetOutput())
        glyphFilter.SetInput(polyData)
    else:
        glyphFilter.SetSourceConnection(tubes.GetOutputPort())
        glyphFilter.SetInputData(polyData)

    # mapper
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(glyphFilter.GetOutputPort())
    mapper.SetLookupTable(lut)
    setMapperScalarRange(mapper, colouringOptions, NSpecies)

    # actor
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetOpacity(1)
    actor.GetProperty().SetLineWidth(bondThicknessVTK)

    # add to actors collection
    actorsDict["Trace vectors"] = utils.ActorObject(actor)

    # close pov file
    fpov.close()

    # time taken
    renderBondsTime = time.time() - renderBondsTime
    logger.debug("Render trace vectors time: %f s", renderBondsTime)

    return newd
Exemplo n.º 7
0
    def render(self, bondCoords, bondVectors, bondScalars, numSpecies,
               colouringOptions, bondsOptions, lut):
        """
        Render the given bonds.
        
        """
        self._logger.debug("Rendering bonds")

        renderBondsTime = time.time()

        # SETTINGS
        bondThicknessVTK = bondsOptions.bondThicknessVTK
        bondNumSides = bondsOptions.bondNumSides
        # END SETTINGS

        # points
        bondPoints = vtk.vtkPoints()
        bondPoints.SetData(bondCoords.getVTK())

        # poly data
        bondPolyData = vtk.vtkPolyData()
        bondPolyData.SetPoints(bondPoints)
        bondPolyData.GetPointData().SetScalars(bondScalars.getVTK())
        bondPolyData.GetPointData().SetVectors(bondVectors.getVTK())

        # line source
        lineSource = vtk.vtkLineSource()

        # tubes
        tubes = vtk.vtkTubeFilter()
        tubes.SetInputConnection(lineSource.GetOutputPort())
        tubes.SetRadius(bondThicknessVTK)
        tubes.SetNumberOfSides(bondNumSides)
        tubes.SetCapping(1)

        # glyph filter
        bondGlyphFilter = vtk.vtkProgrammableGlyphFilter()
        bondGlyphFilter.SetGlyphMethod(
            functools.partial(_bondGlyphMethod, bondGlyphFilter, lineSource))
        if vtk.vtkVersion.GetVTKMajorVersion() <= 5:
            bondGlyphFilter.SetSource(tubes.GetOutput())
            bondGlyphFilter.SetInput(bondPolyData)
        else:
            bondGlyphFilter.SetSourceConnection(tubes.GetOutputPort())
            bondGlyphFilter.SetInputData(bondPolyData)

        # mapper
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(bondGlyphFilter.GetOutputPort())
        mapper.SetLookupTable(lut)
        utils.setMapperScalarRange(mapper, colouringOptions, numSpecies)

        # actor
        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
        actor.GetProperty().SetOpacity(1)
        actor.GetProperty().SetLineWidth(bondThicknessVTK)

        # time taken
        renderBondsTime = time.time() - renderBondsTime
        self._logger.debug("Render bonds time: %f s", renderBondsTime)

        # store attributes
        self._actor = utils.ActorObject(actor)
        self._data["Points"] = bondCoords
        self._data["Scalars"] = bondScalars
        self._data["Vectors"] = bondVectors
        self._data["LUT"] = lut
        self._data["Bond thickness"] = bondsOptions.bondThicknessPOV
Exemplo n.º 8
0
    length = glypher.GetInput(0).GetLength()
    scale = expr.expr(globals(), locals(),
                      ["length", "/", "(", "2.0", "*", "res", ")"])
    squad.SetScale(scale, scale, scale)
    squad.SetCenter(xyz)
    squad.SetPhiRoundness(
        expr.expr(globals(), locals(), ["abs", "(", "x", ")*", "5.0"]))
    squad.SetThetaRoundness(
        expr.expr(globals(), locals(), ["abs", "(", "y", ")*", "5.0"]))
    squad.Update()


# create simple poly data so we can apply glyph
squad = vtk.vtkSuperquadricSource()
squad.Update()
glypher = vtk.vtkProgrammableGlyphFilter()
glypher.SetInputConnection(colors.GetOutputPort())
glypher.SetSourceData(squad.GetOutput())
glypher.SetGlyphMethod(Glyph)
glyphMapper = vtk.vtkPolyDataMapper()
glyphMapper.SetInputConnection(glypher.GetOutputPort())
glyphActor = vtk.vtkActor()
glyphActor.SetMapper(glyphMapper)
# Create the rendering stuff
#
ren1 = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.SetMultiSamples(0)
renWin.AddRenderer(ren1)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
Exemplo n.º 9
0
    xyz = glypher.GetPoint()
    x = lindex(xyz, 0)
    y = lindex(xyz, 1)
    length = glypher.GetInput(0).GetLength()
    scale = expr.expr(globals(), locals(), ["length", "/", "(", "2.0", "*", "res", ")"])
    squad.SetScale(scale, scale, scale)
    squad.SetCenter(xyz)
    squad.SetPhiRoundness(expr.expr(globals(), locals(), ["abs", "(", "x", ")*", "5.0"]))
    squad.SetThetaRoundness(expr.expr(globals(), locals(), ["abs", "(", "y", ")*", "5.0"]))
    squad.Update()


# create simple poly data so we can apply glyph
squad = vtk.vtkSuperquadricSource()
squad.Update()
glypher = vtk.vtkProgrammableGlyphFilter()
glypher.SetInputConnection(colors.GetOutputPort())
glypher.SetSourceData(squad.GetOutput())
glypher.SetGlyphMethod(Glyph)
glyphMapper = vtk.vtkPolyDataMapper()
glyphMapper.SetInputConnection(glypher.GetOutputPort())
glyphActor = vtk.vtkActor()
glyphActor.SetMapper(glyphMapper)
# Create the rendering stuff
#
ren1 = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.SetMultiSamples(0)
renWin.AddRenderer(ren1)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
Exemplo n.º 10
0
 def render(self, bondCoords, bondVectors, bondScalars, numSpecies, colouringOptions, bondsOptions, lut):
     """
     Render the given bonds.
     
     """
     self._logger.debug("Rendering bonds")
     
     renderBondsTime = time.time()
     
     # SETTINGS
     bondThicknessVTK = bondsOptions.bondThicknessVTK
     bondNumSides = bondsOptions.bondNumSides
     # END SETTINGS
     
     # points
     bondPoints = vtk.vtkPoints()
     bondPoints.SetData(bondCoords.getVTK())
     
     # poly data
     bondPolyData = vtk.vtkPolyData()
     bondPolyData.SetPoints(bondPoints)
     bondPolyData.GetPointData().SetScalars(bondScalars.getVTK())
     bondPolyData.GetPointData().SetVectors(bondVectors.getVTK())
     
     # line source
     lineSource = vtk.vtkLineSource()
     
     # tubes
     tubes = vtk.vtkTubeFilter()
     tubes.SetInputConnection(lineSource.GetOutputPort())
     tubes.SetRadius(bondThicknessVTK)
     tubes.SetNumberOfSides(bondNumSides)
     tubes.SetCapping(1)
     
     # glyph filter
     bondGlyphFilter = vtk.vtkProgrammableGlyphFilter()
     bondGlyphFilter.SetGlyphMethod(functools.partial(_bondGlyphMethod, bondGlyphFilter, lineSource))
     if vtk.vtkVersion.GetVTKMajorVersion() <= 5:
         bondGlyphFilter.SetSource(tubes.GetOutput())
         bondGlyphFilter.SetInput(bondPolyData)
     else:
         bondGlyphFilter.SetSourceConnection(tubes.GetOutputPort())
         bondGlyphFilter.SetInputData(bondPolyData)
     
     # mapper
     mapper = vtk.vtkPolyDataMapper()
     mapper.SetInputConnection(bondGlyphFilter.GetOutputPort())
     mapper.SetLookupTable(lut)
     utils.setMapperScalarRange(mapper, colouringOptions, numSpecies)
     
     # actor
     actor = vtk.vtkActor()
     actor.SetMapper(mapper)
     actor.GetProperty().SetOpacity(1)
     actor.GetProperty().SetLineWidth(bondThicknessVTK)
     
     # time taken
     renderBondsTime = time.time() - renderBondsTime
     self._logger.debug("Render bonds time: %f s", renderBondsTime)
     
     # store attributes
     self._actor = utils.ActorObject(actor)
     self._data["Points"] = bondCoords
     self._data["Scalars"] = bondScalars
     self._data["Vectors"] = bondVectors
     self._data["LUT"] = lut
     self._data["Bond thickness"] = bondsOptions.bondThicknessPOV
Exemplo n.º 11
0
def renderBonds(visibleAtoms, mainWindow, pipelinePage, actorsDict, colouringOptions, povfile, 
                scalarsDict, bondArray, NBondsArray, bondVectorArray, bondsOptions):
    """
    Render bonds.
    
    """
    renderBondsTime = time.time()
    logger = logging.getLogger(__name__)
    
    # SETTINGS
    bondThicknessVTK = bondsOptions.bondThicknessVTK
    bondThicknessPOV = bondsOptions.bondThicknessPOV
    bondNumSides = bondsOptions.bondNumSides
    # END SETTINGS
    
    # scalar type
    scalarType = getScalarsType(colouringOptions)
    
    # scalars array
    if scalarType == 5:
        scalars = scalarsDict[colouringOptions.colourBy]
    else:
        scalars = np.array([], dtype=np.float64)
    
    NVisible = len(visibleAtoms)
    
    NBondsHalf = np.sum(NBondsArray)
    NBonds = NBondsHalf * 2
    
    # povray file
    povFilePath = os.path.join(mainWindow.tmpDirectory, povfile)
    fpov = open(povFilePath, "w")
    
    lattice = pipelinePage.inputState
    
    # make LUT
    lut = setupLUT(lattice.specieList, lattice.specieRGB, colouringOptions)
    
    # number of species
    NSpecies = len(lattice.specieList)
    
    # vtk array storing coords of bonds
    bondCoords = vtk.vtkFloatArray()
    bondCoords.SetNumberOfComponents(3)
    bondCoords.SetNumberOfTuples(NBonds)
    
    # vtk array storing scalars (for lut)
    bondScalars = vtk.vtkFloatArray()
    bondScalars.SetNumberOfComponents(1)
    bondScalars.SetNumberOfTuples(NBonds)
    
    # vtk array storing vectors (for tube)
    bondVectors = vtk.vtkFloatArray()
    bondVectors.SetNumberOfComponents(3)
    bondVectors.SetNumberOfTuples(NBonds)
    
    # construct vtk bond arrays
    pov_rgb = np.empty(3, np.float64)
    pov_rgb2 = np.empty(3, np.float64)
    count = 0
    bcount = 0
    for i in range(NVisible):
        index = visibleAtoms[i]
        
        # scalar
        scalar = getScalarValue(lattice, index, scalars, i, colouringOptions)
        
        # colour for povray
        lut.GetColor(scalar, pov_rgb)
        
        # pos
        xpos = lattice.pos[3*index]
        ypos = lattice.pos[3*index+1]
        zpos = lattice.pos[3*index+2]
        
        for _ in range(NBondsArray[i]):
            bondCoords.SetTuple3(bcount, xpos, ypos, zpos)
            bondVectors.SetTuple3(bcount, bondVectorArray[3*count], bondVectorArray[3*count+1], bondVectorArray[3*count+2])
            bondScalars.SetTuple1(bcount, scalar)
            
            # povray bond
            fpov.write(povrayBond(lattice.pos[3*index:3*index+3], 
                                  lattice.pos[3*index:3*index+3] + bondVectorArray[3*count:3*count+3], 
                                  bondThicknessPOV, pov_rgb, 0.0))
            
            bcount += 1
            
            # second half
            visIndex = bondArray[count]
            index2 = visibleAtoms[visIndex]
            
            scalar2 = getScalarValue(lattice, index2, scalars, visIndex, colouringOptions)
            
            bondCoords.SetTuple3(bcount, lattice.pos[3*index2], lattice.pos[3*index2+1], lattice.pos[3*index2+2])
            bondVectors.SetTuple3(bcount, -1 * bondVectorArray[3*count], -1 * bondVectorArray[3*count+1], -1 * bondVectorArray[3*count+2])
            bondScalars.SetTuple1(bcount, scalar2)
            
            # colour for povray
            lut.GetColor(scalar2, pov_rgb2)
            
            # povray bond
            fpov.write(povrayBond(lattice.pos[3*index2:3*index2+3], 
                                  lattice.pos[3*index2:3*index2+3] - bondVectorArray[3*count:3*count+3], 
                                  bondThicknessPOV, pov_rgb2, 0.0))
            
            bcount += 1
            
            count += 1
    
    # points
    bondPoints = vtk.vtkPoints()
    bondPoints.SetData(bondCoords)
    
    # poly data
    bondPolyData = vtk.vtkPolyData()
    bondPolyData.SetPoints(bondPoints)
    bondPolyData.GetPointData().SetScalars(bondScalars)
    bondPolyData.GetPointData().SetVectors(bondVectors)
    
    # line source
    lineSource = vtk.vtkLineSource()
    
    # tubes
    tubes = vtk.vtkTubeFilter()
    tubes.SetInputConnection(lineSource.GetOutputPort())
    tubes.SetRadius(bondThicknessVTK)
    tubes.SetNumberOfSides(bondNumSides)
    tubes.SetCapping(1)
    
    # glyph filter
    bondGlyphFilter = vtk.vtkProgrammableGlyphFilter()
    bondGlyphFilter.SetGlyphMethod(functools.partial(bondGlyphMethod, bondGlyphFilter, lineSource))
    if vtk.vtkVersion.GetVTKMajorVersion() <= 5:
        bondGlyphFilter.SetSource(tubes.GetOutput())
        bondGlyphFilter.SetInput(bondPolyData)
    else:
        bondGlyphFilter.SetSourceConnection(tubes.GetOutputPort())
        bondGlyphFilter.SetInputData(bondPolyData)
    
    # mapper
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(bondGlyphFilter.GetOutputPort())
    mapper.SetLookupTable(lut)
    setMapperScalarRange(mapper, colouringOptions, NSpecies)
    
    # actor
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetOpacity(1)
    actor.GetProperty().SetLineWidth(bondThicknessVTK)
    
    # add to actors collection
    actorsDict["Bonds"] = utils.ActorObject(actor)
    
    # close pov file
    fpov.close()
    
    # time taken
    renderBondsTime = time.time() - renderBondsTime
    logger.debug("Render bonds time: %f s", renderBondsTime)
Exemplo n.º 12
0
def renderTraceVectors(visibleAtoms, mainWindow, pipelinePage, actorsDict, colouringOptions, povfile, 
                       scalarsDict, numBonds, bondVectorArray, drawBondVector, bondsOptions, traceDict):
    """
    Render trace vectors
    
    """
    renderBondsTime = time.time()
    logger = logging.getLogger(__name__)
    logger.debug("Rendering trace vectors...")
    
    # SETTINGS
    bondThicknessVTK = bondsOptions.bondThicknessVTK
    bondThicknessPOV = bondsOptions.bondThicknessPOV
    bondNumSides = bondsOptions.bondNumSides
    # END SETTINGS
    
    # scalar type
    scalarType = getScalarsType(colouringOptions)
    
    # scalars array
    if scalarType == 5:
        scalars = scalarsDict[colouringOptions.colourBy]
    else:
        scalars = np.array([], dtype=np.float64)
    
    NVisible = len(visibleAtoms)
    
    # povray file
    povFilePath = os.path.join(mainWindow.tmpDirectory, povfile)
    fpov = open(povFilePath, "w")
    
    inputState = pipelinePage.inputState
    
    # make LUT
    lut = setupLUT(inputState.specieList, inputState.specieRGB, colouringOptions)
    
    # number of species
    NSpecies = len(inputState.specieList)
    
    # update trace dict with latest bond vectors
    newd = {}
    for i in range(NVisible):
        index = visibleAtoms[i]
        
        if index in traceDict:
            newd[index] = traceDict[index]
        
        # do we add a new vector for this atom
        if drawBondVector[i]:
            mypos = copy.deepcopy(inputState.pos[3*index:3*index+3])
            mybvect = copy.deepcopy(bondVectorArray[3*i:3*i+3])
            myscal = getScalarValue(inputState, index, scalars, i, colouringOptions)
            
            if index in newd:
                newd[index].append((mypos, mybvect, myscal))
            
            else:
                newd[index] = [(mypos, mybvect, myscal)]
    
    # first pass to get size of arrays
    size = 0
    for key in list(newd.keys()):
        size += len(newd[key])
    
    logger.debug("Size of trace arrays = %d", size)
    
    # return if nothing to do
    if size == 0:
        return newd
    
    # make trace arrays
    traceCoords = np.empty((size, 3), np.float64)
    traceVectors = np.empty((size, 3), np.float64)
    traceScalars = np.empty(size, np.float64)
    pov_rgb = np.empty(3, np.float64)
    count = 0
    for key in list(newd.keys()):
        for mypos, mybvect, myscal in newd[key]:
            traceCoords[count][:] = mypos[:]
            traceVectors[count][:] = mybvect[:]
            traceScalars[count] = myscal
            
            count += 1
            
            # write POV-Ray vector
            lut.GetColor(myscal, pov_rgb)
            fpov.write(povrayBond(mypos, 
                                  mypos + mybvect, 
                                  bondThicknessPOV, pov_rgb, 0.0))
    
    # points
    points = vtk.vtkPoints()
    points.SetData(numpy_support.numpy_to_vtk(traceCoords, deep=1))
    
    # poly data
    polyData = vtk.vtkPolyData()
    polyData.SetPoints(points)
    polyData.GetPointData().SetScalars(numpy_support.numpy_to_vtk(traceScalars, deep=1))
    polyData.GetPointData().SetVectors(numpy_support.numpy_to_vtk(traceVectors, deep=1))
    
    # line source
    lineSource = vtk.vtkLineSource()
    
    # tubes
    tubes = vtk.vtkTubeFilter()
    tubes.SetInputConnection(lineSource.GetOutputPort())
    tubes.SetRadius(bondThicknessVTK)
    tubes.SetNumberOfSides(bondNumSides)
    tubes.SetCapping(1)
    
    # glyph filter
    glyphFilter = vtk.vtkProgrammableGlyphFilter()
    glyphFilter.SetGlyphMethod(functools.partial(bondGlyphMethod, glyphFilter, lineSource))
    if vtk.vtkVersion.GetVTKMajorVersion() <= 5:
        glyphFilter.SetSource(tubes.GetOutput())
        glyphFilter.SetInput(polyData)
    else:
        glyphFilter.SetSourceConnection(tubes.GetOutputPort())
        glyphFilter.SetInputData(polyData)
    
    # mapper
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(glyphFilter.GetOutputPort())
    mapper.SetLookupTable(lut)
    setMapperScalarRange(mapper, colouringOptions, NSpecies)
    
    # actor
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetOpacity(1)
    actor.GetProperty().SetLineWidth(bondThicknessVTK)
    
    # add to actors collection
    actorsDict["Trace vectors"] = utils.ActorObject(actor)
    
    # close pov file
    fpov.close()
    
    # time taken
    renderBondsTime = time.time() - renderBondsTime
    logger.debug("Render trace vectors time: %f s", renderBondsTime)
    
    return newd
Exemplo n.º 13
0
    def Execute(self):
        if self.Surface == None:
            self.PrintError("Error: No input surface.")

        if not self.vmtkRenderer:
            self.vmtkRenderer = vmtkrenderer.vmtkRenderer()
            self.vmtkRenderer.Initialize()
            self.OwnRenderer = 1

        self.vmtkRenderer.RegisterScript(self)

        self.DeformedSurface = self.Surface

        sphereSource = vtk.vtkSphereSource()
        sphereSource.SetRadius(1)

        self.SourceGlyphs = vtk.vtkGlyph3D()
        self.SourceGlyphs.SetInput(self.SourceSpheres)
        self.SourceGlyphs.SetSource(sphereSource.GetOutput())
        self.SourceGlyphs.SetScaleModeToDataScalingOff()
        self.SourceGlyphs.SetScaleFactor(self.Surface.GetLength() * 0.01)
        self.SourceGlyphs.GeneratePointIdsOn()
        self.SourceGlyphMapper = vtk.vtkPolyDataMapper()
        self.SourceGlyphMapper.SetInput(self.SourceGlyphs.GetOutput())
        self.SourceGlyphMapper.ScalarVisibilityOff()
        self.SourcePointActor = vtk.vtkActor()
        self.SourcePointActor.SetMapper(self.SourceGlyphMapper)
        self.SourcePointActor.GetProperty().SetColor(1.0, 0.0, 0.0)
        self.SourcePointActor.GetProperty().SetOpacity(self.Opacity)
        self.SourcePointActor.PickableOff()
        self.vmtkRenderer.Renderer.AddActor(self.SourcePointActor)

        self.TargetGlyphs = vtk.vtkGlyph3D()
        self.TargetGlyphs.SetInput(self.TargetSpheres)
        self.TargetGlyphs.SetSource(sphereSource.GetOutput())
        self.TargetGlyphs.SetScaleModeToDataScalingOff()
        self.TargetGlyphs.SetScaleFactor(self.Surface.GetLength() * 0.01)
        self.TargetGlyphs.GeneratePointIdsOn()
        self.TargetGlyphMapper = vtk.vtkPolyDataMapper()
        self.TargetGlyphMapper.SetInput(self.TargetGlyphs.GetOutput())
        self.TargetGlyphMapper.ScalarVisibilityOff()
        self.TargetPointActor = vtk.vtkActor()
        self.TargetPointActor.SetMapper(self.TargetGlyphMapper)
        self.TargetPointActor.GetProperty().SetColor(0.0, 0.0, 1.0)
        self.TargetPointActor.GetProperty().SetOpacity(self.Opacity)
        self.TargetPointActor.PickableOff()
        self.vmtkRenderer.Renderer.AddActor(self.TargetPointActor)

        self.CylinderSource = vtk.vtkCylinderSource()
        self.CylinderSource.SetCenter(0, 0, 0)
        self.CylinderSource.SetRadius(self.Surface.GetLength() * 0.0025)
        self.CylinderSource.SetHeight(0)

        self.CylinderTransform = vtk.vtkTransform()
        self.CylinderTransform.Identity()

        self.CylinderTransformFilter = vtk.vtkTransformPolyDataFilter()
        self.CylinderTransformFilter.SetTransform(self.CylinderTransform)
        self.CylinderTransformFilter.SetInputConnection(self.CylinderSource.GetOutputPort())

        self.DisplacementGlyphs = vtk.vtkProgrammableGlyphFilter()
        self.DisplacementGlyphs.SetInput(self.SourceSpheres)
        self.DisplacementGlyphs.SetSource(self.CylinderTransformFilter.GetOutput())
        self.DisplacementGlyphs.SetGlyphMethod(self.PlaceCylinder)
        self.DisplacementGlyphsMapper = vtk.vtkPolyDataMapper()
        self.DisplacementGlyphsMapper.SetInput(self.DisplacementGlyphs.GetOutput())
        self.DisplacementGlyphsMapper.ScalarVisibilityOff()
        self.DisplacementGlyphsActor = vtk.vtkActor()
        self.DisplacementGlyphsActor.SetMapper(self.DisplacementGlyphsMapper)
        self.DisplacementGlyphsActor.GetProperty().SetColor(0.0, 1.0, 0.0)
        self.DisplacementGlyphsActor.GetProperty().SetOpacity(self.Opacity)
        self.DisplacementGlyphsActor.PickableOff()
        self.vmtkRenderer.Renderer.AddActor(self.DisplacementGlyphsActor)

        # self.vmtkRenderer.RenderWindowInteractor.AddObserver("KeyPressEvent", self.KeyPressed)
        self.vmtkRenderer.AddKeyBinding("u", "Undo.", self.UndoCallback)
        self.vmtkRenderer.AddKeyBinding("space", "Add displacement.", self.PickCallback)
        self.vmtkRenderer.AddKeyBinding("s", "Select source/target.", self.SelectCallback)
        self.vmtkRenderer.AddKeyBinding("n", "Skip to next source/target.", self.NextCallback)
        self.vmtkRenderer.AddKeyBinding("v", "Skip to previous source/target.", self.PreviousCallback)
        self.vmtkRenderer.AddKeyBinding("x", "Delete source/target.", self.DeleteCallback)
        self.vmtkRenderer.AddKeyBinding("r", "Reset target to source.", self.ResetCallback)
        self.vmtkRenderer.AddKeyBinding("d", "Show deformed surface.", self.ShowDeformedCallback)

        self.SurfaceMapper = vtk.vtkPolyDataMapper()
        self.SurfaceMapper.SetInput(self.Surface)
        self.SurfaceMapper.SetScalarVisibility(0)
        surfaceActor = vtk.vtkActor()
        surfaceActor.SetMapper(self.SurfaceMapper)
        surfaceActor.GetProperty().SetOpacity(self.Opacity)
        self.vmtkRenderer.Renderer.AddActor(surfaceActor)

        self.SphereWidget = vtk.vtkSphereWidget()
        self.SphereWidget.SetRadius(self.Surface.GetLength() * 0.01)
        self.SphereWidget.SetInteractor(self.vmtkRenderer.RenderWindowInteractor)
        self.SphereWidget.AddObserver("InteractionEvent", self.SphereCallback)

        self.InputInfo("Please position the mouse and press space to add source and target points, 'u' to undo\n")

        self.InitializeSpheres()
        self.vmtkRenderer.Render()

        if self.Surface.GetSource():
            self.Surface.GetSource().UnRegisterAllOutputs()

        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()