Example #1
2
    def OnExportSurface(self, pubsub_evt):
        filename, filetype = pubsub_evt.data
        if (filetype == const.FILETYPE_STL) or\
           (filetype == const.FILETYPE_VTP) or\
           (filetype == const.FILETYPE_PLY) or\
           (filetype == const.FILETYPE_STL_ASCII):

            # First we identify all surfaces that are selected
            # (if any)
            proj = prj.Project()
            polydata_list = []

            for index in proj.surface_dict:
                surface = proj.surface_dict[index]
                if surface.is_shown:
                    polydata_list.append(surface.polydata)

            if len(polydata_list) == 0:
                utl.debug("oops - no polydata")
                return
            elif len(polydata_list) == 1:
                polydata = polydata_list[0]
            else:
                polydata = pu.Merge(polydata_list)

            # Having a polydata that represents all surfaces
            # selected, we write it, according to filetype
            if filetype == const.FILETYPE_STL:
                writer = vtk.vtkSTLWriter()
                writer.SetFileTypeToBinary()
            elif filetype == const.FILETYPE_STL_ASCII:
                writer = vtk.vtkSTLWriter()
                writer.SetFileTypeToASCII()
            elif filetype == const.FILETYPE_VTP:
                writer = vtk.vtkXMLPolyDataWriter()
            #elif filetype == const.FILETYPE_IV:
            #    writer = vtk.vtkIVWriter()
            elif filetype == const.FILETYPE_PLY:
                writer = vtk.vtkPLYWriter()
                writer.SetFileTypeToASCII()
                writer.SetColorModeToOff()
                #writer.SetDataByteOrderToLittleEndian()
                #writer.SetColorModeToUniformCellColor()
                #writer.SetColor(255, 0, 0)

            if filetype in (const.FILETYPE_STL, const.FILETYPE_PLY):
                # Invert normals
                normals = vtk.vtkPolyDataNormals()
                normals.SetInputData(polydata)
                normals.SetFeatureAngle(80)
                normals.AutoOrientNormalsOn()
                #  normals.GetOutput().ReleaseDataFlagOn()
                normals.UpdateInformation()
                normals.Update()
                polydata = normals.GetOutput()

            filename = filename.encode(wx.GetDefaultPyEncoding())
            writer.SetFileName(filename)
            writer.SetInputData(polydata)
            writer.Write()
def CreateCrossSections(files, outputAreas, outputGeometryFile, outputOutlineFile):
  areaFile = open(outputAreas, 'w')

  planeAppender = vtk.vtkAppendPolyData()
  outlineAppender = vtk.vtkAppendPolyData()
  for idx in range(len(files)):
    print 'Processing contour %d' % idx
    file = files[idx]
    (plane, outline) = CreatePlanarCrossSectionPolyDataFromFile(file)
    areaFile.write(str(ComputePolyDataArea(plane)))
    areaFile.write('\n')
    planeAppender.AddInputData(plane)
    outlineAppender.AddInputData(outline)
    
  planeWriter = vtk.vtkXMLPolyDataWriter()
  planeWriter.SetFileName(outputGeometryFile)
  planeWriter.SetInputConnection(planeAppender.GetOutputPort())
  planeWriter.Update()
  
  outlineWriter = vtk.vtkXMLPolyDataWriter()
  outlineWriter.SetFileName(outputOutlineFile)
  outlineWriter.SetInputConnection(outlineAppender.GetOutputPort())
  outlineWriter.Update()

  areaFile.close()
Example #3
0
def creatPolyData(name, points, cellArray):
    polyData = vtk.vtkPolyData()
    writer_Polydata = vtk.vtkXMLPolyDataWriter()
    fileName_Polydata = "/home/yaser/Desktop/ExtractBoundries/" + name + "polyData.vtp"
    polyData.SetPoints(points)
    polyData.SetVerts(cellArray)
    writer_Polydata = vtk.vtkXMLPolyDataWriter()
    writer_Polydata.SetFileName(fileName_Polydata)
    writer_Polydata.SetInputData(polyData)
    writer_Polydata.Write()
Example #4
0
def main():
    dht = vtkApproximateDHT()

    if len(sys.argv) == 4:
        vector_field_reader = vtkXMLImageDataReader()
        vector_field_reader.SetFileName(sys.argv[1])
        candidate_line_reader = vtkXMLPolyDataReader()
        candidate_line_reader.SetFileName(sys.argv[3])

        dht.SetInputConnection(0, vector_field_reader.GetOutputPort())
        dht.SetInputArrayToProcess(0, 0, 0,
                                   vtkDataObject.FIELD_ASSOCIATION_POINTS,
                                   sys.argv[2])
        dht.SetInputConnection(1, candidate_line_reader.GetOutputPort())
    else:
        # construct analytical vector field
        vector_field = vtkSkewingOscillatingGyreSaddle()
        # output sampled vector field
        writer = vtkXMLImageDataWriter()
        writer.SetInputConnection(vector_field.GetOutputPort(0))
        writer.SetFileName('vector_field.vti')
        writer.Update()
        # construct analytical candidate line
        line_source = vtkLineSource()
        line_source.SetResolution(100)
        line_source.SetPoint1(0., 0., 0.1)
        line_source.SetPoint2(0., 0., 7.9)
        line_source.Update()
        candidate_line = line_source.GetOutput()
        points = vtk_to_numpy(candidate_line.GetPoints().GetData())
        t = points[:, 2]
        points[:, 0] = 0.2 * np.sin(t * (2.0 * np.pi) / 4.0)
        points[:, 1] = 0.8 * np.sin(t * (2.0 * np.pi) / 4.0)
        # output sampled candidate line
        writer = vtkXMLPolyDataWriter()
        writer.SetInputDataObject(candidate_line)
        writer.SetFileName('candidate_line.vtp')
        writer.Update()

        dht.SetInputConnection(0, vector_field.GetOutputPort(0))
        dht.SetInputArrayToProcess(0, 0, 0,
                                   vtkDataObject.FIELD_ASSOCIATION_POINTS, 'u')
        dht.SetInputDataObject(1, candidate_line)

    writer = vtkXMLPolyDataWriter()
    writer.SetInputConnection(dht.GetOutputPort())
    writer.SetFileName('dht.vtp')
    writer.Update()
	def writePolyData(self, polyData, filename, callback = None):
		"""
		Writes the given vtkPolyData instance to disk
					 as .vtp-file with the given filename
		"""
		writer = vtk.vtkXMLPolyDataWriter()
		writer.SetFileName(filename)
		writer.SetInput(polyData)
		def f(obj, evt):
			if obj and callback:
				callback(obj.GetProgress())
			if scripting.mainWindow:
				scripting.mainWindow.updateProgressBar(obj, evt, obj.GetProgress(),"Writing surface %s"%os.path.basename(filename), 0)
		writer.AddObserver("ProgressEvent", lib.messenger.send)
		lib.messenger.connect(writer, "ProgressEvent", f)
		Logging.info("Writing polydata to file %s"%filename,kw="pipeline")
		try:
			ret = writer.Write()
			
			if ret == 0:
				Logging.error("Failed to write polygonal data",
				"Failed to write vtkPolyData object to file %s" % filename)
				return
		except Exception, ex:
			Logging.error("Failed to write poly data",
			"Failed to write vtkPolyData object to file %s" % filename, ex)
			return
Example #6
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(
         self, module_manager,
         vtk.vtkXMLPolyDataWriter(), 'Writing vtkXMLPolyData.',
         ('vtkXMLPolyData',), (),
         replaceDoc=True,
         inputFunctions=None, outputFunctions=None)
Example #7
0
def pointToCellData():
    
    print "Using angle: " + str(angle)
    atpFiles = glob.glob(str(angle) + '/*.vtp')
    if not atpFiles:
        exit("No atp files found")
        
    if not os.path.exists(str(angle) + '_new'):
        os.makedirs(str(angle) + '_new')
    
    for inputFile in atpFiles: 

        print 'Reading', inputFile
        atpReader = vtk.vtkXMLPolyDataReader()
        atpReader.SetFileName(inputFile)
        atpReader.Update()
    
        atpDataset = atpReader.GetOutput()
        
        pointToCell = vtk.vtkPointDataToCellData()
        pointToCell.SetInputData(atpDataset)
        pointToCell.PassPointDataOn()
        pointToCell.Update()
        
        newArray = pointToCell.GetOutput()
        
        # Remove the point data arrays, they exist as cell data
        newArray.GetPointData().RemoveArray('ATP')
        newArray.GetPointData().RemoveArray('tau')
        newArray.GetCellData().RemoveArray('p')
    
        atpWriter = vtk.vtkXMLPolyDataWriter()
        atpWriter.SetInputData(newArray)
        atpWriter.SetFileName(str(angle) + '_new/' + inputFile[3:])
        atpWriter.Update()
