Exemplo n.º 1
0
def addblockid(ug):
    # get number of elements in ug:
    nele = int(ug.GetNumberOfCells())
    # add blockID to ug (required by the ensight format)
    blockIDs = vtk.vtkUnsignedIntArray()
    blockIDs.SetNumberOfTuples(nele)
    blockIDs.SetNumberOfComponents(1)
    blockIDs.SetName("BlockId")
    for j in range(nele):
        blockIDs.SetValue(j,1)
    ug.GetCellData().AddArray(blockIDs)
    return ug
Exemplo n.º 2
0
def addblockid(ug):
    # get number of elements in ug:
    nele = int(ug.GetNumberOfCells())
    # add blockID to ug (required by the ensight format)
    blockIDs = vtk.vtkUnsignedIntArray()
    blockIDs.SetNumberOfTuples(nele)
    blockIDs.SetNumberOfComponents(1)
    blockIDs.SetName("BlockId")
    for j in range(nele):
        blockIDs.SetValue(j,1)
    ug.GetCellData().AddArray(blockIDs)
    return ug
def createUnsignedIntArray(name,
                           n_components=1,
                           n_tuples=0,
                           init_to_zero=0,
                           verbose=0):

    uiarray = vtk.vtkUnsignedIntArray()
    uiarray.SetName(name)
    uiarray.SetNumberOfComponents(n_components)
    uiarray.SetNumberOfTuples(n_tuples)

    if (init_to_zero):
        for k_tuple in xrange(n_tuples):
            uiarray.SetTuple(k_tuple, [0] * n_components)

    return uiarray
def createUnsignedIntArray(name,
                           n_components=1,
                           n_tuples=0,
                           init_to_zero=0,
                           verbose=0):

    array = vtk.vtkUnsignedIntArray()
    array.SetName(name)
    array.SetNumberOfComponents(n_components)
    array.SetNumberOfTuples(n_tuples)

    if (init_to_zero):
        for k_component in range(n_components):
            array.FillComponent(k_component, 0.)

    return array
def createUnsignedIntArray(
        name,
        n_components=1,
        n_tuples=0,
        init_to_zero=0,
        verbose=0):

    uiarray = vtk.vtkUnsignedIntArray()
    uiarray.SetName(name)
    uiarray.SetNumberOfComponents(n_components)
    uiarray.SetNumberOfTuples(n_tuples)

    if (init_to_zero):
        for k_tuple in xrange(n_tuples):
            uiarray.SetTuple(k_tuple, [0]*n_components)

    return uiarray
