def assemble_neuron(neuron_num):
    print(f"Processing neuron {neuron_num}")
    files = glob.glob("meshes-with-axons-filled/*_n%03d.vtp" % neuron_num)
    out_filename = "meshes-with-axons-filled-assembled/n%02d.vtp" % neuron_num

    appendFilter = vtk.vtkAppendPolyData()
    for file in files:
        _, basename = os.path.split(file)

        x, y, z = int(basename[1]), int(basename[3]), int(basename[5])

        print(x, y, z)

        # Prepare to read the file.
        readerVolume = vtk.vtkXMLPolyDataReader()
        readerVolume.SetFileName(file)
        readerVolume.Update()

        # Set up the transform filter
        translation = vtk.vtkTransform()
        translation.Translate(x * 1023.0, y * 1023.0, z * 1023.0 * 2.49)

        transformFilter = vtk.vtkTransformPolyDataFilter()
        transformFilter.SetInputConnection(readerVolume.GetOutputPort())
        transformFilter.SetTransform(translation)
        transformFilter.Update()

        appendFilter.AddInputData(transformFilter.GetOutput())

    appendFilter.Update()

    writer = vtk.vtkXMLDataSetWriter()
    writer.SetFileName(out_filename)
    writer.SetInputData(appendFilter.GetOutput())
    writer.Write()
def main():
    filenames = list()
    uGrids = list()

    uGrids.append(MakeUnstructuredGrid(vtk.vtkVertex()))
    filenames.append("Vertex.vtu")

    uGrids.append(MakePolyVertex())
    filenames.append("PolyVertex.vtu")

    uGrids.append(MakeUnstructuredGrid(vtk.vtkLine()))
    filenames.append("Line.vtu")

    uGrids.append(MakePolyLine())
    filenames.append("PolyLine.vtu")

    uGrids.append(MakeUnstructuredGrid(vtk.vtkTriangle()))
    filenames.append("Triangle.vtu")

    uGrids.append(MakeTriangleStrip())
    filenames.append("TriangleStrip.vtu")

    uGrids.append(MakePolygon())
    filenames.append("Polygon.vtu")

    uGrids.append(MakeUnstructuredGrid(vtk.vtkPixel()))
    filenames.append("Pixel.vtu")

    uGrids.append(MakeUnstructuredGrid(vtk.vtkQuad()))
    filenames.append("Quad.vtu")

    uGrids.append(MakeUnstructuredGrid(vtk.vtkTetra()))
    filenames.append("Tetra.vtu")

    uGrids.append(MakeUnstructuredGrid(vtk.vtkVoxel()))
    filenames.append("Voxel.vtu")

    uGrids.append(MakeUnstructuredGrid(vtk.vtkHexahedron()))
    filenames.append("Hexahedron.vtu")

    uGrids.append(MakeUnstructuredGrid(vtk.vtkWedge()))
    filenames.append("Wedge.vtu")

    uGrids.append(MakeUnstructuredGrid(vtk.vtkPyramid()))
    filenames.append("Pyramid.vtu")

    uGrids.append(MakeUnstructuredGrid(vtk.vtkPentagonalPrism()))
    filenames.append("PentagonalPrism.vtu")

    uGrids.append(MakeUnstructuredGrid(vtk.vtkHexagonalPrism()))
    filenames.append("HexagonalPrism.vtu")

    # Write each grid into  a file
    for i in range(0, len(uGrids)):
        print("Writing: ", filenames[i])
        writer = vtk.vtkXMLDataSetWriter()
        writer.SetFileName(filenames[i])
        writer.SetInputData(uGrids[i])
        writer.Write()
Beispiel #3
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(self,
                                       module_manager,
                                       vtk.vtkXMLDataSetWriter(),
                                       'Writing vtkXMLDataSet.',
                                       ('vtkXMLDataSet', ), (),
                                       replaceDoc=True,
                                       inputFunctions=None,
                                       outputFunctions=None)