def save_contour_as_vtp(points, lines, filename):
    """
    Generates a .vtp file for the given contour to use in ShapeWorks optimizer
    points:   Nx3 np.ndarray of points in the contour
    lines:    Mx2 np.ndarray of lines in the contour
    filename: output .vtp filename
    """
    vtk_pts = vtk.vtkPoints()
    n = points.shape[0]
    for j in range(n):
        x, y, z = points[j]
        vtk_pts.InsertNextPoint((x,y,z))

    vtk_lines = vtk.vtkCellArray()
    m = lines.shape[0]
    for j in range(m):
        vtk_line = vtk.vtkLine()
        vtk_line.GetPointIds().SetId(0, lines[j][0])
        vtk_line.GetPointIds().SetId(1, lines[j][1])
        vtk_lines.InsertNextCell(vtk_line)

    polydata = vtk.vtkPolyData()
    polydata.SetPoints(vtk_pts)
    polydata.SetLines(vtk_lines)

    writer = vtk.vtkXMLPolyDataWriter()
    writer.SetFileName(filename)
    writer.SetInputData(polydata)
    writer.Write()
Example #9
0
def writeDefects(defects_n, defects_v, numdefect_n, numdefect_v, outfile):
    # Preparing the vtp output
    # Create point structure in vtk
    Points = vtk.vtkPoints()
    print "Created Points"
    # Create (something) associated to the points, with different values for each
    Number = vtk.vtkDoubleArray()
    Number.SetNumberOfComponents(1)
    Number.SetName('Number')
    Size = vtk.vtkDoubleArray()
    Size.SetNumberOfComponents(1)
    Size.SetName('Size')
    print "Created Number"
    # Put one point at the centre, and the ndefect ones around it
    Points.InsertNextPoint(0, 0, 0)
    Number.InsertNextValue(0)
    Size.InsertNextValue(0)
    for u in range(numdefect_n):
        Points.InsertNextPoint(defects_n[u, 1], defects_n[u, 2], defects_n[u,
                                                                           3])
        Number.InsertNextValue(1)
        Size.InsertNextValue(1.0)
    for u in range(numdefect_v):
        Points.InsertNextPoint(defects_v[u, 1], defects_v[u, 2], defects_v[u,
                                                                           3])
        Number.InsertNextValue(2)
        Size.InsertNextValue(1.0)
    print "Added Particles and Numbers"

    lines = vtk.vtkCellArray()
    line = vtk.vtkLine()
    for i in range(numdefect_n):
        line = vtk.vtkLine()
        line.GetPointIds().SetId(0, 0)
        line.GetPointIds().SetId(1, i + 1)
        lines.InsertNextCell(line)
    for i in range(numdefect_v):
        line = vtk.vtkLine()
        line.GetPointIds().SetId(0, 0)
        line.GetPointIds().SetId(1, numdefect_n + i + 1)
        lines.InsertNextCell(line)
    print "Added lines"

    polydata = vtk.vtkPolyData()
    polydata.SetPoints(Points)
    polydata.SetLines(lines)
    polydata.GetPointData().AddArray(Number)
    polydata.GetPointData().AddArray(Size)
    print "Finished Polydata"
    polydata.Modified()
    writer = vtk.vtkXMLPolyDataWriter()
    writer.SetFileName(outfile)
    # Python 2.7 vs. 3 incompatibility?
    if vtk.VTK_MAJOR_VERSION <= 5:
        writer.SetInput(polydata)
    else:
        writer.SetInputData(polydata)
    writer.SetDataModeToAscii()
    writer.Write()
    print "Wrote File"
Example #10
0
def sv_centerlines(p):
    """
    Call SimVascular centerline generation
    """
    try:
        import sv
    except ImportError:
        raise ImportError('Run with sv --python -- this_script.py')

    # create a modeler
    kernel = sv.modeling.Kernel.POLYDATA
    modeler = sv.modeling.Modeler(kernel)

    # read surface mesh
    model = modeler.read(p['surf_in'])
    model_polydata = model.get_polydata()

    # generate centerline
    # todo: try use_face_ids
    centerlines_polydata = sv.vmtk.centerlines(model_polydata, [p['caps'][0]],
                                               p['caps'][1:],
                                               use_face_ids=False)

    # write centerline to file
    writer = vtk.vtkXMLPolyDataWriter()
    writer.SetFileName(p['cent_out'])
    writer.SetInputData(centerlines_polydata)
    writer.Update()
    writer.Write()
Example #11
0
def importVTP(filename):
    streamlines = []  #list of streamlines
    filename = str(filename)
    vwriter = vtk.vtkXMLPolyDataWriter()
    reader = vtk.vtkXMLPolyDataReader()
    reader.SetFileName(filename)
    reader.Update()
    reader.ReleaseDataFlagOn()
    data = reader.GetOutput()
    vtxs = vtk_to_numpy(data.GetPoints().GetData())
    pts = data.GetPointData()
    vals = {
        pts.GetArrayName(idx): vtk_to_numpy(pts.GetArray(idx))
        for idx in range(pts.GetNumberOfArrays())
    }  # dictionary of numpy array of scalar values associated with each vertex
    metrics = [
        pts.GetArrayName(idx) for idx in range(pts.GetNumberOfArrays())
    ]  # name of metrics
    if 'tensors' in metrics:
        del metrics[metrics.index('tensors')]
    for i in range(data.GetNumberOfCells()):
        streamlines.append([
            data.GetCell(i).GetPointIds().GetId(p)
            for p in range(data.GetCell(i).GetPointIds().GetNumberOfIds())
        ])
    return (vtxs, vals, streamlines)
Example #12
0
def write_polydata(polydata, filename):
    """Write polydata as vtkPolyData format, according to extension."""

    if VERBOSE:
        print "Writing ", filename, "..."

    basename, extension = os.path.splitext(filename)

    if   (extension == '.vtk'):
        writer = vtk.vtkPolyDataWriter()
        writer.SetFileTypeToBinary()
    elif (extension == '.vtp'):
        writer = vtk.vtkXMLPolyDataWriter()
        writer.SetDataModeToBinary()
    else:
        print 'Cannot recognize model file format'
        return None

    writer.SetFileName(filename)
    if (vtk.vtkVersion().GetVTKMajorVersion() >= 6.0):
        writer.SetInputData(polydata)
    else:
        writer.SetInput(polydata)
    writer.Update()

    del writer

    if VERBOSE:
        print "Done writing ", filename
        print "Number of lines found:", outpd.GetNumberOfLines()
def save_lesion(output_file, input_file, field, limits):
    reader = v.vtkXMLUnstructuredGridReader()
    reader.SetFileName(input_file)
    reader.Update()

    threshold = v.vtkThreshold()
    threshold.SetInput(reader.GetOutput())

    if limits[0] is None:
        threshold.ThresholdByLower(limits[1])
    elif limits[1] is None:
        threshold.ThresholdByUpper(limits[0])
    else:
        threshold.ThresholdBetween(*limits)

    threshold.SetInputArrayToProcess(0, 0, 0, v.vtkDataObject.FIELD_ASSOCIATION_CELLS, field)
    threshold.Update()

    extract_surface = v.vtkDataSetSurfaceFilter()
    extract_surface.SetInput(threshold.GetOutput())
    extract_surface.Update()

    writer = v.vtkXMLPolyDataWriter()
    writer.SetFileName(output_file)
    writer.SetInput(extract_surface.GetOutput())
    writer.Write()
Example #14
0
def pointToCellData():

    atpFiles = sorted(glob.glob('*.vtp'))

    if not atpFiles:
        exit("No atp files found")

    for inputFile in atpFiles:

        print('Reading', inputFile)
        atpReader = vtk.vtkXMLPolyDataReader()
        atpReader.SetFileName(inputFile)
        atpReader.Update()

        atpDataset = atpReader.GetOutput()

        pointToCell = vtk.vtkPointDataToCellData()
        pointToCell.SetInputData(atpDataset)
        pointToCell.PassPointDataOn()
        pointToCell.Update()

        convertedData = pointToCell.GetOutput()

        # Remove the point data arrays, they exist as cell data.
        convertedData.GetPointData().RemoveArray('ATP')
        convertedData.GetPointData().RemoveArray('tau')
        convertedData.GetCellData().RemoveArray('p')

        atpWriter = vtk.vtkXMLPolyDataWriter()
        atpWriter.SetInputData(convertedData)
        atpWriter.SetFileName("_" + inputFile)
        atpWriter.Update()