Exemplo n.º 6
0
def prepareDelaunayData(dimension, agg_globalnodeidx, global_nodecoords, aggpolygons, aggid, aggid2nodes, aggid2procs):
    local_nodeidx2global_nodeidx = {}
    no_of_aggnodes = len(agg_globalnodeidx)
    dim = len(global_nodecoords[0])

    no_aggs = len(aggid2nodes)

    Points = vtk.vtkPoints()
    Vertices = vtk.vtkCellArray()

    for i in range(0, len(agg_globalnodeidx)):
        local_nodeidx2global_nodeidx[i] = agg_globalnodeidx[i]
        nodecoords = global_nodecoords[int(agg_globalnodeidx[i])]
        if dimension == 2:
            id = Points.InsertNextPoint(nodecoords[0], nodecoords[1], 0.0)
        elif dimension == 3:
            id = Points.InsertNextPoint(
                nodecoords[0] + 0.001 * random.random(),
                nodecoords[1] + 0.001 * random.random(),
                nodecoords[2] + 0.001 * random.random(),
            )
        Vertices.InsertNextCell(1)
        Vertices.InsertCellPoint(id)

    # create polygon for current aggregate
    polydata = vtk.vtkPolyData()
    polydata.SetPoints(Points)
    polydata.SetVerts(Vertices)
    polydata.Modified()
    polydata.Update()

    polydata2 = vtk.vtkPolyData()
    if Points.GetNumberOfPoints() > 2:  # todo: avoid error messages + add support for lines/surfaces
        # create delaunay object
        if dimension == 2:
            delaunay = vtk.vtkDelaunay2D()
        elif dimension == 3:
            delaunay = vtk.vtkDelaunay3D()
            # delaunay.SetAlpha(0.1)
        delaunay.SetInput(polydata)
        delaunay.Update()

        # create surfaceFilter
        surfaceFilter = vtk.vtkDataSetSurfaceFilter()
        surfaceFilter.SetInputConnection(delaunay.GetOutputPort())
        surfaceFilter.Update()

        polydata2 = surfaceFilter.GetOutput()

    lookupTable = vtk.vtkLookupTable()
    lookupTable.SetNumberOfTableValues(no_aggs)
    lookupTable.Build()

    Ids = vtk.vtkUnsignedIntArray()
    Ids.SetNumberOfComponents(1)
    Ids.SetName("Ids")
    for i in range(0, Points.GetNumberOfPoints()):
        Ids.InsertNextTuple1(int(aggid))
    Ids.SetLookupTable(lookupTable)

    Procs = vtk.vtkUnsignedCharArray()
    Procs.SetNumberOfComponents(1)
    Procs.SetName("proc")
    for i in range(0, Points.GetNumberOfPoints()):
        Procs.InsertNextTuple1(aggid2procs[aggid])

    polydata2.SetPoints(Points)
    polydata2.SetVerts(Vertices)
    polydata2.GetPointData().SetScalars(Ids)
    polydata2.GetPointData().AddArray(Procs)
    polydata2.Modified()
    polydata2.Update()

    aggpolygons.AddInput(polydata2)