def write_vtk_data(_data, _path_to_file):
    fu.ensure_dir_exists(_path_to_file)
    writer = vtk.vtkXMLDataSetWriter()
    if vtk.VTK_MAJOR_VERSION <= 5:
        writer.SetInput(_data)
    else:
        writer.SetInputData(_data)
    writer.SetFileName(_path_to_file)
    writer.Update()
    writer.Write()
Beispiel #5
0
 def write(self, filename):
     if filename[-4:] == '.vtu':
         filename = filename[:-4]
     writer = vtk.vtkXMLDataSetWriter()
     writer.SetDataModeToAscii()
     for t in xrange(0, self.num_times):
         filename_time = '{:s}.{:03d}.vtu'.format(filename, t)
         print "printing {:s} ...".format(filename_time)
         writer.SetInputData(self.grid[t])
         writer.SetFileName(filename_time)
         writer.Write()
Beispiel #6
0
def save(mesh: geo.Mesh, out_dir: str, name: str):
    out = pathlib.Path(out_dir)
    out.mkdir(exist_ok=True)
    out /= pathlib.Path(f'{name}.vtu')

    grid = mesh.make_vtu_grid()

    writer = vtkXMLDataSetWriter()
    writer.SetFileName(str(out.absolute()))
    writer.SetInputData(grid)
    writer.Write()
Beispiel #7
0
 def write(self, filename):
     if filename[-4:] == '.vtu':
         filename = filename[:-4]
     writer = vtk.vtkXMLDataSetWriter()
     writer.SetDataModeToAscii()
     for t in xrange(0, self.num_times):
         filename_time = '{:s}.{:03d}.vtu'.format(filename, t)
         print "printing {:s} ...".format(filename_time)
         writer.SetInputData(self.grid[t])
         writer.SetFileName(filename_time)
         writer.Write()
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(
         self,
         module_manager,
         vtk.vtkXMLDataSetWriter(),
         "Writing vtkXMLDataSet.",
         ("vtkXMLDataSet",),
         (),
         replaceDoc=True,
         inputFunctions=None,
         outputFunctions=None,
     )
Beispiel #9
0
def write_vtk_data(_data, _path_to_file):
    fu.ensure_dir_exists(_path_to_file)
    file_ext = fu.get_file_extension(_path_to_file)
    if (file_ext == "stl"):
        writer = vtk.vtkSTLWriter()
        writer.SetFileTypeToBinary()
    else:
        writer = vtk.vtkXMLDataSetWriter()
    if vtk.VTK_MAJOR_VERSION <= 5:
        writer.SetInput(_data)
    else:
        writer.SetInputData(_data)
    writer.SetFileName(_path_to_file)
    writer.Write()
Beispiel #10
0
    sys.stdout.write('Attempting read ' + type + ' from junk file.\n')
    reader.Update()
    sys.stdout.write('Attempting read P' + type + ' from junk file.\n')
    preader.Update()

    del input
    del writer
    del reader
    del pwriter
    del preader

# Test the data set writers.
for t in types:
    type = t[0]
    ext = t[1]
    writer = vtk.vtkXMLDataSetWriter()
    pwriter = vtk.vtkXMLPDataSetWriter()
    input = eval('vtk.vtk' + type + '()')

    writer.SetFileName('empty' + type + 'DataSet.' + ext)
    sys.stdout.write('Attempting DataSet ' + type + ' write with no input.\n')
    writer.Write()
    sys.stdout.write('Attempting DataSet ' + type + ' write with empty input.\n')
    writer.SetInputData(input)
    writer.Write()

    pwriter.SetFileName('emptyP' + type + 'DataSet.p' + ext)
    sys.stdout.write('Attempting DataSet ' + type + ' write with no input.\n')
    pwriter.SetNumberOfPieces(1)
    pwriter.Write()
    sys.stdout.write('Attempting DataSet ' + type + ' write with empty input.\n')
