def compute(self): variable = self.getInputFromPort('tvariable') filename = self.getInputFromPort('filename') print "convert to vtk image data" cv = PVCDMSReader() image_data = cv.convert(variable.data) print "convert to poly data" geom = vtk.vtkImageDataGeometryFilter() geom.SetInputData(image_data) geom.ReleaseDataFlagOn() print "Convert to GeoJSON" gw = vtk.vtkGeoJSONWriter() gw.SetInputConnection(geom.GetOutputPort()) gw.WriteToOutputStringOn() gw.Write() gj = str(gw.RegisterAndGetOutputString()).replace('\n','') outf = open(filename, 'w') outf.write(gj)
def runGeoJSONCropExample(input_filename, bbox_filename): inputDataset = loadGeoJSONData(input_filename) bboxDataset = loadGeoJSONData(bbox_filename) # Use the bounds from the bounding box to create an implicit function queryBounds = list(bboxDataset.GetBounds()) bbox = vtk.vtkPlanes() bbox.SetBounds(queryBounds) # This filter uses the implicit function to extract the data bboxFilter = vtk.vtkExtractPolyDataGeometry() bboxFilter.SetInputData(inputDataset) bboxFilter.SetImplicitFunction(bbox) # Exclude (set to 0) or include (set to 1) districts on the boundary bboxFilter.SetExtractBoundaryCells(0) # Get the cropped region and write it to disk bboxFilter.Update() croppedDataset = bboxFilter.GetOutput() outputWriter = vtk.vtkGeoJSONWriter() outputWriter.SetFileName('cropped_output.geojson') outputWriter.SetInputData(croppedDataset) outputWriter.Write() renderer = init() inputActor = renderPolyData(renderer, inputDataset) bboxActor = renderPolyData(renderer, bboxDataset) cropActor = renderPolyData(renderer, croppedDataset) # Set rendering type and color on the actors inputActor.GetProperty().SetRepresentationToWireframe() inputActor.GetProperty().SetColor(0.0, 1.0, 0.0) bboxActor.GetProperty().SetRepresentationToWireframe() bboxActor.GetProperty().SetColor(1.0, 0.0, 0.0) cropActor.GetProperty().SetRepresentationToWireframe() cropActor.GetProperty().SetColor(1.0, 0.0, 1.0) run()
onevertglyph = vtk.vtkPolyData() onevertglyph.SetPoints(pts) onevertglyph.SetVerts(verts) gf.SetSourceData(onevertglyph) gf.SetInputConnection(af.GetOutputPort()) testwrites = ["points","lines","mesh"] failed = False for datasetString in testwrites: if datasetString == "points": toshow=gf elif datasetString == "lines": toshow = ef else: toshow = af gw = vtk.vtkGeoJSONWriter() fname = "sphere_"+datasetString+".json" gw.SetInputConnection(toshow.GetOutputPort()) gw.SetFileName(fname) gw.Write() if (os.path.exists(fname) and os.path.isfile(fname)): os.remove(fname) else: print "Failed to write " + fname + " to file" failed = True gw.WriteToOutputStringOn() gw.Write() gj = "['"+str(gw.RegisterAndGetOutputString()).replace('\n','')+"']" if len(gj) <= 1000: print "Failed to write " + fname + " to buffer"
onevertglyph = vtk.vtkPolyData() onevertglyph.SetPoints(pts) onevertglyph.SetVerts(verts) gf.SetSourceData(onevertglyph) gf.SetInputConnection(af.GetOutputPort()) testwrites = ["points", "lines", "mesh"] failed = False for datasetString in testwrites: if datasetString == "points": toshow = gf elif datasetString == "lines": toshow = ef else: toshow = af gw = vtk.vtkGeoJSONWriter() fname = "sphere_" + datasetString + ".json" gw.SetInputConnection(toshow.GetOutputPort()) gw.SetFileName(fname) gw.Write() if (os.path.exists(fname) and os.path.isfile(fname)): os.remove(fname) else: print "Failed to write " + fname + " to file" failed = True gw.WriteToOutputStringOn() gw.Write() gj = "['" + str(gw.RegisterAndGetOutputString()).replace('\n', '') + "']" if len(gj) <= 1000: print "Failed to write " + fname + " to buffer" failed = True
def serveVTKGeoJSON(self, datasetString): ''' Deliver a geojson encoded serialized vtkpolydata file and render it over the canonical cpipe scene. ''' if vtkOK == False: return """<html><head></head><body>VTK python bindings are not loadable, be sure VTK is installed on the server and its PATHS are set appropriately.</body><html>""" ss = vtk.vtkNetCDFCFReader() #get test data ss.SphericalCoordinatesOff() ss.SetOutputTypeToImage() datadir = cherrypy.request.app.config['/data']['tools.staticdir.dir'] datadir = os.path.join(datadir, 'assets') datafile = os.path.join(datadir, 'clt.nc') ss.SetFileName(datafile) sf = vtk.vtkDataSetSurfaceFilter() #convert to polydata sf.SetInputConnection(ss.GetOutputPort()) cf = vtk.vtkContourFilter() #add some attributes cf.SetInputConnection(sf.GetOutputPort()) cf.SetInputArrayToProcess(0,0,0,"vtkDataObject::FIELD_ASSOCIATION_POINTS", "clt") cf.SetNumberOfContours(10) sf.Update() drange = sf.GetOutput().GetPointData().GetArray(0).GetRange() for x in range(0,10): cf.SetValue(x,x*0.1*(drange[1]-drange[0])+drange[0]) cf.ComputeScalarsOn() ef = vtk.vtkExtractEdges() #make lines to test ef.SetInputConnection(sf.GetOutputPort()) gf = vtk.vtkGlyph3D() #make verts to test pts = vtk.vtkPoints() pts.InsertNextPoint(0,0,0) verts = vtk.vtkCellArray() avert = vtk.vtkVertex() avert.GetPointIds().SetId(0, 0) verts.InsertNextCell(avert) onevertglyph = vtk.vtkPolyData() onevertglyph.SetPoints(pts) onevertglyph.SetVerts(verts) gf.SetSourceData(onevertglyph) gf.SetInputConnection(sf.GetOutputPort()) if datasetString == "points": toshow = gf elif datasetString == "lines": toshow = ef elif datasetString == "contour": toshow = cf else: toshow = sf gw = vtk.vtkGeoJSONWriter() gw.SetInputConnection(toshow.GetOutputPort()) gw.SetScalarFormat(2); if True: gw.SetFileName("/Source/CPIPES/buildogs/deploy/dataset.gj") gw.Write() f = file("/Source/CPIPES/buildogs/deploy/dataset.gj") gj = str(f.readlines()) else: gw.WriteToOutputStringOn() gw.Write() gj = "['"+str(gw.RegisterAndGetOutputString()).replace('\n','')+"']" res = (""" <html> <head> <script type="text/javascript" src="/common/js/gl-matrix.js"></script> <script type="text/javascript" src="/lib/geoweb.min.js"></script> <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script> <script type="text/javascript"> function makedata() { var datasetString = %(gjfile)s.join('\\n'); var data = new ogs.vgl.geojsonReader().getPrimitives(datasetString); var geoms = data.geoms; var mapper = new ogs.vgl.mapper(); mapper.setGeometryData(geoms[0]); """ + self.gjShader + """ var actor = new ogs.vgl.actor(); actor.setMapper(mapper); actor.setMaterial(mat); return actor; } </script> <script type="text/javascript"> function main() { var mapOptions = { zoom : 1, center : ogs.geo.latlng(0.0, 0.0), source : '/data/assets/land_shallow_topo_2048.png' }; var myMap = ogs.geo.map(document.getElementById("glcanvas"), mapOptions); var planeLayer = ogs.geo.featureLayer({ "opacity" : 1, "showAttribution" : 1, "visible" : 1 }, makedata() ); myMap.addLayer(planeLayer); } </script> <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.1/themes/base/jquery-ui.css" /> <script src="http://code.jquery.com/jquery-1.9.1.js"></script> <script src="http://code.jquery.com/ui/1.10.1/jquery-ui.js"></script> </head> <body onload="main()"> <canvas id="glcanvas" width="800" height="600"></canvas> </body> </html> """) % {'gjfile' :gj} return res
def read(self, variables, timestep): #obtain temporal information rawTimes = self._reader.GetOutputInformation(0).Get(vtk.vtkStreamingDemandDrivenPipeline.TIME_STEPS()) tunits = self._reader.GetTimeUnits() converters = attrib_to_converters(tunits) # pick particular timestep if timestep is not None and rawTimes is not None: utcconverter = attrib_to_converters("days since 1970-0-0") abs_request_time = utcconverter[0](float(timestep)/(1000*60*60*24)) local_request_time = converters[5](abs_request_time) # For now clamp to time range if float(local_request_time) < rawTimes[0]: local_request_time = rawTimes[0] elif float(local_request_time) > rawTimes[-1]: local_request_time = rawTimes[-1] sddp = self._reader.GetExecutive() sddp.SetUpdateTimeStep(0, local_request_time) # enable only chosen array(s) narrays = self._reader.GetNumberOfVariableArrays() for x in range(0,narrays): arrayname = self._reader.GetVariableArrayName(x) if arrayname in variables: #cherrypy.log("Enable " + arrayname) self._reader.SetVariableArrayStatus(arrayname, 1) else: #cherrypy.log("Disable " + arrayname) self._reader.SetVariableArrayStatus(arrayname, 0) # wrap around to get the implicit cell extent = self._reader.GetOutputInformation(0).Get(vtk.vtkStreamingDemandDrivenPipeline.WHOLE_EXTENT()) pad = vtk.vtkImageWrapPad() self._reader.Update() data = self._reader.GetOutput() da = data.GetPointData().GetArray(0).GetName(); data.GetPointData().SetActiveScalars(da) pad.SetInputData(data) pad.SetOutputWholeExtent(extent[0], extent[1]+1, extent[2], extent[3], extent[4], extent[5]); # Convert to polydata sf = vtk.vtkDataSetSurfaceFilter() sf.SetInputConnection(pad.GetOutputPort()) # Error reading file? if not sf.GetOutput(): raise IOError("Unable to load data file: " + self.filename) # Convert to GeoJSON gw = vtk.vtkGeoJSONWriter() gw.SetInputConnection(sf.GetOutputPort()) gw.SetScalarFormat(2) gw.WriteToOutputStringOn() gw.Write() gj = str(gw.RegisterAndGetOutputString()).replace('\n','') return gj
def read(filename, vars, rqstTime): ''' Read a file or files from a directory given a wild-card expression ''' # @todo Reading a single file of netcdf cf convention now #cherrypy.log("vtkread " + filename + " " + vars + " " + str(time)) reader = vtk.vtkNetCDFCFReader() #get test data reader.SphericalCoordinatesOff() reader.SetOutputTypeToImage() reader.ReplaceFillValueWithNanOn() reader.SetFileName(filename) reader.UpdateInformation() #obtain temporal information rawTimes = reader.GetOutputInformation(0).Get(vtk.vtkStreamingDemandDrivenPipeline.TIME_STEPS()) tunits = reader.GetTimeUnits() converters = attrib_to_converters(tunits) # pick particular timestep if rqstTime is not None and rawTimes is not None: utcconverter = attrib_to_converters("days since 1970-0-0") abs_request_time = utcconverter[0](float(rqstTime)/(1000*60*60*24)) local_request_time = converters[5](abs_request_time) # For now clamp to time range if float(local_request_time) < rawTimes[0]: local_request_time = rawTimes[0] elif float(local_request_time) > rawTimes[-1]: local_request_time = rawTimes[-1] sddp = reader.GetExecutive() sddp.SetUpdateTimeStep(0, local_request_time) # enable only chosen array(s) narrays = reader.GetNumberOfVariableArrays() for x in range(0,narrays): arrayname = reader.GetVariableArrayName(x) if arrayname in vars: #cherrypy.log("Enable " + arrayname) reader.SetVariableArrayStatus(arrayname, 1) else: #cherrypy.log("Disable " + arrayname) reader.SetVariableArrayStatus(arrayname, 0) # wrap around to get the implicit cell extent = reader.GetOutputInformation(0).Get(vtk.vtkStreamingDemandDrivenPipeline.WHOLE_EXTENT()) pad = vtk.vtkImageWrapPad() reader.Update() data = reader.GetOutput() da = data.GetPointData().GetArray(0).GetName(); data.GetPointData().SetActiveScalars(da) pad.SetInputData(data) pad.SetOutputWholeExtent(extent[0], extent[1]+1, extent[2], extent[3], extent[4], extent[5]); # Convert to polydata sf = vtk.vtkDataSetSurfaceFilter() sf.SetInputConnection(pad.GetOutputPort()) # Error reading file? if not sf.GetOutput(): raise IOError("Unable to load data file: " + filename) # Convert to GeoJSON gw = vtk.vtkGeoJSONWriter() gw.SetInputConnection(sf.GetOutputPort()) gw.SetScalarFormat(2) gw.WriteToOutputStringOn() gw.Write() gj = str(gw.RegisterAndGetOutputString()).replace('\n','') return gj