Exemplo n.º 7
0
def om_display_vtk(f,d = 0,n = 0):
    """
    This function displays a VTK::vtk file generated with OpenMEEG.
    Such a file defines a polydata, containing points and triangles of a single
    mesh. Most often a EEG helmet mesh and associated leadfield.
    """
    welcome = """Welcome\n\n
    Move the slider to see all sources (columns of the input matrix)\n
    Press 'r': To select points/cells.\n"""

    # This callback function does updates the mappers for where n is the slider value
    def CleanPickData(object, event):
        ren.RemoveActor(selactor)
        PickData(object, event, selactor, 0, view, text_init)

    def SelectSource(object, event): # object will be the slider2D
        slidervalue = int(round(object.GetRepresentation().GetValue()))
        mapper.GetInput().GetPointData().SetActiveScalars("Potentials-"+str(slidervalue))
        renWin.SetWindowName(renWin.GetWindowName()[0:(renWin.GetWindowName().find('-')+1)]+str(slidervalue))
        UpdateColorBar(colorBar, mapper)

    # A window with an interactor
    renWin = vtk.vtkRenderWindow()
    renWin.SetSize(600, 600)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)
    iren.SetInteractorStyle(vtk.vtkInteractorStyleRubberBandPick())
    # A picker (to pick points/cells)
    picker = vtk.vtkRenderedAreaPicker()
    iren.SetPicker(picker)
    # Read the input file
    reader = vtk.vtkPolyDataReader()
    reader.SetFileName(f); reader.Update()
    poly = reader.GetOutput()
    renWin.SetWindowName(f+' Potentials-'+str(n))
    # determine the number of sources
    nb_sources = 0
    for i in range(poly.GetPointData().GetNumberOfArrays()):
        if poly.GetPointData().GetGlobalIds('Potentials-'+str(i)):
            nb_sources += 1
    if nb_sources == 0: #the file doesn't provide potentials
        if not d.__class__ == int:
            assert(d.shape[0] == poly.GetNumberOfPoints())
            nb_sources = d.shape[1]
            pot = [vtk.vtkDoubleArray() for j in range(d.shape[1])]
            for j in range(d.shape[1]):
                pot[j].SetName('Potentials-'+str(j))
                for i in range(d.shape[0]):
                    pot[j].InsertNextValue(d[i,j])
                poly.GetPointData().AddArray(pot[j])
            poly.Update()
        if not poly.GetPointData().GetGlobalIds('Indices'):
            ind = vtk.vtkUnsignedIntArray()
            ind.SetName('Indices')
            for i in range(poly.GetNumberOfPoints()):
                ind.InsertNextValue(i)
            poly.GetPointData().AddArray(ind)

    poly.GetPointData().SetActiveScalars('Potentials-'+str(n))

    mapper   = vtk.vtkPolyDataMapper()
    colorBar = vtk.vtkScalarBarActor()
    actor    = vtk.vtkActor()
    ren      = vtk.vtkRenderer()
    mapper.SetInput(poly)
    mapper.SetScalarModeToUsePointData(); mapper.Update()
    actor.SetMapper(mapper)
    ren.AddActor(actor)
    if nb_sources:
        ren.AddActor2D(colorBar)
        UpdateColorBar(colorBar, mapper)
    renWin.AddRenderer(ren)
    renWin.Render()

    if nb_sources > 1:
        # Slider
        sliderWidget = vtk.vtkSliderWidget()
        slider = vtk.vtkSliderRepresentation2D(); slider.SetMaximumValue(nb_sources-1)
        slider.SetValue(n); slider.SetEndCapLength(0.01); slider.SetLabelFormat('%1.0f')
        slider.SetSliderWidth(0.05); slider.SetSliderLength(1./nb_sources)
        slider.GetPoint1Coordinate().SetCoordinateSystemToNormalizedViewport()
        slider.GetPoint1Coordinate().SetValue(.0, 0.02)
        slider.GetPoint2Coordinate().SetCoordinateSystemToNormalizedViewport()
        slider.GetPoint2Coordinate().SetValue(1., 0.02);
        sliderWidget.SetInteractor(iren); sliderWidget.SetRepresentation(slider);
        sliderWidget.SetAnimationModeToAnimate(); sliderWidget.EnabledOn();
        sliderWidget.AddObserver("InteractionEvent", SelectSource);
        # Selection
        selactor = vtk.vtkActor()
        view = vtk.vtkContextView(); view.GetRenderWindow().SetWindowName('Plot')
        view.GetRenderWindow().SetPosition(600, 0); view.GetRenderWindow().SetSize(600, 600)
        # Welcome text
        text_init = vtk.vtkTextActor()
        text_init.SetPosition(10, 300)
        text_init.SetInput(welcome)
        text_init.GetTextProperty().SetColor(1.0, 0.0, 0.0)
        view.GetRenderer().AddActor2D(text_init)
        view.GetInteractor().Initialize()
        iren.AddObserver(vtk.vtkCommand.EndPickEvent,CleanPickData)
    iren.Initialize()
    iren.Start()
Exemplo n.º 8
0
def morphology_polydata(compartments,
                        soma_compartment,
                        color_fn,
                        minRadius=0.0):
    points = vtk.vtkPoints()
    lines = vtk.vtkCellArray()

    radii = vtk.vtkDoubleArray()
    radii.SetNumberOfComponents(1)
    radii.SetName("radius")

    types = vtk.vtkUnsignedCharArray()
    types.SetNumberOfComponents(1)
    types.SetName("type")

    colors = vtk.vtkUnsignedCharArray()
    colors.SetNumberOfComponents(3)
    colors.SetName("colors")

    compartment_ids = vtk.vtkUnsignedIntArray()
    compartment_ids.SetNumberOfComponents(1)
    compartment_ids.SetName("compartment_id")

    pidmap = {}
    soma_pid = -1
    soma_radius = 0

    roots = [c for c in compartments.values() if c['parent'] == -1]

    for ri, root in enumerate(roots):
        print "root", ri
        nodelist = preorder_traversal(root, compartments)

        line = []

        for node in nodelist:
            if len(line) == 0 and node['parent'] != -1:
                line.append(pidmap[node['parent']])

            pid = points.InsertNextPoint(node['x'], node['y'], node['z'])

            # keep track of the pid of the root node, as well as the radius of
            # one of its children.  We'll use that radius as a surrogate radius,
            # since dendrites don't actually have a cone shape
            if node == soma_compartment:
                soma_pid = pid
            if node['parent'] == soma_compartment['id']:
                soma_radius = node['radius']

            radii.InsertNextTuple1(max(node['radius'], minRadius))
            types.InsertNextTuple1(node['type'])

            color = color_fn(node)
            colors.InsertNextTuple3(color[0], color[1], color[2])
            compartment_ids.InsertNextTuple1(int(node['id']))

            pidmap[node['id']] = pid

            line.append(pid)
            if len(node['children']) == 0:
                lines.InsertNextCell(len(line))
                for i in line:
                    lines.InsertCellPoint(i)
                line = []

    for p in xrange(1, points.GetNumberOfPoints()):
        p1 = points.GetPoint(p - 1)
        p2 = points.GetPoint(p)

    # assuming we found a root, update its radius
    if soma_radius > 0 and soma_pid >= 0:
        radii.SetTuple1(soma_pid, soma_radius)

    polyData = vtk.vtkPolyData()
    polyData.SetPoints(points)
    polyData.SetLines(lines)
    polyData.GetPointData().AddArray(radii)
    polyData.GetPointData().AddArray(types)
    polyData.GetPointData().AddArray(colors)
    polyData.GetPointData().AddArray(compartment_ids)
    polyData.GetPointData().SetActiveScalars("radius")

    return polyData