Example #15
0
def writeVTK(fn, pts, poly):
    poly.GetPoints().SetData(numpy_to_vtk(pts))
    writer = vtk.vtkXMLPolyDataWriter()
    writer.SetFileName(fn)
    writer.SetInputData(poly)
    writer.Update()
    writer.Write()
Example #16
0
    def _write_mesh_points_vtk(self, filename, points, power_per_point):

        # setup points and vertices
        vtk_points = vtk.vtkPoints()
        vtk_vertices = vtk.vtkCellArray()
        vtk_point_values = vtk.vtkDoubleArray()
        vtk_point_values.SetName("CollisionEnergies")

        for i in range(points.shape[0]):
            id = vtk_points.InsertNextPoint(points[i, 0], points[i, 1],
                                            points[i, 2])
            vtk_vertices.InsertNextCell(1)
            vtk_vertices.InsertCellPoint(id)
            vtk_point_values.InsertNextValue(power_per_point)

        polydata = vtk.vtkPolyData()
        polydata.SetPoints(vtk_points)
        polydata.SetVerts(vtk_vertices)
        polydata.GetCellData().SetScalars(vtk_point_values)
        polydata.Modified()
        if vtk.VTK_MAJOR_VERSION <= 5:
            polydata.Update()

        writer = vtk.vtkXMLPolyDataWriter()
        writer.SetFileName(filename)
        if vtk.VTK_MAJOR_VERSION <= 5:
            writer.SetInput(polydata)
        else:
            writer.SetInputData(polydata)
        writer.Write()
Example #17
0
def write(obj, fileoutput):
    '''
    Write 3D object to file.
    Possile extensions are: .vtk, .ply, .obj, .stl, .byu, .vtp
    '''
    fr = fileoutput.lower()
    if '.vtk' in fr: w = vtk.vtkPolyDataWriter()
    elif '.ply' in fr: w = vtk.vtkPLYWriter()
    elif '.obj' in fr:
        w = vtk.vtkOBJExporter()
        w.SetFilePrefix(fileoutput.replace('.obj', ''))
        vc.printc('Please use write(vp.renderWin)', 3)
        w.SetInput(obj)
        w.Update()
        vc.printc("Saved file: " + fileoutput, 'g')
        return
    elif '.stl' in fr:
        w = vtk.vtkSTLWriter()
    elif '.byu' in fr or '.g' in fr:
        w = vtk.vtkBYUWriter()
    elif '.vtp' in fr:
        w = vtk.vtkXMLPolyDataWriter()
    else:
        vc.printc('Unavailable format in file ' + fileoutput, c='r')
        exit(1)
    try:
        vu.setInput(w, vu.polydata(obj, True))
        w.SetFileName(fileoutput)
        w.Write()
        vc.printc("Saved file: " + fileoutput, 'g')
    except:
        vc.printc("Error saving: " + fileoutput, 'r')
Example #18
0
def create_mesh(M,P,T):
	n_naca_pts = 50
	write_test_file(M,P,T,-5.,5.,nsections=5)
	wing=create_wing('current_wing','output')
	n_sections=len(wing)
	n_section_pts = 2*n_naca_pts-1

	# build mesh
	vtk_model = vtk.vtkStructuredGrid()
	vtk_model.SetDimensions(n_section_pts,n_sections,1)
	# build points
	vtk_points = vtk.vtkPoints()

	for j in xrange(n_sections):
	    upper_pts = numpy.array([wing[j][1],wing[j][3]]).T
	    lower_pts = numpy.array([wing[j][2],wing[j][4]]).T
	    section_pts = numpy.concatenate((lower_pts[::-1],upper_pts[1:]))
	    for i in xrange(n_section_pts):
		vtk_points.InsertNextPoint(section_pts[i,0],wing[j][0],section_pts[i,1])
	# set points
	vtk_model.SetPoints(vtk_points)

	# convert to poly data    
	pdata_filter = vtk.vtkGeometryFilter()
	if vtk.VTK_MAJOR_VERSION <= 5:
	    pdata_filter.SetInput(vtk_model)
	else:
	    pdata_filter.SetInputData(vtk_model)
	pdata_filter.Update()
	poly_data = pdata_filter.GetOutput()

	# compute normals
	norms = vtk.vtkPolyDataNormals()
	if vtk.VTK_MAJOR_VERSION <= 5:
	    norms.SetInput(poly_data)
	else:
	    norms.SetInputData(poly_data)
	norms.ComputePointNormalsOff()
	norms.ComputeCellNormalsOn()
	norms.ConsistencyOn()
	norms.Update()

	# clean poly data
	clean_poly = vtk.vtkCleanPolyData()
	clean_poly.ToleranceIsAbsoluteOn()
	clean_poly.SetAbsoluteTolerance(1.e-6)
	if vtk.VTK_MAJOR_VERSION <= 5:
	    clean_poly.SetInput(norms.GetOutput())
	else:
	    clean_poly.SetInputData(norms.GetOutput())
	clean_poly.Update()

	# write output mesh
	writer = vtk.vtkXMLPolyDataWriter()
	if vtk.VTK_MAJOR_VERSION <= 5:
	    writer.SetInput(clean_poly.GetOutput())
	else:
	    writer.SetInputData(clean_poly.GetOutput())
	writer.SetFileName('output.vtp')
	writer.Write()
Example #19
0
    def __init__(self, module_manager):

        # call parent constructor
        ModuleBase.__init__(self, module_manager)

        self._writer = vtk.vtkXMLPolyDataWriter()

        module_utils.setup_vtk_object_progress(
            self, self._writer,
            'Writing VTK PolyData')

        

        self._writer.SetDataModeToBinary()

        # ctor for this specific mixin
        FilenameViewModuleMixin.__init__(
            self,
            'Select a filename',
            'VTK PolyData (*.vtp)|*.vtp|All files (*)|*',
            {'vtkXMLPolyDataWriter': self._writer},
            fileOpen=False)
            

        # set up some defaults
        self._config.filename = ''

        self.sync_module_logic_with_config()
Example #20
0
def save_polydata(polydata, file_name, binary=False, color_array_name=None):
    # get file extension (type)
    file_extension = file_name.split(".")[-1].lower()

    # todo better generic load
    # todo test all
    if file_extension == "vtk":
        writer = vtk.vtkPolyDataWriter()
    elif file_extension == "vtp":
        writer = vtk.vtkPolyDataWriter()
    elif file_extension == "fib":
        writer = vtk.vtkPolyDataWriter()
    elif file_extension == "ply":
        writer = vtk.vtkPLYWriter()
    elif file_extension == "stl":
        writer = vtk.vtkSTLWriter()
    elif file_extension == "xml":
        writer = vtk.vtkXMLPolyDataWriter()
    elif file_extension == "obj":
        raise "mni obj or Wavefront obj ?"
    #    writer = set_input(vtk.vtkMNIObjectWriter(), polydata)

    writer.SetFileName(file_name)
    writer = set_input(writer, polydata)
    if color_array_name is not None:
        writer.SetArrayName(color_array_name);
    
    if binary :
        writer.SetFileTypeToBinary()
    writer.Update()
    writer.Write()
Example #21
0
def write_vtp(name, pd):
    """ Writes a VTP file including cell data from vtkPolyData
    """
    writer = vtk.vtkXMLPolyDataWriter()
    writer.SetFileName(name)
    writer.SetInputData(pd)
    writer.Write()