Beispiel #11
0
def main():
    colors = vtk.vtkNamedColors()
    ifn, index = get_program_parameters()

    # Prepare to read the file.
    readerVolume = vtk.vtkXdmfReader()
    readerVolume.SetFileName(ifn)
    readerVolume.Update()

    # Extract the region of interest.
    voi = vtk.vtkExtractVOI()
    voi.SetInputConnection(readerVolume.GetOutputPort())
    voi.SetVOI(0, 1023, 0, 1023, 0, 1023)
    voi.SetSampleRate(1, 1, 1)
    voi.Update()  # Necessary for GetScalarRange().
    srange = voi.GetOutput().GetScalarRange()  # Needs Update() before!
    print("Range", srange)

    # Prepare surface generation.
    contour = vtk.vtkDiscreteMarchingCubes()  # For label images.
    contour.SetInputConnection(voi.GetOutputPort())
    # contour.ComputeNormalsOn()

    print("Doing label", index)

    contour.SetValue(0, index)
    contour.Update()  # Needed for GetNumberOfPolys()!!!

    print("Done contour")

    smoother = vtk.vtkWindowedSincPolyDataFilter()
    smoother.SetInputConnection(contour.GetOutputPort())
    smoother.SetNumberOfIterations(20)  # This has little effect on the error!
    smoother.BoundarySmoothingOff()
    smoother.FeatureEdgeSmoothingOff()
    # smoother.SetFeatureAngle(120.0)
    smoother.SetPassBand(.001)  # This increases the error a lot!
    smoother.NonManifoldSmoothingOn()
    smoother.NormalizeCoordinatesOn()
    smoother.GenerateErrorScalarsOn()
    # smoother.GenerateErrorVectorsOn()
    smoother.Update()

    smoothed_polys = smoother.GetOutput()
    print(smoothed_polys)
    smoother_error = smoothed_polys.GetPointData().GetScalars()

    writer = vtk.vtkXMLDataSetWriter()
    writer.SetFileName("out.vtp")
    writer.SetInputData(smoothed_polys)
    writer.Write()

    # Find min and max z.
    se_range = smoother_error.GetRange()
    print("Smoother error range:", se_range)
    minz = se_range[0]  # min(smoother_error)
    maxz = se_range[1]  # max(smoother_error)
    if maxz > 1:
        print("Big smoother error: min/max:", minz, maxz)
    # minz = 0.3  # This way colours of different particles are comparable.
    # maxz = 1
    minz = 0.3
    maxz = 0.6

    #smoothed_polys = contour.GetOutput()

    # Create the color map.
    colorLookupTable = vtk.vtkLookupTable()
    colorLookupTable.SetTableRange(
        minz,
        maxz)  # This does nothing, use mapper.SetScalarRange(minz, maxz).
    colorLookupTable.SetHueRange(2 / 3.0, 1)
    # colorLookupTable.SetSaturationRange(0, 0)
    # colorLookupTable.SetValueRange(1, 0)
    # colorLookupTable.SetNumberOfColors(256) #256 default
    colorLookupTable.Build()

    # Calculate cell normals.
    triangleCellNormals = vtk.vtkPolyDataNormals()
    triangleCellNormals.SetInputData(smoothed_polys)
    triangleCellNormals.ComputeCellNormalsOn()
    triangleCellNormals.ComputePointNormalsOff()
    triangleCellNormals.ConsistencyOn()
    triangleCellNormals.AutoOrientNormalsOn()
    triangleCellNormals.Update()  # Creates vtkPolyData.

    mapper = vtk.vtkPolyDataMapper()
    # mapper.SetInput(smoothed_polys) # This has no normals.
    mapper.SetInputConnection(
        triangleCellNormals.GetOutputPort())  # this is better for vis;-)
    mapper.ScalarVisibilityOn()  # Show colour.
    mapper.SetScalarRange(minz, maxz)
    # mapper.SetScalarModeToUseCellData() # Contains the label eg. 31
    mapper.SetScalarModeToUsePointData(
    )  # The smoother error relates to the verts.
    mapper.SetLookupTable(colorLookupTable)

    # Take the isosurface data and create geometry.
    actor = vtk.vtkLODActor()
    actor.SetNumberOfCloudPoints(100000)
    actor.SetMapper(mapper)

    # Create the renderer.
    ren = vtk.vtkRenderer()
    ren.SetBackground(colors.GetColor3d("DimGray"))
    ren.AddActor(actor)

    # Create a window for the renderer of size 600X600
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren)
    renWin.SetSize(600, 600)

    # Set a user interface interactor for the render window.
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    # Start the initialization and rendering.
    iren.Initialize()
    renWin.Render()

    ren.GetActiveCamera().SetPosition(255, 255, -128)
    ren.GetActiveCamera().SetFocalPoint(255, 255, 256)
    ren.GetActiveCamera().SetViewUp(0.844464, 0.227883, 0.484716)
    ren.ResetCameraClippingRange()
    renWin.Render()

    iren.Start()