Exemplo n.º 9
0
# Sanity check to ensure we are in the build tree
test_cost_data_file = os.path.join('Testing', 'Temporary', 'CTestCostData.txt')
if not os.path.exists(test_cost_data_file):
    print('Run this script from the build tree after running ctest ' +
          'at least once.')
    sys.exit(1)

# Read the input data
with open(test_cost_data_file, 'r') as fp:
    test_cost_data_lines = fp.readlines()
failed_tests_index = test_cost_data_lines.index('---\n')

# Import the data into a vtkTable
table = vtk.vtkTable()
id_array = vtk.vtkUnsignedIntArray()
id_array.SetName('Pedigree Id')
table.AddColumn(id_array)
attributes = table.GetAttributes(vtk.vtkDataObject.ROW)
attributes.SetActivePedigreeIds('Pedigree Id')
test_name_array = vtk.vtkStringArray()
test_name_array.SetName('Test Name')
table.AddColumn(test_name_array)
number_of_runs_array = vtk.vtkUnsignedIntArray()
number_of_runs_array.SetName('Number of Runs')
table.AddColumn(number_of_runs_array)
test_time_array = vtk.vtkFloatArray()
test_time_array.SetName('Test Time')
table.AddColumn(test_time_array)
runs_long_array = vtk.vtkStringArray()
runs_long_array.SetName('RUNS_LONG Label')
Exemplo n.º 10
0
def prepareDelaunayData3d(dimension, agg_globalnodeidx, global_nodecoords, aggpolygons, aggid, aggid2nodes, aggid2procs):

  local_nodeidx2global_nodeidx = {}
  no_of_aggnodes = len(agg_globalnodeidx)
  no_aggs = len(aggid2nodes)

  Points   = vtk.vtkPoints()
  Vertices = vtk.vtkCellArray()

  for i in range(0,len(agg_globalnodeidx)):
    id = -1
    local_nodeidx2global_nodeidx[i] = agg_globalnodeidx[i]
    nodecoords = global_nodecoords[int(agg_globalnodeidx[i])]
    id = Points.InsertNextPoint(nodecoords[0]+ 0.0001 * random.random(),nodecoords[1]+ 0.0001 * random.random(),nodecoords[2]+ 0.0001 * random.random())
    Vertices.InsertNextCell(1)
    Vertices.InsertCellPoint(id)

  polydata2 = vtk.vtkPolyData()
  polydata2.SetPoints(Points)
  polydata2.Modified()
  polydata2.Update()

  delaunay = vtk.vtkDelaunay3D()
  delaunay.SetInput(polydata2)
  delaunay.Update()

  # create surfaceFilter
  surfaceFilter = vtk.vtkDataSetSurfaceFilter()
  surfaceFilter.SetInputConnection(delaunay.GetOutputPort())
  surfaceFilter.Update()

  pt_polydata = surfaceFilter.GetOutput()

  lookupTable = vtk.vtkLookupTable()
  lookupTable.SetNumberOfTableValues(no_aggs)
  lookupTable.Build()

  Ids = vtk.vtkUnsignedIntArray()
  Ids.SetNumberOfComponents(1)
  Ids.SetName("Ids")
  for i in range(0,Points.GetNumberOfPoints()):
    Ids.InsertNextTuple1(int(aggid))
  Ids.SetLookupTable(lookupTable)

  Procs = vtk.vtkUnsignedCharArray()
  Procs.SetNumberOfComponents(1)
  Procs.SetName("proc")
  for i in range(0,Points.GetNumberOfPoints()):
    Procs.InsertNextTuple1(aggid2procs[aggid])

  polydata3 = vtk.vtkPolyData()
  polydata3 = surfaceFilter.GetOutput()
  polydata3.GetPointData().SetScalars(Ids)
  polydata3.GetPointData().AddArray(Procs)

  polydata4 = vtk.vtkPolyData()
  polydata4.SetPoints(Points)
  polydata4.SetVerts(Vertices)
  polydata4.GetPointData().SetScalars(Ids)
  polydata4.GetPointData().AddArray(Procs)

  #datamapper = vtk.vtkDataSetMapper()
  #datamapper.SetInputConnection(delaunay.GetOutputPort())
  #datamapper.SetInput(polydata3)

  #actor = vtk.vtkActor()
  #actor.SetMapper(datamapper)

  #renderer = vtk.vtkRenderer()
  #renderWindow = vtk.vtkRenderWindow()
  #renderWindow.AddRenderer(renderer)
  #renderWindowInteractor = vtk.vtkRenderWindowInteractor()
  #renderWindowInteractor.SetRenderWindow(renderWindow)
  #renderer.AddActor(actor)
  #renderWindow.Render()
  #renderWindowInteractor.Start()

  #print polydata.GetVertices()

  aggpolygons.AddInput(polydata3)
  aggpolygons.AddInput(polydata4)