Example #22
0
def main(argv=None):
    dimension = 2
    numprocs = 2
    level = 0  # startlevel

    no_multigridlevels = 0

    # check how many processors generated aggregation output
    # while check_files_for_next_level(0,numprocs, "aggs_level%LEVEL_proc%PROC.out") == True:
    #  numprocs = numprocs + 1
    # numprocs = numprocs - 1
    # print "Aggregtaion information for " + str(numprocs) + " processors found"

    # process all multigrid levels
    while check_files_for_next_level(level, numprocs, "aggs_level%LEVEL_proc%PROC.out"):
        global_nodecoords = []

        print "Level " + str(level)

        if level == 0:  # read in coordinates (finest level
            global_nodecoords, dimension = read_finelevel_nodecoords_from_file("example.txt")
        else:
            global_nodecoords, dimension = read_nodecoords_from_file("nodes" + str(level) + ".txt")

        # read aggregates
        aggid2nodes, aggid2procs = readin_aggregates("aggs_level%LEVEL_proc%PROC.out", numprocs, level)

        # vtk polygon for output
        aggpolygons = vtk.vtkAppendPolyData()

        # collect all aggregates
        for aggid, agg_nodes in aggid2nodes.iteritems():
            # build an aggregate
            if dimension == 2:
                prepareDelaunayData(
                    dimension, agg_nodes, global_nodecoords, aggpolygons, aggid, aggid2nodes, aggid2procs
                )
            else:
                prepareDelaunayData3d(
                    dimension, agg_nodes, global_nodecoords, aggpolygons, aggid, aggid2nodes, aggid2procs
                )

                # aggpolygons.GetOutput().GetPointData().SetVectors(vtkDisplacementVector)
                # aggpolygons.Update()

        writer = vtk.vtkXMLPolyDataWriter()
        fname = "aggs" + str(level) + ".vtp"
        writer.SetFileName(fname)
        writer.SetInput(aggpolygons.GetOutput())
        writer.Write()

        write_nodes_file("nodes" + str(level + 1) + ".txt", aggid2nodes, global_nodecoords, dimension)

        # increment number of multigrid levels that have been found in the files
        if no_multigridlevels < level:
            no_multigridlevels = level

        print "VTK Export for level " + str(level) + " finished...\r\n"

        level = level + 1
Example #23
0
def main():
    filename = get_program_parameters()

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

    id = Points.InsertNextPoint(1.0, 0.0, 0.0)
    Vertices.InsertNextCell(1)
    Vertices.InsertCellPoint(id)
    id = Points.InsertNextPoint(0.0, 0.0, 0.0)
    Vertices.InsertNextCell(1)
    Vertices.InsertCellPoint(id)
    id = Points.InsertNextPoint(0.0, 1.0, 0.0)
    Vertices.InsertNextCell(1)
    Vertices.InsertCellPoint(id)

    polydata = vtk.vtkPolyData()
    polydata.SetPoints(Points)
    polydata.SetVerts(Vertices)
    polydata.Modified()

    writer = vtk.vtkXMLPolyDataWriter()
    writer.SetFileName(filename)
    writer.SetInputData(polydata)
    writer.Write()
Example #24
0
def save_one_file(i):
    pts = vtk.vtkPoints()
    df1 = df[df['T']==unique_times[i]]
    x = df1['COORX']
    y = df1['COORY']
    z = df1['COORZ']
    tp = df1['ITYPE']
    pts.SetNumberOfPoints(df1.shape[0])

    if df1.shape[0]==0:
        empty_file[i]=1
    else:
        for j in range(df1.shape[0]):         
            pts.SetPoint(j, (x.iloc[j],y.iloc[j],z.iloc[j]))

        types = vtk.vtkShortArray()
        types.SetNumberOfComponents(1)
        types.SetNumberOfTuples(pts.GetNumberOfPoints())
        types.SetName('Type')
        
        for j in range(df1.shape[0]):         
            types.SetTuple1(j, tp.iloc[j])

        pd = vtk.vtkPolyData()
        pd.SetPoints(pts)
        pd.GetPointData().AddArray(types)

        wr= vtk.vtkXMLPolyDataWriter()
        wr.SetInputData(pd)
        wr.SetDataModeToBinary()
        filename = "pts_{:010d}.vtp".format(i)
        wr.SetFileName(filename)
        wr.Write()
Example #25
0
def write_VTP(filename, vertices, faces):
    """Writes .vtp file format for the Paraview (Kitware (c)) visualisation software.
    
    It relies on the VTK library for its writer. VTP files use the last XML file format of the VTK library and
    correspond to polydata.

    Parameters
    ----------
    filename: str
        name of the mesh file to be written on disk
    vertices: ndarray
        numpy array of the coordinates of the mesh's nodes
    faces: ndarray
        numpy array of the faces' nodes connectivities
    """

    from vtk import vtkXMLPolyDataWriter, VTK_MAJOR_VERSION
    writer = vtkXMLPolyDataWriter()
    writer.SetDataModeToAscii()
    writer.SetFileName(filename)

    polydata = _build_vtkPolyData(vertices, faces)
    if VTK_MAJOR_VERSION <= 5:
        writer.SetInput(polydata)
    else:
        writer.SetInputData(polydata)
    writer.Write()
    def exportModel(self, model, outDir):
        
        modelDisplay = model.GetDisplayNode()
        if not modelDisplay or not modelDisplay.GetVisibility():
            return None
        
        print('  exporting %s' % model.GetName())
        
        writer = vtk.vtkXMLPolyDataWriter()
        if vtk.VTK_MAJOR_VERSION <= 5:
            writer.SetInput(model.GetPolyData())
        else:
            writer.SetInputData(model.GetPolyData())
        fileName = os.path.join(outDir, model.GetName() + '.vtp')
        writer.SetFileName(fileName)
        writer.Write()

        data = {}
        data['name'] = model.GetName()
        data['color'] = modelDisplay.GetColor()
        data['opacity'] = modelDisplay.GetOpacity()
        data['filename'] = fileName
        
        representation = modelDisplay.GetRepresentation()
        if representation == slicer.vtkMRMLDisplayNode.WireframeRepresentation:
            data['geometry_mode'] = 'wireframe'
        elif representation == slicer.vtkMRMLDisplayNode.SurfaceRepresentation \
          and modelDisplay.GetEdgeVisibility():
            data['geometry_mode'] = 'surface_with_edges'
        elif representation == slicer.vtkMRMLDisplayNode.PointsRepresentation:
            data['geometry_mode'] = 'points'

        return data
Example #27
0
    def write(self, fname):
        """
        Write to file.

        Parameters
        ----------
        fname : str
            Filename for writing.

        """
        if isinstance(self.geom, vtk.vtkRectilinearGrid):
            writer = vtk.vtkXMLRectilinearGridWriter()
        elif isinstance(self.geom, vtk.vtkUnstructuredGrid):
            writer = vtk.vtkXMLUnstructuredGridWriter()
        elif isinstance(self.geom, vtk.vtkPolyData):
            writer = vtk.vtkXMLPolyDataWriter()

        default_ext = writer.GetDefaultFileExtension()
        name, ext = os.path.splitext(fname)
        if ext and ext != '.' + default_ext:
            raise ValueError('Given extension {} is not .{}'.format(
                ext, default_ext))
        writer.SetFileName('{}.{}'.format(name, default_ext))
        writer.SetCompressorTypeToZLib()
        writer.SetDataModeToBinary()
        writer.SetInputData(self.geom)

        writer.Write()
Example #28
0
def convert_mris(input_name, output_name):
  """
  Converts a FreeSurfer surface to VTK file format
  """
  # convert surface to VTK format
  if output_name.endswith('.vtp'): temp_name = output_name[0:-1] + 'k'
  else:                            temp_name = output_name
  if not temp_name.endswith('.vtk'):
    raise RuntimeError('Output file name extension must be either .vtk or .vtp')
  check_call(['mris_convert', input_name, temp_name])
  # get surface RAS translation
  out = check_output(["mris_info", input_name], stderr=STDOUT)
  m = re.search("c_\(ras\)\s:\s\((-?\d+\.\d+),\s(-?\d+\.\d+),\s(-?\d+\.\d+)\)", out)
  if m is None: raise RuntimeError('Could not find c_(ras) coordinates in mris_info output!')
  tx = float(m.group(1))
  ty = float(m.group(2))
  tz = float(m.group(3))
  # transform vertex positions to scanner RAS of orig.mgz
  reader = vtkPolyDataReader()
  reader.SetFileName(temp_name)
  reader.Update()
  surface = reader.GetOutput()
  points = surface.GetPoints()
  for i in range(points.GetNumberOfPoints()):
    x, y, z = points.GetPoint(i)
    points.SetPoint(i, x + tx, y + ty, z + tz)
  surface.SetPoints(points)
  if output_name.endswith('.vtp'): writer = vtkXMLPolyDataWriter()
  else:                            writer = vtkPolyDataWriter()
  writer.SetFileName(output_name)
  writer.SetInput(surface)
  writer.Write()
  if temp_name != output_name:
    remove(temp_name)
