def insert(self, document): if not self.view: return if self.CaptureDepth: simple.Render() image = self.view.CaptureDepthBuffer() idata = numpy_support.vtk_to_numpy(image) rw = self.view.GetRenderWindow() width,height = rw.GetSize() try: imageslice = idata.reshape(height,width) except ValueError: imageslice = None #import Image #img = Image.fromarray(imageslice) #img.show() #try: # input("Press enter to continue ") #except NameError: # pass document.data = imageslice self.CaptureDepth = False else: imageslice = None if self.CaptureLuminance and not self.UsingGL2: try: rep = simple.GetRepresentation() if rep != None: rep.DiffuseColor = [1,1,1] rep.ColorArrayName = None except ValueError: pass image = self.view.CaptureWindow(1) ext = image.GetExtent() width = ext[1] - ext[0] + 1 height = ext[3] - ext[2] + 1 imagescalars = image.GetPointData().GetScalars() idata = numpy_support.vtk_to_numpy(imagescalars) idata = self.rgb2grey(idata, height, width) imageslice = np.dstack((idata,idata,idata)) image.UnRegister(None) else: image = self.view.CaptureWindow(1) ext = image.GetExtent() width = ext[1] - ext[0] + 1 height = ext[3] - ext[2] + 1 imagescalars = image.GetPointData().GetScalars() idata = numpy_support.vtk_to_numpy(imagescalars) imageslice = idata.reshape(height,width,3) image.UnRegister(None) #import Image #img = Image.fromarray(imageslice) #img.show() #try: # input("Press enter to continue ") #except NameError: # pass document.data = imageslice if self.iSave: super(ImageExplorer, self).insert(document)
def insert(self, document): if not self.view: return if self.CaptureDepth: simple.Render() image = self.view.CaptureDepthBuffer() idata = numpy_support.vtk_to_numpy(image) rw = self.view.GetRenderWindow() width, height = rw.GetSize() try: imageslice = idata.reshape(height, width) except ValueError: imageslice = None #import Image #img = Image.fromarray(imageslice) #img.show() #try: # input("Press enter to continue ") #except NameError: # pass document.data = imageslice self.CaptureDepth = False else: imageslice = None if self.CaptureLuminance and not self.UsingGL2: try: rep = simple.GetRepresentation() if rep != None: rep.DiffuseColor = [1, 1, 1] rep.ColorArrayName = None except ValueError: pass image = self.view.CaptureWindow(1) ext = image.GetExtent() width = ext[1] - ext[0] + 1 height = ext[3] - ext[2] + 1 imagescalars = image.GetPointData().GetScalars() idata = numpy_support.vtk_to_numpy(imagescalars) idata = self.rgb2grey(idata, height, width) imageslice = np.dstack((idata, idata, idata)) image.UnRegister(None) else: image = self.view.CaptureWindow(1) ext = image.GetExtent() width = ext[1] - ext[0] + 1 height = ext[3] - ext[2] + 1 imagescalars = image.GetPointData().GetScalars() idata = numpy_support.vtk_to_numpy(imagescalars) imageslice = idata.reshape(height, width, 3) image.UnRegister(None) #import Image #img = Image.fromarray(imageslice) #img.show() #try: # input("Press enter to continue ") #except NameError: # pass document.data = imageslice if self.iSave: super(ImageExplorer, self).insert(document)
def rgbreader(self, fname): """opens a color image file and returns it as a color buffer""" if "VTK" in self.backends: reader = self._make_reader(fname) reader.SetFileName(fname) reader.Update() id = reader.GetOutput() ext = id.GetExtent() width = ext[1]+1 height = ext[3]+1 imageslice = n2v.vtk_to_numpy(id.GetPointData().GetArray(0)) imageslice = imageslice.reshape(height, width, 3) return numpy.flipud(imageslice) elif "PIL" in self.backends: try: im = PIL.Image.open(fname) # this image could be any format, but we require RGB # as we handle this image conv_im = im.convert("RGB") return numpy.array( conv_im, numpy.uint8).reshape(im.size[1], im.size[0], 3) except: return None else: print("Warning: need PIL or VTK to read from " + fname)
def test_source_from_a_xy_plane_rectangular_lattice(self): # given lattice = make_orthorhombic_lattice( 'test', (0.3, 0.35, 0.4), (13, 23, 1), origin=(0.2, -2.7, 0.0)) self.add_velocity(lattice) # when data_set = cuds2vtk(cuds=lattice) # then self.assertEqual(data_set.GetNumberOfPoints(), 13 * 23) assert_array_equal(data_set.GetOrigin(), (0.2, -2.7, 0.0)) point_data = data_set.GetPointData() arrays = { point_data.GetArray(index).GetName(): vtk_to_numpy(point_data.GetArray(index)) for index in range(point_data.GetNumberOfArrays())} for node in lattice.iter(item_type=CUBA.NODE): point_id = data_set.ComputePointId(node.index) assert_array_equal( lattice.get_coordinate(node.index), data_set.GetPoint(point_id)) for key, value in node.data.iteritems(): assert_array_equal(arrays[key.name][point_id], value)
def parametrize_dataset(dataset, grid): from paraview.numpy_support import vtk_to_numpy xyz = vtk_to_numpy(dataset.GetPoints().GetData()) from numpy import sqrt from numpy import zeros_like xrt = zeros_like(xyz) xrt[:, 0] = xyz[:, 0] xrt[:, 1] = sqrt(xyz[:, 1] ** 2 + xyz[:, 2] ** 2) from paraview.numpy_support import numpy_to_vtk from paraview.vtk import vtkPoints points = vtkPoints() points.SetData(numpy_to_vtk(xrt, deep=1)) input = vtk.vtkPolyData() input.SetPoints(points) probe = vtk.vtkProbeFilter() probe.SetInput(input) probe.SetSource(grid) probe.Update() outputPointData = probe.GetOutput().GetPointData() pointData = dataset.GetPointData() pointData.AddArray(outputPointData.GetArray('hsH')) pointData.AddArray(outputPointData.GetArray('xm'))
def rgbreader(self, fname): """opens a color image file and returns it as a color buffer""" if "VTK" in self.backends: reader = self._make_reader(fname) reader.SetFileName(fname) reader.Update() id = reader.GetOutput() ext = id.GetExtent() width = ext[1] + 1 height = ext[3] + 1 imageslice = n2v.vtk_to_numpy(id.GetPointData().GetArray(0)) imageslice = imageslice.reshape(height, width, 3) return numpy.flipud(imageslice) elif "PIL" in self.backends: try: im = PIL.Image.open(fname) # this image could be any format, but we require RGB # as we handle this image conv_im = im.convert("RGB") return numpy.array(conv_im, numpy.uint8).reshape( im.size[1], im.size[0], 3) except: return None else: print("Warning: need PIL or VTK to read from " + fname)
def test_source_from_an_orthorhombic_lattice(self): # given lattice = make_orthorhombic_lattice( 'test', (0.5, 0.54, 0.58), (15, 25, 35), (7, 9, 8)) self.add_velocity(lattice) # when data_set = cuds2vtk(cuds=lattice) # then self.assertEqual(data_set.GetNumberOfPoints(), 15 * 25 * 35) assert_array_equal(data_set.GetOrigin(), (7.0, 9.0, 8.0)) point_data = data_set.GetPointData() arrays = { point_data.GetArray(index).GetName(): vtk_to_numpy(point_data.GetArray(index)) for index in range(point_data.GetNumberOfArrays())} for node in lattice.iter(item_type=CUBA.NODE): point_id = data_set.ComputePointId(node.index) assert_array_equal( lattice.get_coordinate(node.index), data_set.GetPoint(point_id)) for key, value in node.data.iteritems(): assert_array_equal(arrays[key.name][point_id], value)
def vtkDataArrayToVTKArray(array, dataset=None): "Given a vtkDataArray and a dataset owning it, returns a VTKArray." narray = numpy_support.vtk_to_numpy(array) # The numpy_support convention of returning an array of snape (n,) # causes problems. Change it to (n,1) if len(narray.shape) == 1: narray = narray.reshape(narray.shape[0], 1) return VTKArray(narray, array=array, dataset=dataset)
def submesh_numpy(pdi, pdo, cell_list): """ Extract cells from pdi with id in the list cell_ids. Create output dataset in pdo. This implementation is stub but aiming to be faster then submesh(). """ pdo.DeepCopy(pdi) pdo.Reset() cell_data=pdi.GetCellData() selection_ids=cell_list # get number of points for every cell cell_types=ns.vtk_to_numpy(pdi.GetCellTypesArray()) cell_0d_ids=np.where(cell_types==VTK_VERTEX)[0] cell_1d_ids=np.where(cell_types==VTK_LINE)[0] cell_2d_ids=np.where(cell_types==VTK_TRIANGLE)[0] cell_3d_ids=np.where(cell_types==VTK_TETRA)[0] cell_sizes=np.zeros(len(cell_types), dtype=int) cell_sizes[cell_0d_ids]=1 cell_sizes[cell_1d_ids]=2 cell_sizes[cell_2d_ids]=3 cell_sizes[cell_3d_ids]=4 assert(len(np.where(cell_sizes==0)[0])==0) # starts of cells in "cells" array cell_locations=ns.vtk_to_numpy(pdi.GetCellLocationsArray()) cells=ns.vtk_to_numpy(pdi.GetCells().GetData()) # padd cells row_ends = np.concatenate((cell_locations, [len(cells)])) lens = np.diff(row_ends) max_len=np.max(lens) pad_len = np.max(lens) - lens where_to_pad = np.repeat(row_ends[1:], pad_len) padding_value = -1.0 padded_cells = np.insert(cells, where_to_pad, -1).reshape(-1, max_len) selected_cells=padded_cells[selection_ids] points=selected_cells[:, 1:].flatten() #points=points[points!=-1] np.set_printoptions(threshold=np.nan)
def captureWindowAsNumpy(self): image = self.view.CaptureWindow(1) ext = image.GetExtent() width = ext[1] - ext[0] + 1 height = ext[3] - ext[2] + 1 imagescalars = image.GetPointData().GetScalars() idata = numpy_support.vtk_to_numpy(imagescalars) image.UnRegister(None) return idata, width, height
def calculer_surface_moyenne(surface_1, surface_2, precision=1e-6, pas_initial=10): """fonction qui calcule une surface moyenne par la methode des spheres inscrites extension de la methode des cercles inscrits """ # conversion en polydata et fusion des blocs surface_1 = convertir_surface_en_polydata(surface_1) surface_2 = convertir_surface_en_polydata(surface_2) #calcul du vecteur Normals normals = vtk.vtkPolyDataNormals() normals.SetInput(surface_1) normals.Update() surface_1_modif = normals.GetOutput() # derafinement de la surface_1 #derafiner = vtk.vtkCleanPolyData() #derafiner.SetInput(surface_1_modif) #derafiner.SetToleranceIsAbsolute(1) #derafiner.SetAbsoluteTolerance(1) #derafiner.Update() #surface_1_modif = derafiner.GetOutput() # calcul de la surface moyenne surface_moyenne = trouver_centres_spheres_inscrites(surface_1_modif, surface_2, precision = precision, pas_initial = pas_initial) normals = vtk.vtkPolyDataNormals() normals.SetInput(surface_moyenne) normals.ConsistencyOn() normals.Update() surface_moyenne = normals.GetOutput() coords = numpy_support.vtk_to_numpy(surface_moyenne.GetPoints().GetData()) normals = numpy_support.vtk_to_numpy(surface_moyenne.GetPointData().GetArray('Normals')) inf = coords - normals * 1e3 sup = coords + normals * 1e3 source = vtk.vtkLineSource() source.SetPoint1(inf[0]) source.SetPoint2(sup[0]) # return source.GetOutput() return surface_moyenne
def submesh_numpy(pdi, pdo, cell_list): """ Extract cells from pdi with id in the list cell_ids. Create output dataset in pdo. This implementation is stub but aiming to be faster then submesh(). """ pdo.DeepCopy(pdi) pdo.Reset() cell_data = pdi.GetCellData() selection_ids = cell_list # get number of points for every cell cell_types = ns.vtk_to_numpy(pdi.GetCellTypesArray()) cell_0d_ids = np.where(cell_types == VTK_VERTEX)[0] cell_1d_ids = np.where(cell_types == VTK_LINE)[0] cell_2d_ids = np.where(cell_types == VTK_TRIANGLE)[0] cell_3d_ids = np.where(cell_types == VTK_TETRA)[0] cell_sizes = np.zeros(len(cell_types), dtype=int) cell_sizes[cell_0d_ids] = 1 cell_sizes[cell_1d_ids] = 2 cell_sizes[cell_2d_ids] = 3 cell_sizes[cell_3d_ids] = 4 assert (len(np.where(cell_sizes == 0)[0]) == 0) # starts of cells in "cells" array cell_locations = ns.vtk_to_numpy(pdi.GetCellLocationsArray()) cells = ns.vtk_to_numpy(pdi.GetCells().GetData()) # padd cells row_ends = np.concatenate((cell_locations, [len(cells)])) lens = np.diff(row_ends) max_len = np.max(lens) pad_len = np.max(lens) - lens where_to_pad = np.repeat(row_ends[1:], pad_len) padding_value = -1.0 padded_cells = np.insert(cells, where_to_pad, -1).reshape(-1, max_len) selected_cells = padded_cells[selection_ids] points = selected_cells[:, 1:].flatten() #points=points[points!=-1] np.set_printoptions(threshold=np.nan)
def vtkDataArrayToVTKArray(array, dataset=None): "Given a vtkDataArray and a dataset owning it, returns a VTKArray." narray = numpy_support.vtk_to_numpy(array) # Make arrays of 9 components into matrices. Also transpose # as VTK store matrices in Fortran order shape = narray.shape if len(shape) == 2 and shape[1] == 9: narray = narray.reshape((shape[0], 3, 3)).transpose(0, 2, 1) return VTKArray(narray, array=array, dataset=dataset)
def test_data_conainter_with_tuple_values(self): # given accumulator = CUBADataAccumulator() # when accumulator.append(DataContainer(VELOCITY=(0.1, 0.2, 0.3))) # then self.assertEqual(len(accumulator), 1) self.assertEqual(accumulator.keys, set([CUBA.VELOCITY])) assert_array_equal( vtk_to_numpy(accumulator[CUBA.VELOCITY]), [(0.1, 0.2, 0.3)])
def test_accumulate_and_expand(self): # given accumulator = CUBADataAccumulator() # when accumulator.append(create_data_container(restrict=[CUBA.MASS])) # then self.assertEqual(len(accumulator), 1) # when accumulator.append( create_data_container(restrict=[CUBA.NAME, CUBA.TEMPERATURE])) # then self.assertEqual(len(accumulator), 2) self.assertEqual(accumulator.keys, set([CUBA.MASS, CUBA.TEMPERATURE])) assert_array_equal( vtk_to_numpy(accumulator[CUBA.TEMPERATURE]), [numpy.nan, dummy_cuba_value(CUBA.TEMPERATURE)]) assert_array_equal( vtk_to_numpy(accumulator[CUBA.MASS]), [dummy_cuba_value(CUBA.MASS), numpy.nan])
def test_accumulate(self): # given cuds_data = [create_data_container(constant=i) for i in range(10)] # when accumulator = CUBADataAccumulator() for data in cuds_data: accumulator.append(data) # then self.assertEqual(len(accumulator), 10) expected_cuba = set(CUBA) & supported_cuba() self.assertEqual(accumulator.keys, expected_cuba) for cuba in expected_cuba: default = dummy_cuba_value(cuba) if isinstance(default, numpy.ndarray): new_shape = (10,) + default.shape assert_array_equal( vtk_to_numpy(accumulator[cuba]).reshape(new_shape), [dummy_cuba_value(cuba, constant=i) for i in range(10)]) else: assert_array_equal( vtk_to_numpy(accumulator[cuba]), [dummy_cuba_value(cuba, constant=i) for i in range(10)])
def test_source_from_a_xy_plane_hexagonal_lattice(self): # given lattice = make_hexagonal_lattice('test', 0.1, 0.2, (5, 4, 1)) self.add_velocity(lattice) # when data_set = cuds2vtk(cuds=lattice) # then self.assertEqual(data_set.GetNumberOfPoints(), 5 * 4) points = vtk_to_numpy(data_set.GetPoints().GetData()) for node in lattice.iter(item_type=CUBA.NODE): position = lattice.get_coordinate(node.index) point_id = data_set.FindPoint(position) assert_array_equal( points[point_id], numpy.asarray(position, dtype=points.dtype))
def test_accumulate_with_missing_values(self): # given accumulator = CUBADataAccumulator() # when accumulator.append(DataContainer()) # then self.assertEqual(len(accumulator), 1) # when accumulator.append( create_data_container( restrict=[CUBA.NAME, CUBA.TEMPERATURE], constant=7)) # then self.assertEqual(len(accumulator), 2) self.assertEqual(accumulator.keys, set([CUBA.TEMPERATURE])) array = vtk_to_numpy(accumulator[CUBA.TEMPERATURE]) assert_array_equal( array, [numpy.nan, dummy_cuba_value(CUBA.TEMPERATURE, constant=7)])
def test_accumulate_on_keys(self): # given cuds_data = [create_data_container(constant=i) for i in range(10)] # when accumulator = CUBADataAccumulator(keys=[CUBA.NAME, CUBA.TEMPERATURE]) # then self.assertEqual(len(accumulator), 0) self.assertEqual(accumulator.keys, set([CUBA.TEMPERATURE])) # when for data in cuds_data: accumulator.append(data) # then self.assertEqual(len(accumulator), 10) self.assertEqual(accumulator.keys, set([CUBA.TEMPERATURE])) assert_array_equal( vtk_to_numpy(accumulator[CUBA.TEMPERATURE]), [dummy_cuba_value( CUBA.TEMPERATURE, constant=i) for i in range(10)])
def test_source_from_a_cubic_lattice(self): # given lattice = make_cubic_lattice('test', 0.4, (14, 24, 34), (4, 5, 6)) self.add_velocity(lattice) # when data_set = cuds2vtk(cuds=lattice) # then self.assertEqual(data_set.GetNumberOfPoints(), 14 * 24 * 34) assert_array_equal(data_set.GetOrigin(), (4.0, 5.0, 6.0)) point_data = data_set.GetPointData() arrays = { point_data.GetArray(index).GetName(): vtk_to_numpy(point_data.GetArray(index)) for index in range(point_data.GetNumberOfArrays())} for node in lattice.iter(item_type=CUBA.NODE): point_id = data_set.ComputePointId(node.index) assert_array_equal( lattice.get_coordinate(node.index), data_set.GetPoint(point_id)) for key, value in node.data.iteritems(): assert_array_equal(arrays[key.name][point_id], value)
def exwssCs(self, clip): if clip is False: from math import tan, pi ExtractBlock1 = ExtractBlock() moblock = {'4': 1, '5': 2, '6': 2, '7': 1, '9': 1} ExtractBlock1.BlockIndices = [moblock['%d' % self.dataset]] self.sledge() WSS = {} points = {'4': [25, 45, 75], '5': [20, 45, 70], '6': [-17.1, -42.5, -65], '7': [14.5, 36.1, 62], '9': [14.2, 35.8, 64]} angles = {'4': [13, 0.008], '5': [35, 0.003], '6': [41, 0.008], '7': [36, 0.015], '9': [27, 0.05]} from paraview import numpy_support as ns Sli = FindSource('Slice1') featureEdges1 = FindSource('FeatureEdges1') for i in range(3): if i == 2: Sli.SliceType.Origin = [points['%d' % self.dataset][2]*0.001, # NOQa -angles['%d' % self.dataset][1], 0] if self.dataset == 6: Sli.SliceType.Normal = [1, tan(float( angles['%d' % self.dataset][0])/50*pi/2), 0] else: Sli.SliceType.Normal = [1, -tan(float( angles['%d' % self.dataset][0])/50*pi/2), 0] else: Sli.SliceType.Origin = [points['%d' % self.dataset][i]*0.001, 0, 0] # NOQA fedge = servermanager.Fetch(featureEdges1) rfedge = fedge.GetBlock(0) WSS['%d' % i] = [] WSS['%d' % i].append(ns.vtk_to_numpy( rfedge.GetPointData().GetArray('wall_shear'))) WSS['%d' % i].append(ns.vtk_to_numpy(rfedge.GetPointData().GetArray('y_coordinate'))) # NOQA WSS['%d' % i].append(ns.vtk_to_numpy(rfedge.GetPointData().GetArray('z_coordinate'))) # NOQA elif clip is True: from math import tan, pi self.clipper('+', False, True, True) self.sledge() WSS = {} points = {'4': [13.8, 34.9, 75], '5': [15.44, 38.5, 70], '6': [17.1, 42.5, 65], '7': [14.5, 36.1, 62], '9': [14.2, 35.8, 64]} angles = {'4': [13, 0.008], '5': [35, 0.003], '6': [41, 0.008], '7': [36, 0.015], '9': [27, 0.05]} from paraview import numpy_support as ns Sli = FindSource('Slice1') featureEdges1 = FindSource('FeatureEdges1') for i in range(2): self.clipper('+', True, False, False) Sli.SliceType.Origin = [points['%d' % self.dataset][i]*0.001, 0, 0] # NOQA fedge = servermanager.Fetch(featureEdges1) rfedge = fedge.GetBlock(0) WSS['%dleft' % i] = [] WSS['%dleft' % i].append(ns.vtk_to_numpy( rfedge.GetPointData().GetArray('wall_shear'))) WSS['%dleft' % i].append(ns.vtk_to_numpy(rfedge.GetPointData().GetArray('y_coordinate'))) # NOQA WSS['%dleft' % i].append(ns.vtk_to_numpy(rfedge.GetPointData().GetArray('z_coordinate'))) # NOQA self.clipper('-', True, False, False) featureEdges1 = FindSource('FeatureEdges1') fedge = servermanager.Fetch(featureEdges1) rfedge = fedge.GetBlock(0) WSS['%dright' % i] = [] WSS['%dright' % i].append(ns.vtk_to_numpy(rfedge.GetPointData().GetArray('wall_shear'))) # NOQA WSS['%dright' % i].append(ns.vtk_to_numpy(rfedge.GetPointData().GetArray('y_coordinate'))) # NOQA WSS['%dright' % i].append(ns.vtk_to_numpy(rfedge.GetPointData().GetArray('z_coordinate'))) # NOQA integrateVariables2 = FindSource('integrateVariables2') # destroy integrateVariables2 Delete(integrateVariables2) del integrateVariables2 # destroy featureEdges1 Delete(featureEdges1) del featureEdges1 integrateVariables1 = FindSource('IntegrateVariables1') # destroy integrateVariables1 Delete(integrateVariables1) del integrateVariables1 slice1 = FindSource('Slice1') # destroy slice1 Delete(slice1) del slice1 clip1 = FindSource('Clip1') # destroy clip1 Delete(clip1) del clip1 # find source nCencas = FindSource('NC0%d.encas' % self.dataset) # set active source SetActiveSource(nCencas) extractBlock1 = FindSource('ExtractBlock1') # destroy extractBlock1 Delete(extractBlock1) del extractBlock1 sledge() Sli = FindSource('Slice1') featureEdges1 = FindSource('FeatureEdges1') Sli.SliceType.Origin = [points['%d' % self.dataset][2]*0.001, -angles['%d' % self.dataset][1], 0] Sli.SliceType.Normal = [1, -tan(float( angles['%d' % self.dataset][0])/50*pi/2), 0] fedge = servermanager.Fetch(featureEdges1) rfedge = fedge.GetBlock(0) WSS['2'] = [] WSS['2'].append(ns.vtk_to_numpy( rfedge.GetPointData().GetArray('wall_shear'))) WSS['2'].append(ns.vtk_to_numpy(rfedge.GetPointData().GetArray('y_coordinate'))) # NOQA WSS['2'].append(ns.vtk_to_numpy(rfedge.GetPointData().GetArray('z_coordinate'))) # NOQA return(WSS)
def exnp(self): '''Extract data for nasopharynx''' data = self.data model = 'NC0%d' % self.model ldat = self.ldat from paraview import numpy_support as ns from math import tan, pi # set origins cons = { 'NC04': 0.065, 'NC04C': 0.01, 'NC04H': -0.008, 'NC05': 0.065, 'NC05C': 0.005, 'NC05H': -0.003, 'NC06': 0.06, 'NC06C': 0.005, 'NC06H': -0.008, 'NC07': 0.062, 'NC07C': 0, 'NC07H': -0.015, 'NC09': 0.064, 'NC09C': 0, 'NC09H': -0.05 } Sli = FindSource("Slice1") Integra = FindSource("IntegrateVariables1") Int = FindSource("IntegrateVariables2") SetActiveSource(Sli) if model == 'NC06': Sli.SliceType.Origin = [ -cons[model] - cons[model + 'C'], cons[model + 'H'], 0 ] # NOQA else: Sli.SliceType.Origin = [ cons[model] + cons[model + 'C'], cons[model + 'H'], 0 ] # NOQA # iterate over nasopharynx resp = self.res / 4 for x in range(resp): if model == 'NC06': Sli.SliceType.Normal = [-1, -tan(pi * x / (2 * resp)), 0] else: Sli.SliceType.Normal = [1, -tan(pi * x / (2 * resp)), 0] intData = servermanager.Fetch(Integra) if model == 'NC09': self.inf['X'].append(cons[model] * 1000 - x * cons[model + 'H'] * pi * 0.05 / resp * 1000) else: self.inf['X'].append(cons[model] * 1000 - x * cons[model + 'H'] * pi * 0.5 / resp * 1000) self.inf['Area'].append( ns.vtk_to_numpy(intData.GetCellData().GetArray('Area'))[0]) for i in data: self.inf[i].append( ns.vtk_to_numpy(intData.GetPointData().GetArray(i))[0]) InDat = servermanager.Fetch(Int) self.inf['Len'].append( ns.vtk_to_numpy( InDat.GetCellData().GetArray('Length'))[0]) # NOQA for i in ldat: self.inf[i].append( ns.vtk_to_numpy(InDat.GetCellData().GetArray(i))[0])
def eximg(self, res): model = self.dataset ExtractBlock1 = ExtractBlock() moblock = {'4': 1, '5': 2, '6': 2, '7': 1, '9': 1} ExtractBlock1.BlockIndices = [moblock['%d' % model]] Sli = Slice(SliceType="Plane") Sli.SliceOffsetValues = [0.0] Sli.SliceType.Normal = [1, 0, 0] Sli.SliceType = "Plane" Sli = FindSource("Slice1") SetActiveSource(Sli) FeatureEdges() featureEdges1 = FindSource('FeatureEdges1') SetActiveSource(featureEdges1) featureEdges1.FeatureEdges = 0 featureEdges1.NonManifoldEdges = 0 Render() cons = { 'NC04': 0.08, 'NC04C': 0.01, 'NC04H': -0.008, 'NC05': 0.08, 'NC05C': 0.005, 'NC05H': -0.003, 'NC06': 0.08, 'NC06C': 0.005, 'NC06H': -0.008, 'NC07': 0.08, 'NC07C': 0, 'NC07H': -0.015, 'NC09': 0.08, 'NC09C': 0, 'NC09H': -0.05 } Sli = FindSource("Slice1") featureEdges1 = FindSource('FeatureEdges1') SetActiveSource(Sli) from paraview import numpy_support as ns img = {} img['X'] = [] img['Y'] = [] img['Z'] = [] model = 'NC0%d' % model for x in range(res): if model == 'NC06': Sli.SliceType.Origin = [ -x * cons[model] / res - cons[model + 'C'], 0, 0 ] else: Sli.SliceType.Origin = [ x * cons[model] / res + cons[model + 'C'], 0, 0 ] img['X'].append(x * cons[model] * 1000 / res) fedge = servermanager.Fetch(featureEdges1) rfedge = fedge.GetBlock(0) img['Y'].append( ns.vtk_to_numpy( rfedge.GetPointData().GetArray('y_coordinate'))) img['Z'].append( ns.vtk_to_numpy( rfedge.GetPointData().GetArray('z_coordinate'))) return img
def resample_to_2d_1d(pdi, pdi_frac, pdo, geom): # geom_types=ns.vtk_to_numpy(geom.GetCellTypesArray()) geom_locations=ns.vtk_to_numpy(geom.GetCellLocationsArray()) geom_2d_id=np.where(geom_types==VTK_TRIANGLE)[0] n_2d_cells=geom_2d_id.size #print geom_2d_id #geom_2d_locations=geom_locations[geom_2d_id] geom_1d_id=np.where(geom_types==VTK_LINE)[0] n_1d_cells=geom_1d_id.size #print geom_1d_id geom_1d_locations=geom_locations[geom_1d_id] # should check that there are both 2d and 1d elements other # similarly we should check that there are only triangles in the pdi # create a sampling dataset aux_dataset=vtk.vtkUnstructuredGrid() # compute centroids input_copy = geom.NewInstance() input_copy.UnRegister(None) input_copy.ShallowCopy(geom) geom_centers=vtk.vtkCellCenters() geom_centers.SetInputData(geom) geom_centers.Update() output=geom_centers.GetOutput() barycenters=ns.vtk_to_numpy(output.GetPoints().GetData()).reshape(-1,3) barycenters_2d=barycenters[geom_2d_id] #print barycenters_2d # shift right half of points barycenters_2d[:,0]=np.where(barycenters_2d[:,0]<0, barycenters_2d[:,0]-X_SHIFT_LEFT, barycenters_2d[:,0]+X_SHIFT_RIGHT) # compute 1d avarage points cell_data=ns.vtk_to_numpy(geom.GetCells().GetData()) grid = np.meshgrid( [0,1,2], geom_1d_locations ) grid = map(np.ravel, grid) cell_data_selection=grid[0]+grid[1] array_of_1d_cells=(cell_data[cell_data_selection]) assert(len(array_of_1d_cells)>0) geom_points_y=ns.vtk_to_numpy(geom.GetPoints().GetData())[:,1] x_points=np.array((0)) y_points=np.array((0)) # trapezoid rule """ def weights(N): return np.array([0.5] + (N-2)*[1.0] + [0.5]) average_weights=np.outer( weights(AVERAGE_POINTS_X), weights(AVERAGE_POINTS_Y)).flatten() # reference grid x=np.linspace(-X_SHIFT_LEFT, X_SHIFT_RIGHT, AVERAGE_POINTS_X) y=np.linspace(0,1,AVERAGE_POINTS_Y) """ def weights(N): # trapezoidal weights return np.array([0.5] + (N-2)*[1.0] + [0.5]) # midpoint rule in both directions (avoid problems at boundary) average_weights=np.outer( np.ones(AVERAGE_POINTS_Y), np.ones(AVERAGE_POINTS_X) ).flatten() # reference grid N=float(AVERAGE_POINTS_X) dx=(X_SHIFT_RIGHT + X_SHIFT_LEFT)/N x=np.linspace(-X_SHIFT_LEFT+dx/2, X_SHIFT_RIGHT-dx/2,N) N=float(AVERAGE_POINTS_Y) y=np.linspace(1/(2*N),1-1/(2*N),N) #print "weights: ", average_weights #print "y: ", y ref_x, ref_y=map(np.ravel, np.meshgrid(x,y)) #print "y: ", ref_y #print "x: ", ref_x assert( np.all(array_of_1d_cells[0::3]==2) ) p0=geom_points_y[array_of_1d_cells[1::3]] p1=geom_points_y[array_of_1d_cells[2::3]] x_points=np.tile(ref_x, geom_1d_id.size) yy,y0=np.meshgrid(ref_y,p0) yy,y1=np.meshgrid(ref_y,p1) y_points=(y0*yy+y1*(1-yy)).ravel() #print average_weights.size, x_points.size, y_points.size assert(x_points.size==y_points.size) assert(AVERAGE_POINTS_X*AVERAGE_POINTS_Y==average_weights.size) z_points=np.zeros(len(x_points)) points_1d=np.hstack(( x_points.reshape((-1,1)), y_points.reshape((-1,1)), z_points.reshape((-1,1)) )) #print points_1d barycenters_2d.shape=(-1,3) points_1d.shape=(-1,3) #all_points=append(barycenters_2d, points_1d) #all_points.shape=(-1,3) # make a dataset # probe on fracture dataset points_f=vtk.vtkPoints() points_f.SetData(ns.numpy_to_vtk(points_1d, deep=1)) point_set_f=vtk.vtkUnstructuredGrid() point_set_f.SetPoints(points_f) probe_f=vtk.vtkProbeFilter() probe_f.SetSourceData(pdi_frac) probe_f.SetInputData(point_set_f) probe_f.Update() out_f=probe_f.GetOutput() probe_data_f=out_f.GetPointData() # probe on continuum dataset points=vtk.vtkPoints() points.SetData(ns.numpy_to_vtk(barycenters_2d, deep=1)) point_set=vtk.vtkUnstructuredGrid() point_set.SetPoints(points) probe=vtk.vtkProbeFilter() probe.SetSourceData(pdi) probe.SetInputData(point_set) probe.Update() out=probe.GetOutput() probe_data=out.GetPointData() # reconstruct element arrays pdo.DeepCopy(geometry) cell_data=pdo.GetCellData() for i_array in range(cell_data.GetNumberOfArrays()): cell_data.RemoveArray(i_array) point_data=pdo.GetPointData() for i_array in range(point_data.GetNumberOfArrays()): point_data.RemoveArray(i_array) assert(probe_data.GetNumberOfArrays() == probe_data_f.GetNumberOfArrays() ) for i_array in range(probe_data.GetNumberOfArrays()): vtk_array=probe_data.GetArray(i_array) array=ns.vtk_to_numpy(vtk_array) n_components=vtk_array.GetNumberOfComponents() n_tuples=vtk_array.GetNumberOfTuples() assert(n_tuples == n_2d_cells) array.shape=(n_tuples,n_components) vtk_array_f=probe_data_f.GetArray(i_array) array_f=ns.vtk_to_numpy(vtk_array_f) n_components_f=vtk_array_f.GetNumberOfComponents() n_tuples_f=vtk_array_f.GetNumberOfTuples() assert(n_components == n_components_f) assert( n_1d_cells*len(average_weights) == n_tuples_f) assert( array.dtype == array_f.dtype) array_f.shape=(n_1d_cells, len(average_weights), n_components) #print vtk_array.GetName() #print array_f.shape #print array_f new_array=np.zeros((pdo.GetNumberOfCells(),n_components), dtype=array.dtype) new_array[geom_2d_id,:]=array new_array[geom_1d_id,:]=np.average(array_f, weights=average_weights, axis=1) new_vtk_array=ns.numpy_to_vtk(new_array, deep=1) new_vtk_array.SetName(vtk_array.GetName()) cell_data.AddArray(new_vtk_array) #ids=ns.numpy_to_vtk(np.arange(n_2d_cells+n_1d_cells), deep=1) #ids.SetName('ids') #cell_data.AddArray(ids) '''
def exdat(self): from paraview import numpy_support as ns # Define relevant constants self.clipper() self.sledge() data = self.data model = 'NC0%d' % self.model ldat = self.ldat res = self.res dic = {'X': [], 'Area': [], 'Len': []} for i in data: dic[i] = [] for i in ldat: dic[i] = [] cons = { 'NC04': 0.065, 'NC04C': 0.01, 'NC04H': -0.008, 'NC05': 0.065, 'NC05C': 0.005, 'NC05H': -0.003, 'NC06': 0.06, 'NC06C': 0.005, 'NC06H': -0.008, 'NC07': 0.062, 'NC07C': 0, 'NC07H': -0.015, 'NC09': 0.064, 'NC09C': 0, 'NC09H': -0.05 } Sli = FindSource("Slice1") Integra = FindSource("IntegrateVariables1") Int = FindSource("IntegrateVariables2") SetActiveSource(Sli) # Extract data for main cavity for x in range(res): if model == 'NC06': Sli.SliceType.Origin = [ -x * cons[model] / res - cons[model + 'C'], 0, 0 ] else: Sli.SliceType.Origin = [ x * cons[model] / res + cons[model + 'C'], 0, 0 ] dic['X'].append(x * cons[model] * 1000 / res) intData = servermanager.Fetch(Integra) dic['Area'].append( ns.vtk_to_numpy( intData.GetCellData().GetArray('Area'))[0]) # NOQA for i in data: dic[i].append( ns.vtk_to_numpy( intData.GetPointData().GetArray(i))[0]) # NOQA InDat = servermanager.Fetch(Int) dic['Len'].append( ns.vtk_to_numpy( InDat.GetCellData().GetArray('Length'))[0]) # NOQA for i in ldat: dic[i].append( ns.vtk_to_numpy( InDat.GetPointData().GetArray(i))[0]) # NOQA self.inf = dic if 'y' == self.ext: self.exnp()
def insert(self, document): """overridden to use paraview to generate an image and create a the document for it""" if not self.view: return if self.CaptureDepth: # Depth capture simple.Render() image = self.view.CaptureDepthBuffer() idata = numpy_support.vtk_to_numpy(image) * 256 rw = self.view.GetRenderWindow() width, height = rw.GetSize() try: imageslice = idata.reshape(height, width) except ValueError: imageslice = None document.data = imageslice self.CaptureDepth = False #printView(self.view) else: imageslice = None if self.CaptureLuminance: if self.UsingGL2: # TODO: needs a fix for luminance pass imageslice = self.captureWindowRGB() else: # GL1 support try: rep = simple.GetRepresentation() if rep != None: rep.DiffuseColor = [1, 1, 1] rep.ColorArrayName = None except ValueError: pass idata, width, height = self.captureWindowAsNumpy() idata = self.rgb2grey(idata, height, width) imageslice = np.dstack((idata, idata, idata)) document.data = imageslice elif self.CaptureValues: # Value capture if self.ValueMode is ValueMode().INVERTIBLE_LUT: imageslice = self.captureWindowRGB() elif self.ValueMode is ValueMode().FLOATING_POINT: simple.Render() image = self.view.GetValuesFloat() idata = numpy_support.vtk_to_numpy(image) idataMin = idata.min() if len(idata) > 0 else 0 idataMax = idata.max() if len(idata) > 0 else 0 self.updateRange(self.view.ArrayNameToDraw, self.view.ArrayComponentToDraw, [idataMin, idataMax]) rw = self.view.GetRenderWindow() width, height = rw.GetSize() try: imageslice = idata.reshape(height, width) except ValueError: imageslice = None document.data = imageslice else: # Capture color image imageslice = self.captureWindowRGB() document.data = imageslice if self.iSave: super(ImageExplorer, self).insert(document)
""" Paraview ProgrammableFilter. This filter assumes a variable 'filter_parameters' that is dictionary containing key 'region_id_to_extract'. The cells where dataset 'region_id' is equal to provided value are extracted. Example: parameters={ "dimension_to_extract" : 2 } ProgrammableFilter(Input=data_in, Script="filter_parameters="+str(parameters)+"\n"+this_file) """ import submesh import numpy as np import paraview.numpy_support as ns pdi = self.GetPolyDataInput() pdo = self.GetOutput() region_id = filter_parameters["region_id_to_extract"] region_id_array = ns.vtk_to_numpy(pdi.GetCellData().GetArray("region_id")) cell_list = np.where(abs(region_id_array - region_id) < 0.5)[0] submesh.submesh(pdi, pdo, cell_list)
""" Paraview ProgrammableFilter. This filter assumes a variable 'filter_parameters' that is dictionary conatining key 'dimension_to_extract' with dimension of simplices to extract (allowed values are 0,1,2,3). Example: parameters={ "dimension_to_extract" : 2 } ProgrammableFilter(Input=data_in, Script="filter_parameters="+str(parameters)+"\n"+this_file) """ import submesh import numpy as np import paraview.numpy_support as ns pdi = self.GetPolyDataInput() pdo = self.GetOutput() dimension = filter_parameters["dimension_to_extract"] type_to_extract = submesh.type_for_dimension[dimension] cell_types = ns.vtk_to_numpy(pdi.GetCellTypesArray()) cell_list = np.where(cell_types == type_to_extract)[0] submesh.submesh(pdi, pdo, cell_list)
def test_with_cuds_particles(self): # given points = [ [0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]] bonds = [[0, 1], [0, 3], [1, 3, 2]] point_temperature = [10., 20., 30., 40.] bond_temperature = [60., 80., 190.] cuds = Particles('test') particle_uids = cuds.add( Particle( coordinates=point, data=DataContainer( TEMPERATURE=point_temperature[index], MASS=index)) for index, point in enumerate(points)) cuds.add( Bond( particles=[particle_uids[uid] for uid in indices], data=DataContainer( TEMPERATURE=bond_temperature[index], MASS=index)) for index, indices in enumerate(bonds)) # when data_set = cuds2vtk(cuds) # then check points self.assertEqual(data_set.GetNumberOfPoints(), 4) coordinates = [ particle.coordinates for particle in cuds.iter( item_type=CUBA.PARTICLE)] vtk_points = [ data_set.GetPoint(index) for index in range(len(particle_uids))] self.assertItemsEqual(vtk_points, coordinates) point_data = data_set.GetPointData() self.assertEqual(point_data.GetNumberOfArrays(), 2) arrays = { point_data.GetArray(index).GetName(): point_data.GetArray(index) for index in range(2)} self.assertItemsEqual(arrays.keys(), ['MASS', 'TEMPERATURE']) mass = vtk_to_numpy(arrays['MASS']) self.assertItemsEqual(mass, range(4)) assert_array_equal( vtk_to_numpy(arrays['TEMPERATURE']), [point_temperature[int(index)] for index in mass]) # then check bonds self.assertEqual(data_set.GetNumberOfCells(), 3) links = [[ particle.coordinates for particle in cuds.iter(bond.particles)] for bond in cuds.iter(item_type=CUBA.BOND)] vtk_lines = data_set.GetLines() lines = [[ data_set.GetPoint(index) for index in line] for line in iter_cells(vtk_lines)] self.assertItemsEqual(lines, links) cell_data = data_set.GetCellData() self.assertEqual(cell_data.GetNumberOfArrays(), 2) arrays = { cell_data.GetArray(index).GetName(): cell_data.GetArray(index) for index in range(2)} self.assertItemsEqual(arrays.keys(), ['MASS', 'TEMPERATURE']) mass = vtk_to_numpy(arrays['MASS']) self.assertItemsEqual(mass, range(3)) assert_array_equal( vtk_to_numpy(arrays['TEMPERATURE']), [bond_temperature[int(index)] for index in mass])
def test_with_cuds_mesh(self): # given points = numpy.array([ [0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1], [2, 0, 0], [3, 0, 0], [3, 1, 0], [2, 1, 0], [2, 0, 1], [3, 0, 1], [3, 1, 1], [2, 1, 1]], 'f') cells = [ [0, 1, 2, 3], # tetra [4, 5, 6, 7, 8, 9, 10, 11]] # hex faces = [[2, 7, 11]] edges = [[1, 4], [3, 8]] count = itertools.count() points = [ Point(coordinates=point, data=DataContainer(TEMPERATURE=index)) for index, point in enumerate(points)] cuds = Mesh('test') cuds.add(points) faces = [ Face( points=[points[index].uid for index in face], data=DataContainer(TEMPERATURE=next(count))) for face in faces] edges = [ Edge( points=[points[index].uid for index in edge], data=DataContainer(TEMPERATURE=next(count))) for edge in edges] cells = [ Cell( points=[points[index].uid for index in cell], data=DataContainer(TEMPERATURE=next(count))) for cell in cells] cuds.add(edges) cuds.add(faces) cuds.add(cells) # when data_set = cuds2vtk(cuds=cuds) # then check points self.assertEqual(data_set.GetNumberOfPoints(), 12) point_data = data_set.GetPointData() self.assertEqual(point_data.GetNumberOfArrays(), 1) temperature = point_data.GetArray(0) self.assertEqual(temperature.GetName(), 'TEMPERATURE') self.assertItemsEqual( vtk_to_numpy(temperature), range(12)) # then check cells self.assertEqual(data_set.GetNumberOfCells(), 5) cell_data = data_set.GetCellData() self.assertEqual(cell_data.GetNumberOfArrays(), 1) temperature = cell_data.GetArray(0) self.assertEqual(temperature.GetName(), 'TEMPERATURE') self.assertItemsEqual( vtk_to_numpy(temperature), range(5)) # For each cell in the container # find the corresponding cell in the vtkCellArray and # verify that they link to points that have the right coordinates. for cell in itertools.chain( cuds.iter(item_type=CUBA.EDGE), cuds.iter(item_type=CUBA.FACE), cuds.iter(item_type=CUBA.CELL)): # The temperature value is also the index that the cells # are expected to have in the vtkCellArray. value = cell.data[CUBA.TEMPERATURE] index = numpy.nonzero(vtk_to_numpy(temperature) == value)[0] vtk_cell = data_set.GetCell(index) ids = vtk_cell.GetPointIds() for i, uid in enumerate(cell.points): cell_point = cuds.get(uid) assert_array_equal( data_set.GetPoint(ids.GetId(i)), cell_point.coordinates)
ls_damp = filter_parameters["damp"] def lsq(A, b, x0, btol=1e-6): r0 = b - A * x0 atol=btol*np.linalg.norm(r0) scaled_btol = btol*np.linalg.norm(b)/np.linalg.norm(r0) result=lsqr(A, r0, damp=ls_damp, iter_lim=100, show=True, atol=atol, btol=scaled_btol) return (x0 + result[0]) pdi = self.GetPolyDataInput() pdo = self.GetOutput() cell_locations=ns.vtk_to_numpy(pdi.GetCellLocationsArray()) cell_node_ids_vtk=np.copy(ns.vtk_to_numpy(pdi.GetCells().GetData())) n_elements=pdi.GetNumberOfCells() n_nodes=pdi.GetNumberOfPoints() assert(n_elements == len(cell_locations)) # sparse matrix for PointData -> CellData interpolation (averages of nodal values) row_starts = np.append(cell_locations, len(cell_node_ids_vtk)) nodes_per_cell_vtk = row_starts[1:] - row_starts[0:-1] # remove cell sizes nodes_per_cell=nodes_per_cell_vtk - 1 row_starts = np.cumsum(np.insert(nodes_per_cell,0,0)) cell_node_ids_vtk[cell_locations]=-1 cell_node_ids=cell_node_ids_vtk[cell_node_ids_vtk!=-1]
def exdat(self): from paraview import numpy_support as ns # Define relevant constants self.clipper() self.sledge() data = self.data model = 'NC0%d' % self.model ldat = self.ldat res = self.res dic = {'X': [], 'Area': [], 'Len': []} for i in data: dic[i] = [] for i in ldat: dic[i] = [] cons = {'NC04': 0.065, 'NC04C': 0.01, 'NC04H': -0.008, 'NC05': 0.065, 'NC05C': 0.005, 'NC05H': -0.003, 'NC06': 0.06, 'NC06C': 0.005, 'NC06H': -0.008, 'NC07': 0.062, 'NC07C': 0, 'NC07H': -0.015, 'NC09': 0.064, 'NC09C': 0, 'NC09H': -0.05} Sli = FindSource("Slice1") Integra = FindSource("IntegrateVariables1") Int = FindSource("IntegrateVariables2") SetActiveSource(Sli) # Extract data for main cavity for x in range(res): if model == 'NC06': Sli.SliceType.Origin = [ -x*cons[model]/res - cons[model+'C'], 0, 0] else: Sli.SliceType.Origin = [ x*cons[model]/res + cons[model+'C'], 0, 0] dic['X'].append(x*cons[model]*1000/res) intData = servermanager.Fetch(Integra) dic['Area'].append(ns.vtk_to_numpy(intData.GetCellData().GetArray('Area'))[0]) # NOQA for i in data: dic[i].append(ns.vtk_to_numpy(intData.GetPointData().GetArray(i))[0]) # NOQA InDat = servermanager.Fetch(Int) dic['Len'].append(ns.vtk_to_numpy(InDat.GetCellData().GetArray('Length'))[0]) # NOQA for i in ldat: dic[i].append(ns.vtk_to_numpy(InDat.GetPointData().GetArray(i))[0]) # NOQA self.inf = dic if 'y' == self.ext: self.exnp()
def eximg(self, res): model = self.dataset ExtractBlock1 = ExtractBlock() moblock = {'4': 1, '5': 2, '6': 2, '7': 1, '9': 1} ExtractBlock1.BlockIndices = [moblock['%d' % model]] Sli = Slice(SliceType="Plane") Sli.SliceOffsetValues = [0.0] Sli.SliceType.Normal = [1, 0, 0] Sli.SliceType = "Plane" Sli = FindSource("Slice1") SetActiveSource(Sli) FeatureEdges() featureEdges1 = FindSource('FeatureEdges1') SetActiveSource(featureEdges1) featureEdges1.FeatureEdges = 0 featureEdges1.NonManifoldEdges = 0 Render() cons = {'NC04': 0.08, 'NC04C': 0.01, 'NC04H': -0.008, 'NC05': 0.08, 'NC05C': 0.005, 'NC05H': -0.003, 'NC06': 0.08, 'NC06C': 0.005, 'NC06H': -0.008, 'NC07': 0.08, 'NC07C': 0, 'NC07H': -0.015, 'NC09': 0.08, 'NC09C': 0, 'NC09H': -0.05} Sli = FindSource("Slice1") featureEdges1 = FindSource('FeatureEdges1') SetActiveSource(Sli) from paraview import numpy_support as ns img = {} img['X'] = [] img['Y'] = [] img['Z'] = [] model = 'NC0%d' % model for x in range(res): if model == 'NC06': Sli.SliceType.Origin = [ -x*cons[model]/res - cons[model+'C'], 0, 0] else: Sli.SliceType.Origin = [ x*cons[model]/res + cons[model+'C'], 0, 0] img['X'].append(x*cons[model]*1000/res) fedge = servermanager.Fetch(featureEdges1) rfedge = fedge.GetBlock(0) img['Y'].append(ns.vtk_to_numpy( rfedge.GetPointData().GetArray('y_coordinate'))) img['Z'].append( ns.vtk_to_numpy(rfedge.GetPointData() .GetArray('z_coordinate'))) return img
atol = btol * np.linalg.norm(r0) scaled_btol = btol * np.linalg.norm(b) / np.linalg.norm(r0) result = lsqr(A, r0, damp=ls_damp, iter_lim=100, show=True, atol=atol, btol=scaled_btol) return (x0 + result[0]) pdi = self.GetPolyDataInput() pdo = self.GetOutput() cell_locations = ns.vtk_to_numpy(pdi.GetCellLocationsArray()) cell_node_ids_vtk = np.copy(ns.vtk_to_numpy(pdi.GetCells().GetData())) n_elements = pdi.GetNumberOfCells() n_nodes = pdi.GetNumberOfPoints() assert (n_elements == len(cell_locations)) # sparse matrix for PointData -> CellData interpolation (averages of nodal values) row_starts = np.append(cell_locations, len(cell_node_ids_vtk)) nodes_per_cell_vtk = row_starts[1:] - row_starts[0:-1] # remove cell sizes nodes_per_cell = nodes_per_cell_vtk - 1 row_starts = np.cumsum(np.insert(nodes_per_cell, 0, 0)) cell_node_ids_vtk[cell_locations] = -1 cell_node_ids = cell_node_ids_vtk[cell_node_ids_vtk != -1]
def WriteMPASImages(datadescription, timestep): global LookupTable1, ScalarBar1, RenderView1 global BasicRep global HeadingRep, RightSideRep, LeftSideRep, TimeRep, DateRep global Calculator1, Threshold1, ThresholdRep grid = datadescription.GetInputDescriptionByName(gridname).GetGrid() for view in servermanager.GetRenderViews(): if (timestep % view.cpFrequency == 0 or datadescription.GetForceOutput() == True): for varTuple in variable_action: varName = varTuple[0] fileName = varTuple[1] if use_layer: layer = varTuple[2] HeadingRep.Visibility = 0 RightSideRep.Visibility = 0 LeftSideRep.Visibility = 0 TimeRep.Visibility = 0 DateRep.Visibility = 0 # Output file name fileName = fileName.replace('%t', str(timestep)) if use_layer: fileName = fileName.replace('%l', str(layer)) ScalarBar1.Title = varName # Scalar range for colormap # need to mask out land values. first convert to a numpy array, mask # the values, and find the min and max of the remaining values data = numpy_support.vtk_to_numpy(grid.GetCellData().GetArray(varName)) data = numpy.ma.masked_equal(data, -1e34) mins = data.min(axis=0) maxes = data.max(axis=0) if use_layer: minval = mins[layer] maxval = maxes[layer] LookupTable1.VectorMode = 'Component' LookupTable1.VectorComponent = layer ScalarBar1.ComponentTitle = str(layer) else: minval = mins maxval = maxes # find the global min and max by doing an mpi allreduce comm = mpi4py.MPI.COMM_WORLD sendbuf = numpy.array(minval, 'f') rcvbuf = numpy.array(0.0, 'f') comm.Allreduce([sendbuf, MPI.FLOAT], [rcvbuf, MPI.FLOAT], op=MPI.MIN) minval = rcvbuf sendbuf = numpy.array(maxval, 'f') rcvbuf = numpy.array(0.0, 'f') comm.Allreduce([sendbuf, MPI.FLOAT], [rcvbuf, MPI.FLOAT], op=MPI.MAX) maxval = rcvbuf # set the scalar bar range to the global min and max LookupTable1.RGBPoints=[minval, 0.23, 0.299, 0.754, (minval+maxval)/2.0, 0.865, 0.865, 0.865, maxval, 0.706, 0.016, 0.15] # if using layers, update the threshold to remove the land cells if use_layer: # set color bar title here array_name = '%s_%i' % (varName, layer) Calculator1.Function = array_name Calculator1.ResultArrayName = array_name BasicRep.Visibility = 0 ThresholdRep.Visibility = 1 ThresholdRep.ColorAttributeType = 'CELL_DATA' ThresholdRep.SelectionCellFieldDataArrayName = array_name ThresholdRep.ColorArrayName = ('CELL_DATA', array_name) else: BasicRep.ColorArrayName = varName if annotationShowHeading: HeadingRep.Visibility = 1 if annotationShowRightSide: RightSideRep.Visibility = 1 if annotationShowLeftSide: LeftSideRep.Visibility = 1 if annotationShowSimulationTime: TimeRep.Visibility = 1 if annotationShowDate: DateRep.Visibility = 1 # camera bounds view.SMProxy.ResetCamera() view.SMProxy.GetActiveCamera().Zoom(image_zoom) view.ViewTime = datadescription.GetTime() Render(view) WriteImage(fileName, view, Magnification=view.cpMagnification)
def resample_to_2d_1d(pdi, pdo, geom): # geom_types = ns.vtk_to_numpy(geom.GetCellTypesArray()) geom_locations = ns.vtk_to_numpy(geom.GetCellLocationsArray()) geom_2d_id = np.where(geom_types == VTK_TRIANGLE)[0] n_2d_cells = geom_2d_id.size #print geom_2d_id geom_2d_locations = geom_locations[geom_2d_id] geom_1d_id = np.where(geom_types == VTK_LINE)[0] n_1d_cells = geom_1d_id.size #print geom_1d_id geom_1d_locations = geom_locations[geom_1d_id] # should check that there are both 2d and 1d elements other # similarly we should check that there are only triangles in the pdi # create a sampling dataset aux_dataset = vtk.vtkUnstructuredGrid() # compute centroids input_copy = geom.NewInstance() input_copy.UnRegister(None) input_copy.ShallowCopy(geom) geom_centers = vtk.vtkCellCenters() geom_centers.SetInputData(geom) geom_centers.Update() output = geom_centers.GetOutput() barycenters = ns.vtk_to_numpy(output.GetPoints().GetData()).reshape(-1, 3) barycenters_2d = barycenters[geom_2d_id] #print barycenters_2d # shift right half of points barycenters_2d[:, 0] = np.where(barycenters_2d[:, 0] < 0, barycenters_2d[:, 0] + LEFT_SHIFT, barycenters_2d[:, 0] + RIGHT_SHIFT) # compute 1d avarage points cell_data = ns.vtk_to_numpy(geom.GetCells().GetData()) grid = np.meshgrid([0, 1, 2], geom_1d_locations) grid = map(np.ravel, grid) cell_data_selection = grid[0] + grid[1] array_of_1d_cells = (cell_data[cell_data_selection]) assert (len(array_of_1d_cells) > 0) geom_points_y = ns.vtk_to_numpy(geom.GetPoints().GetData())[:, 1] x_points = np.array((0)) y_points = np.array((0)) # reference grid x = np.linspace(LEFT_SHIFT, RIGHT_SHIFT, AVERAGE_POINTS) y = np.linspace(0, 1, AVERAGE_POINTS) ref_x, ref_y = map(np.ravel, np.meshgrid(x, y)) assert (np.all(array_of_1d_cells[0::3] == 2)) p0 = geom_points_y[array_of_1d_cells[1::3]] p1 = geom_points_y[array_of_1d_cells[2::3]] x_points = np.tile(ref_x, geom_1d_id.size) yy, y0 = np.meshgrid(ref_y, p0) yy, y1 = np.meshgrid(ref_y, p1) y_points = (y0 * yy + y1 * (1 - yy)).ravel() assert (x_points.size == y_points.size) z_points = np.zeros(len(x_points)) points_1d = np.hstack((x_points.reshape((-1, 1)), y_points.reshape( (-1, 1)), z_points.reshape((-1, 1)))) #print points_1d all_points = append(barycenters_2d, points_1d) all_points.shape = (-1, 3) # make a probe dataset points = vtk.vtkPoints() points.SetData(make_vtk_array(all_points, "points")) point_set = vtk.vtkUnstructuredGrid() point_set.SetPoints(points) probe = vtk.vtkProbeFilter() probe.SetSourceData(pdi) probe.SetInputData(point_set) probe.Update() out = probe.GetOutput() probe_data = out.GetPointData() # reconstruct element arrays pdo.DeepCopy(geometry) cell_data = pdo.GetCellData() for i_array in range(probe_data.GetNumberOfArrays()): # make interpolation array vtk_array = probe_data.GetArray(i_array) array_name = vtk_array.GetName() n_components = vtk_array.GetNumberOfComponents() n_tuples = vtk_array.GetNumberOfTuples() array = ns.vtk_to_numpy(vtk_array) array.shape = (n_tuples, n_components) new_array = np.zeros((pdo.GetNumberOfCells(), n_components), dtype=array.dtype) new_array[geom_2d_id, :] = array[0:n_2d_cells, :] array_1d = array[n_2d_cells:, :].reshape( n_1d_cells, AVERAGE_POINTS * AVERAGE_POINTS, n_components) new_array[geom_1d_id, :] = np.average(array_1d, axis=1) new_vtk_array = ns.numpy_to_vtk(new_array, deep=1) cell_data.AddArray( make_vtk_array(new_array, "interpol_" + vtk_array.GetName())) # compute difference array vtk_geometry_array = pdo.GetCellData().GetArray(array_name) if vtk_geometry_array: assert_eq(vtk_geometry_array.GetNumberOfComponents(), new_array.shape[1]) assert_eq(vtk_geometry_array.GetNumberOfTuples(), new_array.shape[0]) geometry_array = ns.vtk_to_numpy(vtk_geometry_array) geometry_array.shape = new_array.shape difference = geometry_array - new_array cell_data.AddArray( make_vtk_array(difference, "diff_" + vtk_array.GetName()))
def pvtu_file(file,variables,reader='none',returnreader=False): if os.path.isfile(file): pass tarfile = False elif os.path.isfile(file+'.tar.gz'): tarfile = True cwd = os.getcwd() os.chdir(os.path.dirname(file)) os.system('tar -xzf '+file+'.tar.gz') else: sys.exit("File "+file+" does not exist.") try: from paraview import numpy_support, simple # Load vtu file if reader == 'none': reader = simple.XMLPartitionedUnstructuredGridReader(FileName=file) reader.FileName = file vtudata = simple.servermanager.Fetch(reader) except: try: import vtk from vtk.util import numpy_support if reader == 'none': reader = vtk.vtkXMLPUnstructuredGridReader() reader.SetFileName(file) reader.Update() vtudata = reader.GetOutput() except: sys.exit("You do not have the necessary modules (vtk or paraview) to import vtu files.") # Get number of nodes n = vtudata.GetNumberOfPoints() # Set up output array varnames = ['Node Number','x','y','z'] types = [np.int64, np.float64, np.float64, np.float64] for var in variables: if var == 'velocity': opts = ['velocity 1','velocity 2','velocity 3','velocity'] for opt in opts: varnames.append(opt) types.append(np.float64) del opt, opts elif var == 'ssavelocity': opts = ['ssavelocity 1','ssavelocity 2','ssavelocity 3','ssavelocity'] for opt in opts: varnames.append(opt) types.append(np.float64) del opt, opts elif var.endswith('update'): opts = [var+' 1',var+' 2',var+' 3'] for opt in opts: varnames.append(opt) types.append(np.float64) elif var == 'vsurfini': opts = ['vsurfini 1','vsurfini 2','vsurfini'] for opt in opts: varnames.append(opt) types.append(np.float64) del opt, opts else: types.append(np.float64) varnames.append(var) if ('beta' in varnames) and (('velocity 1' in varnames) or ('ssavelocity 1' in varnames)): varnames.append('taub') types.append(np.float64) varnames.append('betasquared') types.append(np.float64) data = np.empty(n,dtype = zip(varnames, types)) # Get coordinates x = np.zeros(n) y = np.zeros(n) z = np.zeros(n) for i in range(0,n): x[i],y[i],z[i] = vtudata.GetPoint(i) data['x'][:] = x data['y'][:] = y data['z'][:] = z # Get variables for var in variables: if var == 'velocity': velocity = numpy_support.vtk_to_numpy(vtudata.GetPointData().GetArray(var)) data['velocity 1'] = velocity[:,0] data['velocity 2'] = velocity[:,1] data['velocity 3'] = velocity[:,2] data['velocity'] = np.sqrt(data['velocity 1']**2+data['velocity 2']**2) elif var == 'ssavelocity': ssavelocity = numpy_support.vtk_to_numpy(vtudata.GetPointData().GetArray(var)) data['ssavelocity 1'] = ssavelocity[:,0] data['ssavelocity 2'] = ssavelocity[:,1] data['ssavelocity 3'] = ssavelocity[:,2] data['ssavelocity'] = np.sqrt(data['ssavelocity 1']**2+data['ssavelocity 2']**2) elif var == 'vsurfini': try: vsurfini = numpy_support.vtk_to_numpy(vtudata.GetPointData().GetArray(var)) data['vsurfini 1'] = vsurfini[:,0] data['vsurfini 2'] = vsurfini[:,1] data['vsurfini'] = np.sqrt(data['vsurfini 1']**2+data['vsurfini 2']**2) except: try: data['vsurfini 1'] = numpy_support.vtk_to_numpy(vtudata.GetPointData().GetArray('vsurfini 1')) data['vsurfini 2'] = numpy_support.vtk_to_numpy(vtudata.GetPointData().GetArray('vsurfini 2')) data['vsurfini'] = np.sqrt(data['vsurfini 1']**2+data['vsurfini 2']**2) except: # To account for bug in steady.sif, which won't save "vsurfini 1" and "vsurfini 2" # at the same time, so I've saved "vsurfini 2" as vsurfini2 data['vsurfini 1'] = numpy_support.vtk_to_numpy(vtudata.GetPointData().GetArray('vsurfini 1')) data['vsurfini 2'] = numpy_support.vtk_to_numpy(vtudata.GetPointData().GetArray('vsurfini2')) data['vsurfini'] = np.sqrt(data['vsurfini 1']**2+data['vsurfini 2']**2) elif var.endswith('update'): update = numpy_support.vtk_to_numpy(vtudata.GetPointData().GetArray(var)) data[var+' 1'] = update[:,0] data[var+' 2'] = update[:,1] data[var+' 3'] = update[:,2] else: data[var] = numpy_support.vtk_to_numpy(vtudata.GetPointData().GetArray(var)) if ('taub' in varnames) and ('ssavelocity' in varnames): data['taub'] = data['beta']**2.0*np.sqrt(data['ssavelocity 1']**2.0+data['ssavelocity 2']**2.0) elif ('taub' in varnames) and ('velocity' in varnames): data['taub'] = data['beta']**2.0*np.sqrt(data['velocity 1']**2.0+data['velocity 2']**2.0) if ('betasquared' in varnames): data['betasquared'] = data['beta']**2 # Some of the nodes are shared/repeated between partitions, so we need to remove those var1,ind1 = np.unique(x,return_index = True) var2,ind2 = np.unique(y,return_index = True) var3,ind3 = np.unique(z,return_index = True) ind = np.union1d(np.union1d(ind1,ind2),ind3) data_final = data[ind] if tarfile: i = int(file[-9:-5]) os.system('rm '+file[0:-10]+'*{0:04d}.'.format(i)+'*vtu') os.chdir(cwd) vtudata.ReleaseData() del ind,var1,var2,var3,ind1,ind2,ind3,varnames,vtudata,data,x,y,z,var,types,variables del n if returnreader: return data_final,reader else: return data_final
def MultiplyVTKArray(vtkArray, factor): numarray = numpy_support.vtk_to_numpy(vtkArray) numarray *= factor del numarray
""" Paraview ProgrammableFilter. This filter assumes a variable 'filter_parameters' that is dictionary containing key 'region_id_to_extract'. The cells where dataset 'region_id' is equal to provided value are extracted. Example: parameters={ "dimension_to_extract" : 2 } ProgrammableFilter(Input=data_in, Script="filter_parameters="+str(parameters)+"\n"+this_file) """ import submesh import numpy as np import paraview.numpy_support as ns pdi = self.GetPolyDataInput() pdo = self.GetOutput() region_id = filter_parameters["region_id_to_extract"] region_id_array = ns.vtk_to_numpy( pdi.GetCellData().GetArray("region_id") ) int_array=np.round(region_id_array).astype(np.int) cell_list=np.where(int_array == region_id)[0] submesh.submesh(pdi, pdo, cell_list)
def exnp(self): '''Extract data for nasopharynx''' data = self.data model = 'NC0%d' % self.model ldat = self.ldat from paraview import numpy_support as ns from math import tan, pi # set origins cons = {'NC04': 0.065, 'NC04C': 0.01, 'NC04H': -0.008, 'NC05': 0.065, 'NC05C': 0.005, 'NC05H': -0.003, 'NC06': 0.06, 'NC06C': 0.005, 'NC06H': -0.008, 'NC07': 0.062, 'NC07C': 0, 'NC07H': -0.015, 'NC09': 0.064, 'NC09C': 0, 'NC09H': -0.05} Sli = FindSource("Slice1") Integra = FindSource("IntegrateVariables1") Int = FindSource("IntegrateVariables2") SetActiveSource(Sli) if model == 'NC06': Sli.SliceType.Origin = [-cons[model] - cons[model+'C'], cons[model+'H'], 0] # NOQA else: Sli.SliceType.Origin = [cons[model] + cons[model+'C'], cons[model+'H'], 0] # NOQA # iterate over nasopharynx resp = self.res/4 for x in range(resp): if model == 'NC06': Sli.SliceType.Normal = [-1, -tan(pi*x/(2*resp)), 0] else: Sli.SliceType.Normal = [1, -tan(pi*x/(2*resp)), 0] intData = servermanager.Fetch(Integra) if model == 'NC09': self.inf['X'].append( cons[model]*1000 - x*cons[model+'H']*pi*0.05/resp*1000) else: self.inf['X'].append( cons[model]*1000 - x*cons[model+'H']*pi*0.5/resp*1000) self.inf['Area'].append(ns.vtk_to_numpy( intData.GetCellData().GetArray('Area'))[0]) for i in data: self.inf[i].append( ns.vtk_to_numpy(intData.GetPointData().GetArray(i))[0]) InDat = servermanager.Fetch(Int) self.inf['Len'].append(ns.vtk_to_numpy(InDat.GetCellData().GetArray('Length'))[0]) # NOQA for i in ldat: self.inf[i].append( ns.vtk_to_numpy(InDat.GetCellData().GetArray(i))[0])
def trouver_centres_spheres_inscrites(surface_1, surface_2, precision=1e-6, pas_initial=10): """fonction qui recherche les centrse des spheres inscrites entre les surface_1 et surface_2 le vecteur 'Normals' doit etre present aux noeuds de surface_1 la recherche se fait par trouver_zero_fonction_croissante, pour chacun des points de surface_1 on cherche un point sur la ligne orthogonale a surface_1, equidistant de surface_1 et surface_2 --> centre de la sphere inscrite entre surface_1 et surface_2 passant par le point de surface_1 considere surface_1 et surface_2 doivent etre des vtkPolyData """ # initialisation des outils vtk de calcul des distances calcul_distance_1 = vtk.vtkKdTreePointLocator() calcul_distance_1.SetDataSet(surface_1) calcul_distance_1.BuildLocator() calcul_distance_2 = vtk.vtkKdTreePointLocator() calcul_distance_2.SetDataSet(surface_2) calcul_distance_2.BuildLocator() vtkMath = vtk.vtkMath() # lecture des donnees de la surface liste_normals_surface_1 = numpy_support.vtk_to_numpy(surface_1.GetPointData().GetArray('Normals')) liste_points_surface_1 = numpy_support.vtk_to_numpy(surface_1.GetPoints().GetData()) # ACTION liste_centres = numpy.empty((0,3)) print "progression ", printed = False for numero_point_surface_1 in range(0, surface_1.GetNumberOfPoints()): progress = ((numero_point_surface_1 + 1) * 100) // surface_1.GetNumberOfPoints() if progress % 10 == 0 and printed is False: print "{0}%".format(progress), printed = True elif progress % 10 != 0: printed = False """le vecteur normal et les coordonnees de point definissent une ligne sur laquelle chercher le centre de la sphere""" normal = liste_normals_surface_1[numero_point_surface_1] point = liste_points_surface_1[numero_point_surface_1] def fonction_a_annuler(x): centre = point + x * normal p1 = surface_1.GetPoint(calcul_distance_1.FindClosestPoint(centre)) p2 = surface_2.GetPoint(calcul_distance_2.FindClosestPoint(centre)) dist_1 = vtkMath.Distance2BetweenPoints(p1, centre) dist_2 = vtkMath.Distance2BetweenPoints(p2, centre) nv_ecart = dist_1 ** (1. / 2) - dist_2 ** (1. / 2) return nv_ecart """ recherche du centre de la sphere inscrite par trouver_zero_fonction_croissante""" # il est possible que le pas initial indique soit trop petit pas = pas_initial while fonction_a_annuler(pas) < 0: pas *= 2. # recherche par dichotomie x_solution = trouver_zero_fonction_croissante(0.0, pas, fonction_a_annuler, precision) centre = point + x_solution * normal liste_centres = numpy.r_[liste_centres, centre.reshape((1, 3))] print "termine" # creation d'un object vtkPolyData vtkPoints_mean = vtk.vtkPoints() vtkPoints_mean.SetData(numpy_support.numpy_to_vtk(liste_centres, deep = 1)) surface_moyenne = vtk.vtkPolyData() surface_moyenne.SetPoints(vtkPoints_mean) surface_moyenne.SetPolys(surface_1.GetPolys()) surface_moyenne.Update() return surface_moyenne
""" Paraview ProgrammableFilter. This filter assumes a variable 'filter_parameters' that is dictionary conatining key 'dimension_to_extract' with dimension of simplices to extract (allowed values are 0,1,2,3). Example: parameters={ "dimension_to_extract" : 2 } ProgrammableFilter(Input=data_in, Script="filter_parameters="+str(parameters)+"\n"+this_file) """ import submesh import numpy as np import paraview.numpy_support as ns pdi = self.GetPolyDataInput() pdo = self.GetOutput() dimension = filter_parameters["dimension_to_extract"] type_to_extract = submesh.type_for_dimension[ dimension ] cell_types=ns.vtk_to_numpy(pdi.GetCellTypesArray()) cell_list=np.where(cell_types == type_to_extract)[0] submesh.submesh(pdi, pdo, cell_list)