Exemplo n.º 11
0
# Sanity check to ensure we are in the build tree
test_cost_data_file = os.path.join('Testing', 'Temporary', 'CTestCostData.txt')
if not os.path.exists(test_cost_data_file):
    print('Run this script from the build tree after running ctest ' +
          'at least once.')
    sys.exit(1)

# Read the input data
with open(test_cost_data_file, 'r') as fp:
    test_cost_data_lines = fp.readlines()
failed_tests_index = test_cost_data_lines.index('---\n')

# Import the data into a vtkTable
table = vtk.vtkTable()
id_array = vtk.vtkUnsignedIntArray()
id_array.SetName('Pedigree Id')
table.AddColumn(id_array)
attributes = table.GetAttributes(vtk.vtkDataObject.ROW)
attributes.SetActivePedigreeIds('Pedigree Id')
test_name_array = vtk.vtkStringArray()
test_name_array.SetName('Test Name')
table.AddColumn(test_name_array)
number_of_runs_array = vtk.vtkUnsignedIntArray()
number_of_runs_array.SetName('Number of Runs')
table.AddColumn(number_of_runs_array)
test_time_array = vtk.vtkFloatArray()
test_time_array.SetName('Test Time')
table.AddColumn(test_time_array)
runs_long_array = vtk.vtkStringArray()
runs_long_array.SetName('RUNS_LONG Label')
Exemplo n.º 12
0
def getvtkarray(attribute_type):
    # assume ints are positive
    if attribute_type is int:
        return vtk.vtkUnsignedIntArray()
    elif attribute_type is float:
        return vtk.vtkDoubleArray()