Example #29
0
    def OnExportSurface(self, pubsub_evt):
        filename, filetype = pubsub_evt.data
        if (filetype == const.FILETYPE_STL) or\
           (filetype == const.FILETYPE_VTP) or\
           (filetype == const.FILETYPE_PLY) or\
           (filetype == const.FILETYPE_STL_ASCII):

            # First we identify all surfaces that are selected
            # (if any)
            proj = prj.Project()
            polydata_list = []

            for index in proj.surface_dict:
                surface = proj.surface_dict[index]
                if surface.is_shown:
                    polydata_list.append(surface.polydata)

            if len(polydata_list) == 0:
                utl.debug("oops - no polydata")
                return
            elif len(polydata_list) == 1:
                polydata = polydata_list[0]
            else:
                polydata = pu.Merge(polydata_list)

            # Having a polydata that represents all surfaces
            # selected, we write it, according to filetype
            if filetype == const.FILETYPE_STL:
                writer = vtk.vtkSTLWriter()
                writer.SetFileTypeToBinary()
            elif filetype == const.FILETYPE_STL_ASCII:
                writer = vtk.vtkSTLWriter()
                writer.SetFileTypeToASCII()
            elif filetype == const.FILETYPE_VTP:
                writer = vtk.vtkXMLPolyDataWriter()
            #elif filetype == const.FILETYPE_IV:
            #    writer = vtk.vtkIVWriter()
            elif filetype == const.FILETYPE_PLY:
                writer = vtk.vtkPLYWriter()
                writer.SetFileTypeToASCII()
                writer.SetColorModeToOff()
                #writer.SetDataByteOrderToLittleEndian()
                #writer.SetColorModeToUniformCellColor()
                #writer.SetColor(255, 0, 0)

            if filetype in (const.FILETYPE_STL, const.FILETYPE_PLY):
                # Invert normals
                normals = vtk.vtkPolyDataNormals()
                normals.SetInputData(polydata)
                normals.SetFeatureAngle(80)
                normals.AutoOrientNormalsOn()
                #  normals.GetOutput().ReleaseDataFlagOn()
                normals.UpdateInformation()
                normals.Update()
                polydata = normals.GetOutput()

            filename = filename.encode(wx.GetDefaultPyEncoding())
            writer.SetFileName(filename)
            writer.SetInputData(polydata)
            writer.Write()
Example #30
0
def write_vtp(file_name, polyData):
    out = vtk.vtkXMLPolyDataWriter()
    out.SetInputDataObject(polyData)
    out.SetDataModeToAscii()
    out.SetFileName(file_name)
    out.Write()
    return 1
Example #31
0
def saveData_VTP_vtk(pts, sdata, vdata, filename, mode='binary', zlib=False):

    grid = createPolyData(pts, sdata, vdata)

    writer = vtk.vtkXMLPolyDataWriter()
    if zlib:
        writer.SetCompressorTypeToZLib()
    else:
        writer.SetCompressorTypeToNone()

    if mode == 'binary':
        writer.SetDataModeToBinary()
    elif mode == 'ascii':
        writer.SetDataModeToAscii()
    elif mode == 'appended':  # ajoute les donnees en fin de fichier
        writer.SetDataModeToAppended()
        writer.EncodeAppendedDataOff()  # pas de base64 encoding
    else:
        raise Exception('unknown mode %s (choices are binary/ascii/appended)' %
                        mode)

    if version > 5:
        writer.SetInputData(grid)
    else:
        writer.SetInput(grid)
    writer.SetFileName(filename)
    writer.Write()
    print "%s written" % filename
Example #32
0
    def writeVTKCenterLine(self, filename):
        "Create data in VTK format to compute isocontour"

        writer = vtk.vtkXMLPolyDataWriter()
        writer.SetFileName(filename + '.vtp')
        writer.SetInput(self.profileTubes.GetOutput())
        writer.Write()
Example #33
0
def write_vtk_polydata(poly, fn):
    """
    This function writes a vtk polydata to disk
    Args:
        poly: vtk polydata
        fn: file name
    Returns:
        None
    """
    print('Writing vtp with name:', fn)
    if (fn == ''):
        return 0

    _, extension = os.path.splitext(fn)

    if extension == '.vtk':
        writer = vtk.vtkPolyDataWriter()
    elif extension == '.stl':
        writer = vtk.vtkSTLWriter()
    elif extension == '.vtp':
        writer = vtk.vtkXMLPolyDataWriter()
    elif extension == '.obj':
        writer = vtk.vtkOBJWriter()
    else:
        raise ValueError("Incorrect extension" + extension)
    writer.SetInputData(poly)
    writer.SetFileName(fn)
    writer.Update()
    writer.Write()
    return
Example #34
0
 def writeVTKContour(self, filename):
     "Create data in VTK format to compute isocontour"
     # Add thickness to the resulting line.
     writer = vtk.vtkXMLPolyDataWriter()
     writer.SetFileName(filename + '.vtp')
     writer.SetInput(self.profileContour)
     writer.Write()
def buildATPMesh(polydata, filename):
    
    centroidFilter = vtk.vtkCellCenters()
    centroidFilter.VertexCellsOn()
    centroidFilter.SetInputData(polydata)
    
    newPolydata = vtk.vtkPolyData()
    newPolydata = centroidFilter.GetOutput()
    centroidFilter.Update()
    
    ATPValues = vtk.vtkDoubleArray()
    ATPValues.SetName("initialATP")
    
    _, _, yMin, yMax, _, _ = polydata.GetBounds()
    yRange = yMax - yMin
    
    for pointId in range(0, newPolydata.GetNumberOfPoints()):
        _, y, _ = newPolydata.GetPoint(pointId)
        ATPValue = y / (yRange * 1.0)
        ATPValues.InsertNextValue(ATPValue)
        
    newPolydata.GetCellData().SetScalars(ATPValues)
    
    polyDataWriter = vtk.vtkXMLPolyDataWriter()
    polyDataWriter.SetFileName(filename)
    polyDataWriter.SetInputData(newPolydata)    
    polyDataWriter.Write()
Example #36
0
    def addMeshFromFile(self, name, filename):
        """
        Add a mesh shape from a file.
        Accepted format : .stl or mesh encoded in VTK .vtp format
        """
        if name not in self._ref:

            if os.path.splitext(filename)[-1][1:] == 'stl':
                reader = vtk.vtkSTLReader()
                reader.SetFileName(filename)
                reader.Update()

                with tmpfile() as tmpf:
                    writer=vtk.vtkXMLPolyDataWriter()
                    writer.SetInputData(reader.GetOutput())
                    writer.SetFileName(tmpf[1])
                    writer.Write()

                    shape_data = str_of_file(tmpf[1])

            else:
                assert os.path.splitext(filename)[-1][1:] == 'vtp'
                shape_data = str_of_file(filename)


            self.addMeshShapeFromString(name, shape_data)
Example #37
0
 def __gen_path_vtp(self, path_gesture_data, vtk_path):
     '''
      generate points into VTP file for paraview
      args:
         path_gesture_data: nx12 numpy array, contains
                     [x, y, z, pos_xaxis_x, pos_xaxis_y, pos_xaxis_z, pos_yaxis_x, pos_yaxis_y, pos_yaxis_z,
                     pos_zaxis_x, pos_zaxis_y, pos_zaxis_z]
         vtk_path: string, the stored path vtp files path and file name
     '''
     number_of_steps = path_gesture_data.shape[0]
     points = vtk.vtkPoints()
     points.SetNumberOfPoints(number_of_steps)
     # Create the topology of the point (a vertex)
     vertices = vtk.vtkCellArray()
     vertices.InsertNextCell(number_of_steps)
     for i in range(number_of_steps):
         points.SetPoint(i, path_gesture_data[i, 0], path_gesture_data[i, 1], path_gesture_data[i, 2])
         # We need an an array of point id's for InsertNextCell.
         vertices.InsertCellPoint(i)
     polydata = vtk.vtkPolyData()
     polydata.SetPoints(points)
     polydata.SetLines(vertices)
     namedColors = vtk.vtkNamedColors()
     colors = vtk.vtkUnsignedCharArray()
     colors.SetNumberOfComponents(3)
     colors.InsertNextTypedTuple(namedColors.GetColor3ub("white"))
     polydata.GetCellData().SetScalars(colors)
     writer = vtk.vtkXMLPolyDataWriter()
     writer.SetFileName(vtk_path)
     writer.SetInputData(polydata)
     writer.Write()
     print("path VTP file is generated!")