Beispiel #12
0
    sys.stdout.write('Attempting read ' + type + ' from junk file.\n')
    reader.Update()
    sys.stdout.write('Attempting read P' + type + ' from junk file.\n')
    preader.Update()

    del input
    del writer
    del reader
    del pwriter
    del preader

# Test the data set writers.
for t in types:
    type = t[0]
    ext = t[1]
    writer = vtk.vtkXMLDataSetWriter()
    pwriter = vtk.vtkXMLPDataSetWriter()
    input = eval('vtk.vtk' + type + '()')

    writer.SetFileName('empty' + type + 'DataSet.' + ext)
    sys.stdout.write('Attempting DataSet ' + type + ' write with no input.\n')
    writer.Write()
    sys.stdout.write('Attempting DataSet ' + type + ' write with empty input.\n')
    writer.SetInputData(input)
    writer.Write()

    pwriter.SetFileName('emptyP' + type + 'DataSet.p' + ext)
    sys.stdout.write('Attempting DataSet ' + type + ' write with no input.\n')
    pwriter.SetNumberOfPieces(1)
    pwriter.Write()
    sys.stdout.write('Attempting DataSet ' + type + ' write with empty input.\n')
def process_one_chunk(filename, out_filename):
    print(f"Processing file {filename}")
    xdmf_template = "chunk_template.xdmf"
    _, basename = os.path.split(filename)
    xdmf_out = f"xdmf/{basename}.xdmf"

    copy_and_replace(xdmf_template, xdmf_out, replacement='../' + filename)

    cube = h5py.File(filename, 'r')
    neuron_ids = np.array(cube['neuron_ids'])
    cube.close()

    # Prepare to read the file.
    readerVolume = vtk.vtkXdmfReader()
    readerVolume.SetFileName(xdmf_out)
    readerVolume.Update()

    # Extract the region of interest.
    # voi = vtk.vtkExtractVOI()
    # voi.SetInputConnection(readerVolume.GetOutputPort())
    # voi.SetVOI(0, 1023, 0, 1023, 0, 1023)
    # voi.SetSampleRate(1, 1, 1)
    # voi.Update()  # Necessary for GetScalarRange().

    for index in neuron_ids:
        full_out_name = out_filename % index
        if os.path.exists(full_out_name):
            print("Skipping neuron %d" % index)
            continue
        print("Processing neuron %d" % index)

        # Prepare surface generation.
        contour = vtk.vtkDiscreteMarchingCubes()  # For label images.
        contour.SetInputConnection(readerVolume.GetOutputPort())
        contour.SetValue(0, index)
        contour.Update()  # Needed for GetNumberOfPolys()!!!

        smoother = vtk.vtkWindowedSincPolyDataFilter()
        smoother.SetInputConnection(contour.GetOutputPort())
        smoother.SetNumberOfIterations(15)
        smoother.BoundarySmoothingOff()
        smoother.FeatureEdgeSmoothingOff()
        smoother.SetPassBand(.01)
        smoother.NonManifoldSmoothingOn()
        smoother.NormalizeCoordinatesOn()
        smoother.GenerateErrorScalarsOn()
        smoother.Update()

        decimate = vtk.vtkDecimatePro()
        decimate.SetInputData(smoother.GetOutput())
        decimate.SetTargetReduction(.8)
        decimate.PreserveTopologyOn()
        decimate.BoundaryVertexDeletionOff()
        decimate.Update()

        smoothed_polys = decimate.GetOutput()

        writer = vtk.vtkXMLDataSetWriter()
        writer.SetFileName(full_out_name)
        writer.SetInputData(smoothed_polys)
        writer.Write()

    return 1