Exemplo n.º 13
0
def generate_polydata(compartments, root_compartment, minRadius=.25):
    import vtk
    points = vtk.vtkPoints()
    lines = vtk.vtkCellArray()

    radii = vtk.vtkDoubleArray()
    radii.SetNumberOfComponents(1)
    radii.SetName("radius")

    types = vtk.vtkUnsignedCharArray()
    types.SetNumberOfComponents(1)
    types.SetName("type")

    compartment_ids = vtk.vtkUnsignedIntArray()
    compartment_ids.SetNumberOfComponents(1)
    compartment_ids.SetName("compartment_id")

    nodelist = preorder_traversal(root_compartment, compartments)

    pidmap = {}
    line = []

    root_pid = -1
    root_radius = 0

    for node in nodelist:

        if len(line) == 0 and node['parent'] != "-1":
            line.append(pidmap[node['parent']])

        pid = points.InsertNextPoint(node['x'], node['y'], node['z'])

        # keep track of the pid of the root node, as well as the radius of
        # one of its children.  We'll use that radius as a surrogate radius,
        # since dendrites don't actually have a cone shape
        if node['parent'] == "-1":
            root_pid = pid
            try:
                child = compartments[node['children'][0]]
                root_radius = child['radius']
            except BaseException as e:
                print(e)
                pass

        radii.InsertNextTuple1(max(node['radius'], minRadius))
        types.InsertNextTuple1(node['type'])
        compartment_ids.InsertNextTuple1(int(node['id']))

        pidmap[node['id']] = pid

        line.append(pid)
        if len(node['children']) == 0:
            lines.InsertNextCell(len(line))
            for i in line:
                lines.InsertCellPoint(i)
            line = []

    for p in xrange(1,points.GetNumberOfPoints()):
        p1 = points.GetPoint(p-1)
        p2 = points.GetPoint(p)

    # assuming we found a root, update its radius
    if root_radius > 0 and root_pid >= 0:
        radii.SetTuple1(root_pid, root_radius)

    polyData = vtk.vtkPolyData()
    polyData.SetPoints(points)
    polyData.SetLines(lines)
    polyData.GetPointData().AddArray(radii)
    polyData.GetPointData().AddArray(types)
    polyData.GetPointData().AddArray(compartment_ids)
    polyData.GetPointData().SetActiveScalars("radius")

    return polyData
import pytest
import vtk

from pytestvtk.assert_vtk import assert_vtk


@pytest.fixture(params=[
    vtk.vtkDoubleArray(),
    vtk.vtkFloatArray(),
    vtk.vtkIntArray(),
    vtk.vtkIdTypeArray(),
    vtk.vtkLongArray(),
    vtk.vtkShortArray(),
    vtk.vtkUnsignedCharArray(),
    vtk.vtkUnsignedIntArray(),
    vtk.vtkUnsignedLongArray(),
    vtk.vtkUnsignedLongLongArray(),
    vtk.vtkUnsignedShortArray(),
    vtk.vtkCharArray(),
])
def vtk_array(request):
    array = request.param
    array.SetName('testing_array')
    array.SetNumberOfTuples(3)
    array.SetNumberOfComponents(3)
    array.InsertTuple3(0, 1, 2, 3)
    array.InsertTuple3(1, 4, 5, 6)
    array.InsertTuple3(2, 7, 8, 9)
    return array