Example #38
0
    def writePolyData(self, polyData, filename, callback=None):
        """
		Writes the given vtkPolyData instance to disk
					 as .vtp-file with the given filename
		"""
        writer = vtk.vtkXMLPolyDataWriter()
        writer.SetFileName(filename)
        writer.SetInput(polyData)

        def f(obj, evt):
            if obj and callback:
                callback(obj.GetProgress())
            if scripting.mainWindow:
                scripting.mainWindow.updateProgressBar(
                    obj, evt, obj.GetProgress(),
                    "Writing surface %s" % os.path.basename(filename), 0)

        writer.AddObserver("ProgressEvent", lib.messenger.send)
        lib.messenger.connect(writer, "ProgressEvent", f)
        Logging.info("Writing polydata to file %s" % filename, kw="pipeline")
        try:
            ret = writer.Write()

            if ret == 0:
                Logging.error(
                    "Failed to write polygonal data",
                    "Failed to write vtkPolyData object to file %s" % filename)
                return
        except Exception, ex:
            Logging.error(
                "Failed to write poly data",
                "Failed to write vtkPolyData object to file %s" % filename, ex)
            return
Example #39
0
def saveVTP(vtxs, vals, streamlines, filename):
    polydata = vtk.vtkPolyData()
    points = vtk.vtkPoints()
    lines = vtk.vtkCellArray()
    points.SetNumberOfPoints(len(vtxs))
    vtxs2 = vtxs
    for i, p in tqdm(enumerate(vtxs2)):
        points.SetPoint(i, p[0], p[1], p[2])
    for stream in streamlines:
        lines.InsertNextCell(len(stream))
        for i in stream:
            lines.InsertCellPoint(i)
    polydata.SetPoints(points)
    polydata.SetLines(lines)
    pointdata = polydata.GetPointData()
    for sname, sarr in vals.iteritems():
        arr = vtk.vtkFloatArray()
        arr.SetName(sname)
        arr.SetNumberOfComponents(1)
        for v in sarr:
            arr.InsertNextTuple1(v)
        pointdata.AddArray(arr)
        pointdata.SetActiveScalars(sname)
    vwriter = vtk.vtkXMLPolyDataWriter()
    vwriter.SetInput(polydata)
    vwriter.SetFileName(str(filename))
    vwriter.Write()
def createTrail(ts):
    Points = vtk.vtkPoints()
    id_array = vtk.vtkIntArray()
    #id_array.SetNumberofComponents(1)
    id_array.SetName("haloid")
    
    phi_array = vtk.vtkDoubleArray()
    phi_array.SetName("phi")
    for i in range(0,ts+1):
        px,py,pz,phid,pphi = readParticle(i)
        for j in range(0,len(px)):
            Points.InsertNextPoint(px[j],py[j],pz[j])
            id_array.InsertNextTuple1(phid[j])
            phi_array.InsertNextTuple1(pphi[j])
    
    polydata = vtk.vtkPolyData()
    polydata.SetPoints(Points)
    polydata.GetPointData().AddArray(id_array)
    polydata.GetPointData().AddArray(phi_array)
    
    if vtk.VTK_MAJOR_VERSION <= 5:
        polydata.Update()
        
    
    outputFile = "/home/subhashis/VisData/merger_trees/particleTrail/time" + str(ts) + ".vtp" 
        
    writer = vtk.vtkXMLPolyDataWriter();
    writer.SetFileName(outputFile);
    if vtk.VTK_MAJOR_VERSION <= 5:
        writer.SetInput(polydata)
    else:
        writer.SetInputData(polydata)
    writer.Write()
    print "Done generating output for time %d" %ts
Example #41
0
    def Save(self, filename, counter, u, stress, uname='displacement'):
        """ Save the stress result of elements at time t with stress tensor of dim.
            Dim is an array like ['xx', 'yy', 'xy', 'xz', 'yz']
        """
        dim = np.array(['xx', 'yy', 'xy', 'xz', 'yz'])
        for i, name in enumerate(dim):
            for iSmp in range(self.nSmp):
                stressVec = numpy_to_vtk(stress[:, iSmp, i])
                stressVec.SetName('{}_{:03d}'.format(name, iSmp))
                self.polyDataModel.GetCellData().AddArray(stressVec)

        for iSmp in range(self.nSmp):
            uTuples = numpy_to_vtk(u[iSmp, :, :])
            uTuples.SetName('{}_{:03d}'.format(uname, iSmp))
            self.polyDataModel.GetPointData().AddArray(uTuples)

        filename, fileExtension = os.path.splitext(filename)
        stressFilename = '{}{}{}'.format(filename, counter, fileExtension)

        writer = vtk.vtkXMLPolyDataWriter() if fileExtension.endswith(
            'vtp') else vtk.vtkXMLUnstructuredGridWriter()
        writer.SetInputData(self.polyDataModel)
        writer.SetFileName(stressFilename)
        writer.Write()

        print('Write result to {}.'.format(stressFilename))
Example #42
0
def write_vtk_xml_polydata_curve_set(filename, coords_set, attributes=[]):
    levels = len(coords_set)

    vtkmultipieceobj = vtk.vtkMultiPieceDataSet()
    vtkmultipieceobj.SetNumberOfPieces(levels)

    for ii in np.arange(levels):

        coords = coords_set[ii]

        if coords.shape[0] < coords.shape[1]:
            coords = coords.T

        coords = coords.copy()  # To ensure C_CONTIGUOUS is True

        polydata = vtk.vtkPolyData()
        points = vtk.vtkPoints()

        points.SetData(numpy_support.numpy_to_vtk(coords))
        polydata.SetPoints(points)

        lines = vtk.vtkCellArray()
        lines.InsertNextCell(coords.shape[0])
        for i in np.arange(coords.shape[0]):
            lines.InsertCellPoint(i)

        polydata.SetLines(lines)
        vtkmultipieceobj.SetPiece(ii, polydata)

    writer = vtk.vtkXMLPolyDataWriter()
    writer.SetInput(vtkmultipieceobj)
    writer.SetFileName(filename)
    writer.SetDataModeToAscii()
    writer.Write()
Example #43
0
def write_polydata(file_name, data, datatype=None):
    """ Write the given VTK object to a file.

    Args:
        file_name (str): The name of the file to write. 
        data (vtkDataObject): Data to write.
        datatype (str): Additional parameter for vtkIdList objects.
    """
    # Check filename format.
    file_ext = file_name.split(".")[-1]

    if file_ext == '':
        raise RuntimeError('The file does not have an extension')

    # Get writer.
    if file_ext == 'vtp':
        writer = vtk.vtkXMLPolyDataWriter()
    elif file_ext == 'vtu':
        writer = vtk.vtkXMLUnstructuredGridWriter()
    else:
        raise RuntimeError('Unknown file type %s' % file_ext)

    # Set file name and the data to write.
    writer.SetFileName(file_name)
    writer.SetInputData(data)
    writer.Update()

    # Write the data.
    writer.Write()
Example #44
0
def _write_to_file(polydata: Union[PolyData, JoinedPolyData],
                   target_folder: str,
                   file_name: str,
                   writer: VTKWriters = VTKWriters.binary):
    """Write vtkPolyData to a file."""

    extension = writer.value

    if writer.name == 'legacy':
        _writer = vtk.vtkPolyDataWriter()
    else:
        _writer = vtk.vtkXMLPolyDataWriter()
        if writer.name == 'binary':
            _writer.SetDataModeToBinary()
        else:
            _writer.SetDataModeToAscii()

    file_path = pathlib.Path(target_folder, f'{file_name}.{extension}')
    _writer.SetFileName(file_path.as_posix())
    if isinstance(polydata, vtk.vtkPolyData):
        _writer.SetInputData(polydata)
    else:
        _writer.SetInputConnection(polydata.GetOutputPort())

    _writer.Write()
    return file_path.as_posix()
Example #45
0
    def writeDefects(self, defects, numdefect, outfile):
        # Preparing the vtp output
        # Create point structure in vtk
        Points = vtk.vtkPoints()
        print("Created Points")
        Charge = vtk.vtkDoubleArray()
        Charge.SetNumberOfComponents(1)
        Charge.SetName('Charge')
        for u in range(numdefect):
            Points.InsertNextPoint(defects[u][1], defects[u][2], defects[u][3])
            Charge.InsertNextValue(defects[u][0])

        polydata = vtk.vtkPolyData()
        polydata.SetPoints(Points)
        #polydata.SetLines(lines)
        polydata.GetPointData().AddArray(Charge)

        print("Finished Polydata")
        polydata.Modified()
        writer = vtk.vtkXMLPolyDataWriter()
        writer.SetFileName(outfile)
        # Python 2.7 vs. 3 incompatibility?
        if vtk.VTK_MAJOR_VERSION <= 5:
            writer.SetInput(polydata)
        else:
            writer.SetInputData(polydata)
        #writer.SetDataModeToAscii()
        writer.SetDataModeToBinary()
        writer.SetCompressorTypeToZLib()
        writer.Write()
        print("Wrote File")
Example #46
0
def stltoh5(stlfile, basepath, epsilon_inside, epsilon_outside, lattice=Lattice(), verbosity=0):
  
  if not os.path.exists(stlfile):
    if sys.version_info.major == 2:
      raise IOError('No such file or directory: {}'.format(stlfile)) # py2
    else:
      raise FileNotFoundError('No such file or directory: {}'.format(stlfile)) # py3
  
  print('--> timer start')
  time_start = time.time()

  # read in .stl file
  reader = vtk.vtkSTLReader()
  reader.SetFileName(stlfile)
  reader.Update()
  polydata = reader.GetOutput()

  # write .vtp file
  writer = vtk.vtkXMLPolyDataWriter()
  writer.SetInputData(polydata)
  writer.SetFileName(basepath + '.' + writer.GetDefaultFileExtension())
  writer.Write()

  # set up implicit_function
  implicit_function = vtk.vtkImplicitPolyDataDistance()
  implicit_function.SetInput(polydata)

  print("--> Elapsed time: %.4f sec" % (time.time() - time_start))
  
  stl_to_vts_and_h5(implicit_function, basepath, lattice, epsilon_inside, epsilon_outside)
  print("--> Elapsed time: %.4f sec" % (time.time() - time_start))
  return
def rescaleATPToRange():
    # This is where the data is for testing purposes.
    print "Current working directory:", os.getcwd()

    print 'Reading', inputFile
    atpReader = vtk.vtkXMLPolyDataReader()
    atpReader.SetFileName(inputFile)
    atpReader.Update()

    atpDataset = atpReader.GetOutput()
    atp = atpDataset.GetPointData().GetArray('ATP')

    inMin, inMax = atp.GetRange()

    atpR = vtk.vtkFloatArray()
    atpR.SetName('initialATP')    
    
    for i in range(atp.GetNumberOfTuples()):
        val = atp.GetTuple(i)[0]
        atpR.InsertNextValue(rescale(val, inMin, inMax))

    atpDataset.GetCellData().AddArray(atpR)
    
    atpDataset.GetPointData().RemoveArray('ATP')
    atpDataset.GetPointData().RemoveArray('tau_w')
    atpDataset.GetCellData().RemoveArray('initialJPLC')

    print 'Writing', outputFile
    atpWriter = vtk.vtkXMLPolyDataWriter()
    atpWriter.SetInput(atpDataset)
    atpWriter.SetFileName(outputFile)
    atpWriter.Update()

    print 'Reading', inputSurfaceFile
    surfaceReader = vtk.vtkXMLPolyDataReader()
    surfaceReader.SetFileName(inputSurfaceFile)
    surfaceReader.Update()

    surface = surfaceReader.GetOutput()
    surface.GetCellData().AddArray(atpR)

    print 'Writing', outputSurfaceFile
    surfaceWriter = vtk.vtkXMLPolyDataWriter()
    surfaceWriter.SetInput(surface)
    surfaceWriter.SetFileName(outputSurfaceFile)
    surfaceWriter.Update()
Example #48
0
def copyScalarsToVtk(nifti_img, vtk_file, output_file, scalar_name='Scalar'):
    img = nib.load(nifti_img)
    affine = np.matrix(img.get_affine())
    print affine
    img_data = img.get_data()

    ph_data = np.zeros(img_data.shape)
    dims = ph_data.shape
    for i,v in enumerate(np.linspace(0,10,num=dims[0])):
        ph_data[i] += v

    coords = []
    vals = []

    aff_inv = affine.I

    from vtkFileIO import vtkToStreamlines
    import vtk

    streams, vtkdata = vtkToStreamlines(vtk_file)
    points = np.concatenate(streams)
    print 'world'
    max = np.amax(points, axis=0)
    print max
    min = np.amin(points, axis=0)
    print min


    points = np.hstack((points,np.ones((points.shape[0],1))))
    #coords = np.hstack((coords,np.ones((coords.shape[0],1))))

    #coords_world = coords * affine
    points_ijk = aff_inv * points.T
    points_ijk = points_ijk.T[:,:3]

    print 'ijk'
    max = np.amax(points_ijk, axis=0)
    print max
    min = np.amin(points_ijk, axis=0)
    print min

    import time
    s = time.time()
    scalars = trilinear_interpolator_speedup(img_data, points_ijk)

    vtkScalars = vtk.vtkFloatArray()
    vtkScalars.SetName(scalar_name)
    vtkScalars.SetNumberOfComponents(1)
    #vtkScalars.SetNumberOfTuples(len(scalars))
    for i,v in enumerate(scalars):
        vtkScalars.InsertNextTuple1(v)
    vtkdata.GetPointData().SetScalars(vtkScalars)

    writer = vtk.vtkXMLPolyDataWriter()
    #writer = vtk.vtkPolyDataWriter()
    writer.SetInput(vtkdata)
    writer.SetFileName(output_file)
    writer.Write()
def save_one_file(infilename, outfilename):

    df1 = read_file( infilename )

    if df1.shape[0]==0:
      return

    pts = vtk.vtkPoints()
    x = df1['COORX']
    y = df1['COORY']
    z = df1['COORZ']
    tp = df1['ITYPE']
    il = df1['ILAGR']
    ex = df1['EXIST']
    tt = df1['T']
    pts.SetNumberOfPoints(df1.shape[0])

    for j in range(df1.shape[0]):         
        pts.SetPoint(j, (x.iloc[j],y.iloc[j],z.iloc[j]))

    types = vtk.vtkShortArray()
    types.SetNumberOfComponents(1)
    types.SetNumberOfTuples(pts.GetNumberOfPoints())
    types.SetName('ITYPE')
  
    ilagr = vtk.vtkIntArray()
    ilagr.SetNumberOfComponents(1)
    ilagr.SetNumberOfTuples(pts.GetNumberOfPoints())
    ilagr.SetName('ILAGR')

    exist = vtk.vtkShortArray()
    exist.SetNumberOfComponents(1)
    exist.SetNumberOfTuples(pts.GetNumberOfPoints())
    exist.SetName('EXIST')

    T = vtk.vtkFloatArray()
    T.SetNumberOfComponents(1)
    T.SetNumberOfTuples(pts.GetNumberOfPoints())
    T.SetName('T')

    for j in range(df1.shape[0]):         
        types.SetTuple1(j, tp.iloc[j])
        ilagr.SetTuple1(j, il.iloc[j])
        exist.SetTuple1(j, ex.iloc[j])
        T.SetTuple1(j, tt.iloc[j])

    pd = vtk.vtkPolyData()
    pd.SetPoints(pts)
    pd.GetPointData().AddArray(types)
    pd.GetPointData().AddArray(ilagr)
    pd.GetPointData().AddArray(exist)
    pd.GetPointData().AddArray(T)

    wr= vtk.vtkXMLPolyDataWriter()
    wr.SetInputData(pd)
    wr.SetDataModeToBinary()
    wr.SetFileName(outfilename)
    wr.Write()
Example #50
0
def geom_viz(geomData, filename='sample.vtp'):
    """
    DESCRIPTION
    -----------
    geom_viz(geomData, filename='geom.vtp')
    Generate a simple point centered vtp file to visualize grain ID.
    PARAMETERS
    ----------
    geomData: numpy.array
    Grain ID populated in a numpy array representing the extruded
    microstructure.
    filename: str
    Output VTP file name.
    RETURNS
    -------
    NOTES
    ----
    """
    polydata = vtk.vtkPolyData()
    points = vtk.vtkPoints()
    vertices = vtk.vtkCellArray()

    gids = vtk.vtkFloatArray()
    gids.SetNumberOfComponents(1)
    gids.SetName("GrainID")

    # iterating through CPFFT data
    cnt = 0
    x, y, z = geomData.shape
    for i in range(x):
        for j in range(y):
            for k in range(z):
                # set position
                points.InsertNextPoint(i, j, k)
                vertex = vtk.vtkVertex()
                vertex.GetPointIds().SetId(0, cnt)
                cnt += 1
                vertices.InsertNextCell(vertex)
                # set Grain ID
                gids.InsertNextTuple1(geomData[i, j, k])
    # finish the vtp object
    polydata.SetPoints(points)
    polydata.SetVerts(vertices)
    polydata.GetPointData().SetScalars(gids)
    polydata.Modified()

    if vtk.VTK_MAJOR_VERSION <= 5:
        polydata.Update()

    writer = vtk.vtkXMLPolyDataWriter()
    writer.SetFileName(filename)

    if vtk.VTK_MAJOR_VERSION <= 5:
        writer.SetInput(polydata)
    else:
        writer.SetInputData(polydata)

    writer.Write()