Exemplo n.º 15
0
def prepareDelaunayData3d(
    dimension, agg_globalnodeidx, global_nodecoords, aggpolygons, aggid, aggid2nodes, aggid2procs
):

    local_nodeidx2global_nodeidx = {}
    no_of_aggnodes = len(agg_globalnodeidx)
    no_aggs = len(aggid2nodes)

    Points = vtk.vtkPoints()
    Vertices = vtk.vtkCellArray()

    for i in range(0, len(agg_globalnodeidx)):
        id = -1
        local_nodeidx2global_nodeidx[i] = agg_globalnodeidx[i]
        nodecoords = global_nodecoords[int(agg_globalnodeidx[i])]
        id = Points.InsertNextPoint(
            nodecoords[0] + 0.0001 * random.random(),
            nodecoords[1] + 0.0001 * random.random(),
            nodecoords[2] + 0.0001 * random.random(),
        )
        Vertices.InsertNextCell(1)
        Vertices.InsertCellPoint(id)

    polydata2 = vtk.vtkPolyData()
    polydata2.SetPoints(Points)
    polydata2.Modified()
    polydata2.Update()

    delaunay = vtk.vtkDelaunay3D()
    delaunay.SetInput(polydata2)
    delaunay.Update()

    # create surfaceFilter
    surfaceFilter = vtk.vtkDataSetSurfaceFilter()
    surfaceFilter.SetInputConnection(delaunay.GetOutputPort())
    surfaceFilter.Update()

    pt_polydata = surfaceFilter.GetOutput()

    lookupTable = vtk.vtkLookupTable()
    lookupTable.SetNumberOfTableValues(no_aggs)
    lookupTable.Build()

    Ids = vtk.vtkUnsignedIntArray()
    Ids.SetNumberOfComponents(1)
    Ids.SetName("Ids")
    for i in range(0, Points.GetNumberOfPoints()):
        Ids.InsertNextTuple1(int(aggid))
    Ids.SetLookupTable(lookupTable)

    Procs = vtk.vtkUnsignedCharArray()
    Procs.SetNumberOfComponents(1)
    Procs.SetName("proc")
    for i in range(0, Points.GetNumberOfPoints()):
        Procs.InsertNextTuple1(aggid2procs[aggid])

    polydata3 = vtk.vtkPolyData()
    polydata3 = surfaceFilter.GetOutput()
    polydata3.GetPointData().SetScalars(Ids)
    polydata3.GetPointData().AddArray(Procs)

    polydata4 = vtk.vtkPolyData()
    polydata4.SetPoints(Points)
    polydata4.SetVerts(Vertices)
    polydata4.GetPointData().SetScalars(Ids)
    polydata4.GetPointData().AddArray(Procs)

    # datamapper = vtk.vtkDataSetMapper()
    # datamapper.SetInputConnection(delaunay.GetOutputPort())
    # datamapper.SetInput(polydata3)

    # actor = vtk.vtkActor()
    # actor.SetMapper(datamapper)

    # renderer = vtk.vtkRenderer()
    # renderWindow = vtk.vtkRenderWindow()
    # renderWindow.AddRenderer(renderer)
    # renderWindowInteractor = vtk.vtkRenderWindowInteractor()
    # renderWindowInteractor.SetRenderWindow(renderWindow)
    # renderer.AddActor(actor)
    # renderWindow.Render()
    # renderWindowInteractor.Start()

    # print polydata.GetVertices()

    aggpolygons.AddInput(polydata3)
    aggpolygons.AddInput(polydata4)
Exemplo n.º 16
0
def generate_polydata(compartments, root_compartment, minRadius=.25):
    import vtk
    points = vtk.vtkPoints()
    lines = vtk.vtkCellArray()

    radii = vtk.vtkDoubleArray()
    radii.SetNumberOfComponents(1)
    radii.SetName("radius")

    types = vtk.vtkUnsignedCharArray()
    types.SetNumberOfComponents(1)
    types.SetName("type")

    compartment_ids = vtk.vtkUnsignedIntArray()
    compartment_ids.SetNumberOfComponents(1)
    compartment_ids.SetName("compartment_id")

    nodelist = preorder_traversal(root_compartment, compartments)

    pidmap = {}
    line = []

    root_pid = -1
    root_radius = 0

    for node in nodelist:

        if len(line) == 0 and node['parent'] != "-1":
            line.append(pidmap[node['parent']])

        pid = points.InsertNextPoint(node['x'], node['y'], node['z'])

        # keep track of the pid of the root node, as well as the radius of
        # one of its children.  We'll use that radius as a surrogate radius,
        # since dendrites don't actually have a cone shape
        if node['parent'] == "-1":
            root_pid = pid
            try:
                child = compartments[node['children'][0]]
                root_radius = child['radius']
            except BaseException as e:
                print(e)
                pass

        radii.InsertNextTuple1(max(node['radius'], minRadius))
        types.InsertNextTuple1(node['type'])
        compartment_ids.InsertNextTuple1(int(node['id']))

        pidmap[node['id']] = pid

        line.append(pid)
        if len(node['children']) == 0:
            lines.InsertNextCell(len(line))
            for i in line:
                lines.InsertCellPoint(i)
            line = []

    for p in xrange(1, points.GetNumberOfPoints()):
        p1 = points.GetPoint(p - 1)
        p2 = points.GetPoint(p)

    # assuming we found a root, update its radius
    if root_radius > 0 and root_pid >= 0:
        radii.SetTuple1(root_pid, root_radius)

    polyData = vtk.vtkPolyData()
    polyData.SetPoints(points)
    polyData.SetLines(lines)
    polyData.GetPointData().AddArray(radii)
    polyData.GetPointData().AddArray(types)
    polyData.GetPointData().AddArray(compartment_ids)
    polyData.GetPointData().SetActiveScalars("radius")

    return polyData
Exemplo n.º 17
0
def prepareDelaunayData(dimension, agg_globalnodeidx, global_nodecoords, aggpolygons, aggid, aggid2nodes, aggid2procs):
  local_nodeidx2global_nodeidx = {}
  no_of_aggnodes = len(agg_globalnodeidx)
  dim = len(global_nodecoords[0])

  no_aggs = len(aggid2nodes)

  Points   = vtk.vtkPoints()
  Vertices = vtk.vtkCellArray()

  for i in range(0,len(agg_globalnodeidx)):
    local_nodeidx2global_nodeidx[i] = agg_globalnodeidx[i]
    nodecoords = global_nodecoords[int(agg_globalnodeidx[i])]
    if dimension==2:
      id = Points.InsertNextPoint(nodecoords[0],nodecoords[1],0.0)
    elif dimension==3:
      id = Points.InsertNextPoint(nodecoords[0]+ 0.001 * random.random(),nodecoords[1]+ 0.001 * random.random(),nodecoords[2]+ 0.001 * random.random())
    Vertices.InsertNextCell(1)
    Vertices.InsertCellPoint(id)

  # create polygon for current aggregate
  polydata = vtk.vtkPolyData()
  polydata.SetPoints(Points)
  polydata.SetVerts(Vertices)
  polydata.Modified()
  polydata.Update()

  polydata2 = vtk.vtkPolyData()
  if Points.GetNumberOfPoints()>2: # todo: avoid error messages + add support for lines/surfaces
    # create delaunay object
    if dimension==2:
      delaunay = vtk.vtkDelaunay2D()
    elif dimension==3:
      delaunay = vtk.vtkDelaunay3D()
      #delaunay.SetAlpha(0.1)
    delaunay.SetInput(polydata)
    delaunay.Update()

    # create surfaceFilter
    surfaceFilter = vtk.vtkDataSetSurfaceFilter()
    surfaceFilter.SetInputConnection(delaunay.GetOutputPort())
    surfaceFilter.Update()

    polydata2 = surfaceFilter.GetOutput()

  lookupTable = vtk.vtkLookupTable()
  lookupTable.SetNumberOfTableValues(no_aggs)
  lookupTable.Build()

  Ids = vtk.vtkUnsignedIntArray()
  Ids.SetNumberOfComponents(1)
  Ids.SetName("Ids")
  for i in range(0,Points.GetNumberOfPoints()):
    Ids.InsertNextTuple1(int(aggid))
  Ids.SetLookupTable(lookupTable)

  Procs = vtk.vtkUnsignedCharArray()
  Procs.SetNumberOfComponents(1)
  Procs.SetName("proc")
  for i in range(0,Points.GetNumberOfPoints()):
    Procs.InsertNextTuple1(aggid2procs[aggid])


  polydata2.SetPoints(Points)
  polydata2.SetVerts(Vertices)
  polydata2.GetPointData().SetScalars(Ids)
  polydata2.GetPointData().AddArray(Procs)
  polydata2.Modified()
  polydata2.Update()

  aggpolygons.AddInput(polydata2)