Example #51
0
 def WriteVTKXMLNetworkFile(self):
     if self.OutputFileName == '':
         self.PrintError('Error: no OutputFileName.')
     self.PrintLog('Writing VTK XML network file.')
     writer = vtk.vtkXMLPolyDataWriter()
     writer.SetInput(self.Network)
     writer.SetFileName(self.OutputFileName)
     #writer.SetDataModeToAscii()
     writer.Write()
Example #52
0
def writeVTPFile(fileName,vtkPolyObject):
    '''Function to write vtk polydata file (vtp).'''
    polyWriter = vtk.vtkXMLPolyDataWriter()
    if float(vtk.VTK_VERSION.split('.')[0]) >=6:
        polyWriter.SetInputData(vtkPolyObject)
    else:
        polyWriter.SetInput(vtkPolyObject)
    polyWriter.SetFileName(fileName)
    polyWriter.Update()
Example #53
0
 def WriteVTKXMLSurfaceFile(self):
     if (self.OutputFileName == ''):
         self.PrintError('Error: no OutputFileName.')
     self.PrintLog('Writing VTK XML surface file.')
     writer = vtk.vtkXMLPolyDataWriter()
     writer.SetInput(self.Surface)
     writer.SetFileName(self.OutputFileName)
     #writer.SetDataModeToAscii()
     writer.Write()
Example #54
0
    def buildcube(self, args):
        path = '/var/www/polycache/'
        ci = args[3]
        cubedimension = args[4]
        timestep = args[5]
        xcorner = args[0]
        ycorner = args[1]
        zcorner = args[2]
        #Django hack for connection issue with multiprocessing.  This forces a new connection for each process.
        connection.close()
        #print("Gettting cube: ", xcorner, ycorner, zcorner)
        mortonstart = jhtdblib.JHTDBLib().createmortonindex(xcorner, ycorner, zcorner)
        mortonend = jhtdblib.JHTDBLib().createmortonindex(xcorner + cubedimension, ycorner + cubedimension, zcorner + cubedimension)
        dataset = Dataset.objects.get(dbname_text=ci.dataset)
        #Determine if we have a hit or miss.
        cache = Polycache.objects.filter(zindexstart =mortonstart,zindexend = mortonend, dataset=dataset, threshold=ci.threshold, timestep=timestep, filterwidth=ci.filter)
        #import pdb; pdb.set_trace();
        #We don't want to cache strided contour data.
        #skip cache for concurrent testing
        fullname = ""
        if ((len(cache) > 0) and 0 and (ci.xstep ==1) and (ci.ystep == 1) and (ci.zstep==1)): #cache hit, serve up the file
            #print("Cache hit " + str(timestep))
            #reader = vtk.vtkXMLPolyDataReader()
            #reader.SetFileName(path + cache[0].filename)
            #print path + cache[0].filename
            #vtpcube = reader
            fullname = path + cache[0].filename

        else: #Cache miss, grab from db and cache the result
            #print ("Cache miss")
            cubeci = copy.deepcopy(ci)
            cubeci.xstart = xcorner
            cubeci.ystart = ycorner
            cubeci.zstart = zcorner
            cubeci.xlen= cubeci.ylen= cubeci.zlen = cubedimension
            start = time.time()
            vtpcube = self.getvtkdata(cubeci, timestep)
            end = time.time()
            #Now write to disk
            writer = vtk.vtkXMLPolyDataWriter()
            vtpfilename = ci.dataset + '-' + str(ci.threshold).replace(".", "_") +'-' +str(ci.filter) + '-'+ str(timestep)+'-'+ str(mortonstart) + '-' + str(mortonend)
            fullname = path + vtpfilename
            writer.SetFileName(fullname)
            writer.SetInputData(vtpcube.GetOutput())
            writer.Write()
            
            #cleanup

            #ccache = Polycache(zindexstart=mortonstart, zindexend=mortonend, filename=vtpfilename, compute_time=(end-start), threshold=ci.threshold,dataset=dataset, computation=ci.datafields.split(",")[0], timestep=timestep, filterwidth=ci.filter)
            #ccache.save()
            #import pdb;pdb.set_trace()
        #print("Returning cube: ", xcorner, ycorner, zcorner)
        #return vtpcube
        #q.put(vtpcube.GetOutputPort())
        #fullcube.AddInputConnection(vtpcube.GetOutputPort())
        #print("wrote tempfile")
        return (fullname)
Example #55
0
def Export(polydata, filename, bin=False):
    writer = vtk.vtkXMLPolyDataWriter()
    writer.SetFileName(filename)
    if bin:
        writer.SetDataModeToBinary()
    else:
        writer.SetDataModeToAscii()
    writer.SetInput(polydata)
    writer.Write()
Example #56
0
    def CentreLinePolyData(self):
        """Compute centrelines based on the profile, reusing our
        memoed copy or reading from the cache file if possible.
        """
        if (os.path.exists(self.CentreLineFile ) and 
            os.path.getmtime(self.CentreLineFile ) > os.path.getmtime(self.StlFile) and
            os.path.getmtime(self.CentreLineFile ) > os.path.getmtime(self.FileName)):
            # Cached!
            reader = vtk.vtkXMLPolyDataReader()
            reader.SetFileName(self.CentreLineFile)
            reader.Update()
            return reader.GetOutput()

        # Have to compute it
        
        # Read the STL file
        reader = vtk.vtkSTLReader()
        reader.SetFileName(profile.StlFile)
        
        # Find the seed points for centreline calculation
        # Use points one iolet radius back along the normal.
        
        outletPts = []
        def scale(iolet):
            pt = (iolet.Centre - iolet.Radius * iolet.Normal)
            pt = pt / self.LengthUnit
            return pt.magnitude
        
        for iolet in self.Iolets:
            if isinstance(iolet._iolet, Inlet):
                inletPt = scale(iolet)
            else:
                outletPts.append(scale(iolet))
                pass
            continue
        
        srcPts, tgtPts = FindSeeds(reader, inletPt, outletPts)
        
        # Lazy import since it's so slow!
        from vmtk import vtkvmtk
        centreliner = vtkvmtk.vtkvmtkPolyDataCenterlines()
        centreliner.SetInputConnection(reader.GetOutputPort())
    
        centreliner.SetSourceSeedIds(srcPts)
        centreliner.SetTargetSeedIds(tgtPts)
        centreliner.SetRadiusArrayName("radius")
        centreliner.SetCostFunction("1/R")

        cleaner = vtk.vtkCleanPolyData()
        cleaner.SetInputConnection(centreliner.GetOutputPort())
        
        writer = vtk.vtkXMLPolyDataWriter()
        writer.SetInputConnection(cleaner.GetOutputPort())
        writer.SetFileName(self.CentreLineFile)
        writer.Write()
        return cleaner.GetOutput()
Example #57
0
def WritePolyData(surface, filename):
    """ Scrive PolyData su file """
    if not os.path.exists(filename):
        writer = vtk.vtkXMLPolyDataWriter()
        writer.SetInput(surface)
        writer.SetFileName(filename)
        writer.Write()
        return filename
    else:
        return filename
Example #58
0
 def WriteVTKXMLSurfaceFile(self):
     if self.OutputFileName == "":
         self.PrintError("Error: no OutputFileName.")
     self.PrintLog("Writing VTK XML surface file.")
     writer = vtk.vtkXMLPolyDataWriter()
     if self.Ascii:
         writer.SetDataModeToAscii()
     writer.SetInput(self.Surface)
     writer.SetFileName(self.OutputFileName)
     writer.Write()
Example #59
0
def Export(polydata, filename, bin=False):
    writer = vtk.vtkXMLPolyDataWriter()
    print filename, type(filename)
    writer.SetFileName(filename.encode('utf-8'))
    if bin:
        writer.SetDataModeToBinary()
    else:
        writer.SetDataModeToAscii()
    writer.SetInputData(polydata)
    writer.Write()