Esempio n. 1
0
    def calculate_eigenvectors_eigenvalues(self):
        if not (self.active_tensor
                in self.processed_tensors_for_eigenvectors_eigenvalues):
            self.processed_tensors_for_eigenvectors_eigenvalues.append(
                self.active_tensor)

            input_grid = self.inputs[0].outputs[0]
            tensor_field = array(
                input_grid.point_data.get_array(self.active_tensor))

            result = map(
                lambda x: linalg.eig(
                    reshape(x, (self.dimensions, self.dimensions))),
                tensor_field)
            sorted_indices = map(lambda x: argsort(x[0]), result)

            for i in range(self.dimensions):
                eigenvalues = map(lambda x, y: x[0][y[i]], result,
                                  sorted_indices)
                eigenvectors = map(lambda x, y: x[1][y[i]], result,
                                   sorted_indices)

                eigenvalues_field = tvtk.FloatArray(name=self.active_tensor +
                                                    '_eigenvalues_' + ` i `)
                eigenvalues_field.from_array(eigenvalues)
                self.grid.point_data.add_array(eigenvalues_field)

                eigenvectors_field = tvtk.FloatArray(name=self.active_tensor +
                                                     '_eigenvectors_' + ` i `)
                eigenvectors_field.from_array(eigenvectors)
                self.grid.point_data.add_array(eigenvectors_field)
Esempio n. 2
0
    def grad_curl(self, array, curl):
        # Can't remove arrays by index - that's why I've given it a name
        temp_name = 'a_temp_name_hopefully_nobody_will_ever_use'
        temp_array = tvtk.FloatArray(name=temp_name)
        temp_array.from_array(array)
        self.grid.point_data.add_array(temp_array)

        if (curl):
            self.grid.point_data.set_active_vectors(temp_name)
        else:
            self.grid.point_data.set_active_scalars(temp_name)

        cd = tvtk.CellDerivatives()
        cd.input = self.grid
        if (curl):
            cd.vector_mode = 'compute_vorticity'
        cd.update()

        cp = tvtk.CellDataToPointData()
        cp.input = cd.output
        cp.update()

        self.grid.point_data.remove_array(
            'a_temp_name_hopefully_nobody_will_ever_use')

        return cp.output.point_data.get_array('Vorticity')
Esempio n. 3
0
    def calculate_propotionaleigenvectors(self):
        if not (self.active_tensor
                in self.processed_tensors_for_proportionaleigenvectors):
            self.processed_tensors_for_proportionaleigenvectors.append(
                self.active_tensor)

            self.calculate_edgelengths()
            input_grid = self.inputs[0].outputs[0]

            for i in range(self.dimensions):
                eigenvectors = array(
                    self.grid.point_data.get_array(self.active_tensor +
                                                   '_eigenvectors_' + ` i `))
                edgelengths = array(
                    self.grid.point_data.get_array(self.active_tensor +
                                                   '_edgelengths_' + ` i `))
                proportionaleigenvectors = map(multiply, eigenvectors,
                                               edgelengths)

                proportionaleigenvectors_field = tvtk.FloatArray(
                    name=self.active_tensor + '_proportionaleigenvectors_' +
                    ` i `)
                proportionaleigenvectors_field.from_array(
                    proportionaleigenvectors)
                self.grid.point_data.add_array(proportionaleigenvectors_field)
Esempio n. 4
0
    def AddScalarField(self, name, array):
        """Adds a scalar field with the specified name using the values from the array."""
        # In vtktools.py the following used SetNumberOfValues=len(array)
        data = tvtk.FloatArray(number_of_tuples=len(array), name=name)
        for i in range(len(array)):
            data.set_value(i, array[i])

        pointdata = self.ugrid.point_data
        pointdata.add_array(data)
        pointdata.set_active_scalars(name)
Esempio n. 5
0
  def read(self, filename):

    reader = VTKDataReader()
    data = reader.read(filename)

    cells = data['cells']
    vertices = data['vertices']

    (ncells, ncorners) = cells.shape
    (nvertices, spaceDim) = vertices.shape
    
    vtkData = tvtk.UnstructuredGrid()
    vtkData.points = vertices
    assert(spaceDim == 3)
    assert(ncorners == 3)
    cellType = tvtk.Triangle().cell_type

    vtkData.set_cells(cellType, cells)


    # Displacement vector
    displacement = data['vertex_fields']['displacement']
    array = tvtk.FloatArray()
    array.from_array(displacement.squeeze())
    array.name = "Displacement (m)"
    vtkData.point_data.vectors = array
    vtkData.point_data.vectors.name = "Displacement (m)"

    # Compute velocity magnitude
    velocity = data['vertex_fields']['velocity']
    velocityLog = ((velocity[:,0]**2 + 
                    velocity[:,1]**2 + 
                    velocity[:,2]**2)**0.5)
    array = tvtk.FloatArray()
    array.from_array(velocityLog.squeeze())
    array.name = "Velocity (m/s)"
    vtkData.point_data.scalars = array
    vtkData.point_data.scalars.name = "Velocity (m/s)"

    return vtkData
Esempio n. 6
0
    def AddVectorField(self, name, array):
        """Adds a vector field with the specified name using the values from the array."""
        n = array.size
        # In vtktools.py the following used SetNumberOfValues=n
        data = tvtk.FloatArray(number_of_components=array.shape[1],
                               number_of_tuples=n,
                               name=name)
        for i in range(n):
            data.set_value(i, array.reshape(n)[i])

        pointdata = self.ugrid.point_data
        pointdata.add_array(data)
        pointdata.set_active_vectors(name)
Esempio n. 7
0
    def calculate_edgelengths(self):
        if not (self.active_tensor in self.processed_tensors_for_edgelengths):
            self.processed_tensors_for_edgelengths.append(self.active_tensor)

            input_grid = self.inputs[0].outputs[0]

            for i in range(self.dimensions):
                eigenvalues = array(
                    self.grid.point_data.get_array(self.active_tensor +
                                                   '_eigenvalues_' + ` i `))
                edgelengths = map(lambda x: 1 / sqrt(x), eigenvalues)

                edgelengths_field = tvtk.FloatArray(name=self.active_tensor +
                                                    '_edgelengths_' + ` i `)
                edgelengths_field.from_array(edgelengths)
                self.grid.point_data.add_array(edgelengths_field)
Esempio n. 8
0
    def _add_attribute_array(self, attribute_array, i, type):
        """
        Adds the given attribute array to either point_data or
        cell_data of the unstructured grid.
        """
        attribute_array_name = 'Attribute %i' % i
        if (type == 'cell'):  # .ele file attributes are of type Int
            tvtk_attribute_array = tvtk.IntArray(name=attribute_array_name)
            attribute_array = map(int, attribute_array)
        else:  # .node file attributes are of type Float
            tvtk_attribute_array = tvtk.FloatArray(name=attribute_array_name)
        tvtk_attribute_array.from_array(attribute_array)
        getattr(self._grid, '%s_data' % type).add_array(tvtk_attribute_array)
        getattr(self, '_%s_scalars_list' % type).append(attribute_array_name)

        if (i == 0):
            self._set_data_name(type, 'Attribute 0')
Esempio n. 9
0
    def test_array_conversion(self):
        """Test if Numeric/VTK array conversion works."""
        # This is only a simple test.
        data = numpy.array(
            [[0, 0, 0, 10], [1, 0, 0, 20], [0, 1, 0, 20], [0, 0, 1, 30]], 'f')
        triangles = numpy.array([[0, 1, 3], [0, 3, 2], [1, 2, 3], [0, 2, 1]])
        points = data[:, :3]
        temperature = data[:, -1]
        mesh = tvtk.PolyData()
        mesh.points = points
        mesh.polys = triangles
        mesh.point_data.scalars = temperature

        # Test if a normal float array also works.
        temp = tvtk.FloatArray()
        temp.from_array(temperature)
        mesh.point_data.scalars = temp
Esempio n. 10
0
def make_data():
    points = N.array(
        [
            [0, 0, 0],
            [1, 0, 0],
            [0, 1, 0],
            [0, 0, 1],  # tets
            [1, 0, 0],
            [2, 0, 0],
            [1, 1, 0],
            [1, 0, 1],
            [2, 0, 0],
            [3, 0, 0],
            [2, 1, 0],
            [2, 0, 1],
        ],
        'f')
    tets = N.array([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]])
    tet_type = tvtk.Tetra().cell_type
    ug = tvtk.UnstructuredGrid(points=points)
    ug.set_cells(tet_type, tets)
    # Setup the point attributes.
    temp = N.random.random(12)
    v = N.random.randn(12, 3)
    ten = N.random.randn(12, 9)
    a = tvtk.FloatArray(name='p')
    a.from_array(N.random.randn(12))
    ug.point_data.add_array(a)
    ug.point_data.scalars = temp
    ug.point_data.scalars.name = 't'
    ug.point_data.vectors = v
    ug.point_data.vectors.name = 'v'
    ug.point_data.tensors = ten
    ug.point_data.tensors.name = 'ten'
    # Setup the cell attributes.
    temp = N.random.random(3)
    v = N.random.randn(3, 3)
    ten = N.random.randn(3, 9)
    ug.cell_data.scalars = temp
    ug.cell_data.scalars.name = 't'
    ug.cell_data.vectors = v
    ug.cell_data.vectors.name = 'v'
    ug.cell_data.tensors = ten
    ug.cell_data.tensors.name = 'ten'
    return ug
Esempio n. 11
0
    def test_data_array(self):
        """Test if vtkDataArrays behave in a Pythonic fashion."""
        # Check a 3D array.
        f = tvtk.FloatArray()
        a = numpy.array([[0., 0, 0], [1, 1, 1]])
        f.from_array(a)
        self.assertEqual(f.number_of_components, 3)
        self.assertEqual(f.number_of_tuples, 2)
        self.assertEqual(mysum(f.to_array() - a), 0)
        for i, j in zip(a, f):
            self.assertEqual(mysum(i - j), 0.0)
        self.assertEqual(f[0], (0.0, 0.0, 0.0))
        self.assertEqual(f[-1], (1., 1., 1.))
        self.assertEqual(repr(f), '[(0.0, 0.0, 0.0), (1.0, 1.0, 1.0)]')
        f.append((2, 2, 2))
        f.extend([[3, 3, 3], [4, 4, 4]])
        self.assertEqual(len(f), 5)
        self.assertEqual(f.number_of_components, 3)
        self.assertEqual(f.number_of_tuples, 5)
        f[1] = [-1, -1, -1]
        self.assertEqual(f[1], (-1.0, -1.0, -1.0))
        self.assertRaises(IndexError, f.__getitem__, 100)
        self.assertRaises(IndexError, f.__setitem__, 100, 100)

        # Check a 5D arrray
        a = numpy.array([[0., 0, 0, 0, 0], [1, 1, 1, 1, 1]])
        f.from_array(a)
        self.assertEqual(mysum(f.to_array() - a), 0.0)
        for i, j in zip(a, f):
            self.assertEqual(mysum(i - j), 0.0)
        self.assertEqual(f[0], (0.0, 0.0, 0.0, 0.0, 0.0))
        self.assertEqual(f[-1], (1., 1., 1., 1., 1.))
        self.assertEqual(
            repr(f), '[(0.0, 0.0, 0.0, 0.0, 0.0), (1.0, 1.0, 1.0, 1.0, 1.0)]')
        f.append((2, 2, 2, 2, 2))
        f.extend([[3, 3, 3, 3, 3], [4, 4, 4, 4, 4]])
        self.assertEqual(len(f), 5)
        self.assertEqual(f.number_of_components, 5)
        self.assertEqual(f.number_of_tuples, 5)
        self.assertEqual(f[-1], (4., 4., 4., 4., 4.))
        f[1] = [-1, -1, -1, -1, -1]
        self.assertEqual(f[1], (-1.0, -1.0, -1.0, -1.0, -1.0))
        self.assertRaises(IndexError, f.__getitem__, 100)
        self.assertRaises(IndexError, f.__setitem__, 100, 100)
Esempio n. 12
0
    def draw_height_quantity(self, quantityName):
        """Use the vtkPolyData and prepare/update the rest of the VTK
        rendering pipeline.
        """
        if quantityName in self.vtk_mappers:
            mapper = self.vtk_mappers[quantityName]
        else:
            mapper = self.vtk_mappers[quantityName] = vtkPolyDataMapper()
        mapper.SetInput(self.vtk_polyData[quantityName])
        mapper.Update()

        if quantityName not in self.vtk_actors:
            actor = self.vtk_actors[quantityName] = vtkActor()
            actor.SetMapper(mapper)
            self.vtk_renderer.AddActor(actor)
        else:
            actor = self.vtk_actors[quantityName]

        if quantityName in self.colours_height:
            colour = self.colours_height[quantityName]
            if type(colour) == TupleType:
                if type(colour[0]) == FunctionType:
                    # It's a function, so take colour[1] as the
                    # lower bound on the scalar range and
                    # colour[2] as the upper bound on the scalar
                    # range.
                    scalars = tvtk.FloatArray()
                    list(
                        map(scalars.InsertNextValue,
                            colour[0](self.build_quantity_dict())))
                    self.vtk_polyData[quantityName].GetPointData().SetScalars(
                        scalars)
                    mapper.SetScalarRange(colour[1:])
                    mapper.Update()
                else:
                    # It's a 3-tuple representing an RGB value.
                    actor.GetProperty().SetColor(colour)
            else:
                actor.GetProperty().SetColor(0.5, 0.5, 0.5)
        else:
            actor.GetProperty().SetColor(0.5, 0.5, 0.5)
Esempio n. 13
0
class CitcomSHDFUgrid:
    
    """This Class converts CitcomS hdf files to tvtk UnstructuredGrid Dataset Objects """
    
    data = None
    _nx = None
    _ny = None
    _nz = None
    _nx_redu = None
    _ny_redu = None
    _nz_redu = None
    _radius_inner = None
    _radius_outer = None
    timesteps = None
    frequency = None
    
    progress = 0
    
    #Global because a Unstructured Grid can only hold one scalar value at a time
    #but our hdf file reader plugin wants to be able to read both
    __vtkordered_visc = tvtk.FloatArray()
    __vtkordered_temp = tvtk.FloatArray()  
    

    def vtk_iter(self,nx,ny,nz):
        """Iterator for CitcomDataRepresentation(yxz) to VTK(xyz)"""
        for i in xrange(nx):
            for j in xrange(ny):
                for k in xrange(nz):
                    yield k + nz * i + nz * nx * j

    
    def reduce_iter(self,n,nredu):
        """Iterator to reduce the CitcomS grid"""
        i=0
        n_f=float(n)
        nredu_f=float(nredu)
        fl=(n_f-1)/nredu_f
        redu = 0
        for i in xrange(nredu+1):
            yield int(round(redu))
            redu = redu + fl
            
    
    def velocity2cart(self,vel_colat,vel_long,r, x, y, z):
        """Converts vectors in spherical to cartesian coordiantes"""
        x1 = r*sin(x)*cos(y)+vel_colat*cos(x)*cos(y)-vel_long*sin(y)
        y1 = r*sin(x)*sin(y)+vel_colat*cos(x)*sin(y)+vel_long*cos(y)
        z1 = r*cos(x)-vel_colat*sin(x)
        return x1, y1, z1


    #Converts Spherical to Cartesian Coordinates
    def RTF2XYZ(self,thet, phi, r):
        """Converts points from spherical to cartesian coordinates"""
        x = r * sin(thet) * cos(phi)
        y = r * sin(thet) * sin(phi)
        z = r * cos(thet)
        return x, y, z
    
    
    
    def __citcom2vtk(self,t,f,nproc_surf,nx_redu,ny_redu,nz_redu):
        """Method to convert one timestep from a hdf file to a Vtk file. This Method is used
        by the method initialize. Initialize reads the necessary meta information from the hdf file"""
        
        hexagrid = tvtk.UnstructuredGrid()
        hexagrid.allocate(1,1)
        
        vtkordered_velo = tvtk.FloatArray()
        
        nx = self._nx
        ny = self._ny
        nz = self._nz
        counter = 0
        el_nx_redu = nx_redu + 1
        el_ny_redu = ny_redu + 1
        el_nz_redu = nz_redu + 1
            
        ordered_points = [] #reset Sequences for points   
        ordered_temperature = []
        ordered_velocity = []
        ordered_viscosity = []
    
        for capnr in xrange(nproc_surf):
          
           
            cap = f.root._f_getChild("cap%02d" % capnr)
    
            temp_coords =  [] # reset Coordinates, Velocity, Temperature Sequence
            temp_vel = []     
            temp_temp = []
            temp_visc = []
    
            #Information from hdf
            hdf_coords = cap.coord[:]
            hdf_velocity = cap.velocity[t]
            hdf_temperature = cap.temperature[t]
            hdf_viscosity = cap.viscosity[t]
    

            #Create Iterator to change data representation
            nx_redu_iter = self.reduce_iter(nx,nx_redu)
            ny_redu_iter = self.reduce_iter(ny,ny_redu)
            nz_redu_iter = self.reduce_iter(nz,nz_redu)
      
            #vtk_i = self.vtk_iter(el_nx_redu,el_ny_redu,el_nz_redu)
             
         
            # read citcom data - zxy (z fastest)
            for j in xrange(el_ny_redu):
                j_redu = ny_redu_iter.next()
                nx_redu_iter = self.reduce_iter(nx,nx_redu)
                for i in xrange(el_nx_redu):
                    i_redu = nx_redu_iter.next()
                    nz_redu_iter = self.reduce_iter(nz,nz_redu)
                    for k in xrange(el_nz_redu):
                        k_redu = nz_redu_iter.next()
                
                        colat, lon, r = map(float,hdf_coords[i_redu,j_redu,k_redu])
                        x_coord, y_coord, z_coord = self.RTF2XYZ(colat,lon,r)
                        ordered_points.append((x_coord,y_coord,z_coord))
      
                        ordered_temperature.append(float(hdf_temperature[i_redu,j_redu,k_redu]))
                        ordered_viscosity.append(float(hdf_viscosity[i_redu,j_redu,k_redu]))
                
                    
                        vel_colat, vel_lon , vel_r = map(float,hdf_velocity[i_redu,j_redu,k_redu])
                        x_velo, y_velo, z_velo = self.velocity2cart(vel_colat,vel_lon,vel_r, colat,lon , r)
                    
                        ordered_velocity.append((x_velo,y_velo,z_velo))                        
        
        
            ##Delete Objects for GC
            del hdf_coords
            del hdf_velocity
            del hdf_temperature
            del hdf_viscosity
        

           
            #Create Connectivity info    
            if counter==0:
                 i=1    #Counts X Direction
                 j=1    #Counts Y Direction
                 k=1    #Counts Z Direction
    
                 for n in xrange((el_nx_redu*el_ny_redu*el_nz_redu)-(el_nz_redu*el_nx_redu)):
                     if (i%el_nz_redu)==0:            #X-Values!!!
                         j+=1                 #Count Y-Values
        
                     if (j%el_nx_redu)==0:
                         k+=1                #Count Z-Values
                  
                     if i%el_nz_redu!=0 and j%el_nx_redu!=0:            #Check if Box can be created
                         #Get Vertnumbers
                         n0 = n+(capnr*(el_nx_redu*el_ny_redu*el_nz_redu))
                         n1 = n0+el_nz_redu
                         n2 = n1+el_nz_redu*el_nx_redu
                         n3 = n0+el_nz_redu*el_nx_redu
                         n4 = n0+1
                         n5 = n4+el_nz_redu
                         n6 = n5+el_nz_redu*el_nx_redu
                         n7 = n4+el_nz_redu*el_nx_redu
                         #Created Polygon Box
                         hexagrid.insert_next_cell(12,[n0,n1,n2,n3,n4,n5,n6,n7])
             
                     i+=1
        
        
        #Store Arrays in Vtk conform Datastructures
        self.__vtkordered_temp.from_array(ordered_temperature)
        self.__vtkordered_visc.from_array(ordered_viscosity)                                    
        vtkordered_velo.from_array(ordered_velocity)
        
        self.__vtkordered_temp.name = 'Temperature'
        self.__vtkordered_visc.name = 'Viscosity'
        hexagrid.point_data.scalars = self.__vtkordered_temp
        vtkordered_velo.name = 'Velocity'
        hexagrid.point_data.vectors = vtkordered_velo
        hexagrid.points = ordered_points
            
        self.progress += 1
        
        return hexagrid
            
            
    def initialize(self,filename,timestep,nx_redu,ny_redu,nz_redu):
        """Call this method to convert a Citcoms Hdf file to a Vtk file"""
        
        #Read meta-inforamtion
        hdf=tables.openFile(filename,'r')
        self._nx = int(hdf.root.input._v_attrs.nodex)
        self._ny = int(hdf.root.input._v_attrs.nodey)
        self._nz = int(hdf.root.input._v_attrs.nodez)
        
        #Clip against boundaries
        if nx_redu>=0 or nx_redu>=self._nx:
            nx_redu = self._nx-1
        if ny_redu==0 or ny_redu>=self._ny:
            ny_redu = self._ny-1
        if nz_redu==0 or nz_redu>=self._nz:
            nz_redu = self._nz-1
        
        #Make reduction factors global
        self._nx_redu = nx_redu
        self._ny_redu = ny_redu
        self._nz_redu = nz_redu
        
        #Number of Timesteps in scene   
        self.timesteps = int(hdf.root.time.nrows)
        #Number of caps
        nproc_surf = int(hdf.root.input._v_attrs.nproc_surf)
        #Store the Inner Radius. Import if we want to create a core
        self._radius_inner = self._radius_inner = float(hdf.root.input._v_attrs.radius_inner)
        #start computation
        hexgrid = self.__citcom2vtk(timestep,hdf,nproc_surf,nx_redu,ny_redu,nz_redu)
        
        hdf.close()
        self.progress = -1
        return hexgrid 
        
    def get_vtk_viscosity(self):
        return self.__vtkordered_visc
    
    def get_vtk_temperature(self):
        return self.__vtkordered_temp
Esempio n. 14
0
    def field_operation(self, operation, input_arrays, output_array):
        scalar_op = False  # Operation on scalars only?
        vector_op = False  # Operation on vectors only?
        custom_fn = False  # Custom Python function defined?
        multiple_inputs = True  # Operation with multiple inputs?

        if (operation == 'Sum'):
            self.check_min_input_size(input_arrays, 2)
            function = lambda x: add.reduce(x)
        elif (operation == 'Multiply'):
            self.check_min_input_size(input_arrays, 2)
            function = lambda x: multiply.reduce(x)
        elif (operation == 'Dot product'):
            vector_op = True
            self.check_exact_input_size(input_arrays, 2)
            function = lambda x: map(dot, x[0], x[1])
        elif (operation == 'Cross product'):
            vector_op = True
            self.check_exact_input_size(input_arrays, 2)
            function = lambda x: cross(x[0], x[1])
        elif (operation == 'Python function'):
            custom_fn = True
            try:
                function = lambda inputs: eval(self.custom_function)
            except:
                raise Exception, 'There is an error in your custom Python function.'

        else:
            multiple_inputs = False
            if (operation == 'Reciprocal'):
                function = lambda x: 1 / x
            elif (operation == 'Exponential'):
                function = lambda x: exp(x)
            elif (operation == 'Natural log'):
                function = lambda x: log(x)
            elif (operation == 'Step'):
                function = lambda x: map(lambda x: (x > 0) + 0, x)
            elif (operation == 'Scale/Offset'):
                function = lambda x: x
            elif (operation == 'd/dx'):
                scalar_op = True
                function = lambda x: self.derivative(x, 0)
            elif (operation == 'd/dy'):
                scalar_op = True
                function = lambda x: self.derivative(x, 1)
            elif (operation == 'd/dz'):
                scalar_op = True
                function = lambda x: self.derivative(x, 2)
            elif (operation == 'Curl'):
                vector_op = True
                function = lambda x: self.grad_curl(x, True)
            elif (operation == 'Grad'):
                scalar_op = True
                function = lambda x: self.grad_curl(x, False)
            elif (operation == 'Div'):
                vector_op = True
                function = self.divergence
            elif (operation == 'Normalize'):
                vector_op = True
                function = lambda x: map(multiply, x, 1 / array(
                    map(linalg.norm, x)))
            elif (operation == '2-norm'):
                vector_op = True
                function = lambda x: map(linalg.norm, x)
            elif (operation == 'x-component'):
                vector_op = True
                function = lambda x: self.get_axis(x, 0)
            elif (operation == 'y-component'):
                vector_op = True
                function = lambda x: self.get_axis(x, 1)
            elif (operation == 'z-component'):
                vector_op = True
                function = lambda x: self.get_axis(x, 2)
            else:
                raise Exception, 'Undefined operation.'
            self.check_exact_input_size(input_arrays, 1)

        # Retrieve array data
        input_data = self.retrieve_arrays(input_arrays, scalar_op, vector_op)

        if (multiple_inputs):
            if (custom_fn):
                try:
                    result = function(input_data)
                except:
                    raise Exception, 'There is an error in your custom Python function.'
            else:
                result = function(input_data)
        else:
            result = function(input_data[0])

        output_array_name = output_array[0]
        scale_factor = output_array[1]
        offset = output_array[2]

        # Scale and offset result array if necessary
        if (scale_factor != 1.0 or offset != 0.0):
            result = array(result) * scale_factor + offset

        # Store result (replaces array with name output_array_name if it exists)
        output_array = tvtk.FloatArray(name=output_array_name)
        output_array.from_array(result)
        self.grid.point_data.add_array(output_array)
        self.pipeline_changed = True
Esempio n. 15
0
class CitcomSHDFFileReader(Source):
    """This source manages a CitcomS Hdf file given to it. """

    # The version of this class.  Used for persistence.
    __version__ = 0

    # The VTK dataset to manage.
    data = Instance(tvtk.DataSet)
    # Class to convert Hdf to Vtk Unstructured Grid Objects
    citcomshdftougrid = CitcomSHDFUgrid()
    current_timestep = Int(0)
    #To support changing the Scalar values in Mayavi2
    temperature = Instance(tvtk.FloatArray())
    viscosity = Instance(tvtk.FloatArray())

    #Resolution comming from Hdf file
    nx = Int()
    ny = Int()
    nz = Int()

    #Current reduced resolution. User defined
    nx_redu = Int()
    ny_redu = Int()
    nz_redu = Int()

    #Number of timesteps in Hdf
    timesteps = Int()

    #Button to trigger the process of reading a timestep
    read_timestep = Button('Read timestep')
    filename = Str()

    ########################################
    # Dynamic traits: These traits are dummies and are dynamically
    # updated depending on the contents of the file.

    # The active point scalar name.
    point_scalars_name = Trait('', TraitPrefixList(['']))
    # The active point vector name.
    point_vectors_name = Trait('', TraitPrefixList(['']))
    # The active point tensor name.
    point_tensors_name = Trait('', TraitPrefixList(['']))

    # The active cell scalar name.
    cell_scalars_name = Trait('', TraitPrefixList(['']))
    # The active cell vector name.
    cell_vectors_name = Trait('', TraitPrefixList(['']))
    # The active cell tensor name.
    cell_tensors_name = Trait('', TraitPrefixList(['']))
    ########################################

    # Our view.
    view = View(
        Group(
            Item(name='current_timestep'),
            Item(name='nx_redu'),
            Item(name='ny_redu'),
            Item(name='nz_redu'),
            Item(name='read_timestep', style='simple', label='Simple'),
            Item(name='point_scalars_name'),
            Item(name='point_vectors_name'),
            Item(name='point_tensors_name'),
            Item(name='cell_scalars_name'),
            Item(name='cell_vectors_name'),
            Item(name='cell_tensors_name'),
        ), )

    ######################################################################
    # `object` interface
    ######################################################################
    #Invoked during process of saving the visualization to a file
    def __get_pure_state__(self):
        d = super(CitcomSHDFFileReader, self).__get_pure_state__()
        output = "Filename: " + self.filename + "NX:%d NY:%d NZ:%d" % (
            self.nx_redu, self.ny_redu, self.nz_redu)
        z = gzip_string(output)
        d['data'] = z
        return d

    #When the Visualisation is opened again this Method is called
    def __set_pure_state__(self, state):
        z = state.data
        if z:
            d = gunzip_string(z)
            m = re.search('(?<=Filename:)\w+', header)
            file_name = m.group(0)
            m = re.search('(?<=NX:)\w+', d)
            self.nx_redu = int(m.group(0))
            m = re.search('(?<=NX:)\w+', d)
            self.ny_redu = int(m.group(0))
            m = re.search('(?<=NX:)\w+', d)
            self.nz_redu = int(m.group(0))

            if not isfile(file_name):
                msg = 'Could not find file at %s\n' % file_name
                msg += 'Please move the file there and try again.'
                raise IOError, msg

            self.filename = file_name

            #self.data = self.citcomshdftougrid.initialize(self.filename,0,0,0,0,False,False)
            f = tables.openFile(file_name, 'r')
            self.nx = int(f.root.input._v_attrs.nodex)
            self.ny = int(f.root.input._v_attrs.nodey)
            self.nz = int(f.root.input._v_attrs.nodez)

            self.timesteps = int(f.root.time.nrows)
            f.close()
            self.data = self.citcomshdftougrid.initialize(
                self.filename, self.current_timestep, self.nx_redu,
                self.ny_redu, self.nz_redu)
            self.data_changed = True
            self._update_data()
            # Now set the remaining state without touching the children.
            set_state(self, state, ignore=['children', '_file_path'])
            # Setup the children.
            handle_children_state(self.children, state.children)
            # Setup the children's state.
            set_state(self, state, first=['children'], ignore=['*'])

    ######################################################################
    # `Base` interface
    ######################################################################
    def start(self):
        """This is invoked when this object is added to the mayavi
        pipeline.
        """
        # Do nothing if we are already running.
        if self.running:
            return

        # Update the data just in case.
        self._update_data()

        # Call the parent method to do its thing.  This will typically
        # start all our children.
        super(CitcomSHDFFileReader, self).start()

    def update(self):
        """Invoke this to flush data changes downstream."""
        self.data_changed = True

    def initialize(self, file_name):
        """This Methods initializes the reader and reads the meta-information from the Hdf file """
        self.filename = file_name

        #self.data = self.citcomshdftougrid.initialize(self.filename,0,0,0,0,False,False)
        f = tables.openFile(file_name, 'r')
        self.nx = int(f.root.input._v_attrs.nodex)
        self.ny = int(f.root.input._v_attrs.nodey)
        self.nz = int(f.root.input._v_attrs.nodez)

        self.nx_redu = self.nx
        self.ny_redu = self.ny
        self.nz_redu = self.nz

        self.timesteps = int(f.root.time.nrows)
        f.close()

    ######################################################################
    # `TreeNodeObject` interface
    ######################################################################
    def tno_get_label(self, node):
        """ Gets the label to display for a specified object.
        """
        ret = "CitcomS HDF Data (uninitialized)"
        if self.data:
            typ = self.data.__class__.__name__
            ret = "CitcomS HDF Data (%d)" % self.current_timestep
        return ret

    ######################################################################
    # Non-public interface
    ######################################################################
    def _data_changed(self, data):
        """Invoked when the upsteam data sends an data_changed event"""
        self._update_data()
        self.outputs = [data]
        self.data_changed = True
        # Fire an event so that our label on the tree is updated.
        self.trait_property_changed('name', '', self.tno_get_label(None))

    ##Callbacks for our traits
    def _current_timestep_changed(self, new_value):
        """Callback for the current timestep input box"""
        if new_value < 0:
            self.current_timestep = 0
        if new_value > self.timesteps:
            self.current_timestep = self.timesteps - 1

    def _read_timestep_fired(self):
        """Callback for the Button to read one timestep"""

        self.data = self.citcomshdftougrid.initialize(self.filename,
                                                      self.current_timestep,
                                                      self.nx_redu,
                                                      self.ny_redu,
                                                      self.nz_redu)
        self.temperature = self.citcomshdftougrid.get_vtk_temperature()
        self.viscosity = self.citcomshdftougrid.get_vtk_viscosity()

        ##New Thread Code
        #thread1 = CitcomSHdf2UGridThread()
        #thread2 = CitcomSProgressBar()

        #thread1.set_citcomsreader(self.filename,self.current_timestep,self.nx_redu,self.ny_redu,self.nz_redu,self.thread_callback)
        #progress = thread1.get_ref()
        #thread1.start()
        #thread2.set_ref(progress)
        #thread2.start()

        self.data_changed = True
        self._update_data()

    def _nx_redu_changed(self, new_value):
        """callback for the nx_redu input box"""
        if new_value < 1:
            self.nx_redu = 1
        if new_value > self.nx:
            self.nx_redu = self.nx

    def _ny_redu_changed(self, new_value):
        """callback for the ny_redu input box"""
        if new_value < 1:
            self.ny_redu = 1
        if new_value > self.ny:
            self.ny_redu = self.ny

    def _nz_redu_changed(self, new_value):
        """callback for the nz_redu input box"""
        if new_value < 1:
            self.nz_redu = 1
        if new_value > self.nz:
            self.nz_redu = self.nz

    def _point_scalars_name_changed(self, value):
        if value == "Temperature":
            self.data.point_data.scalars = self.temperature
        if value == "Viscosity":
            self.data.point_data.scalars = self.viscosity
        self.data_changed = True
        self._set_data_name('scalars', 'point', value)

    def _point_vectors_name_changed(self, value):
        self._set_data_name('vectors', 'point', value)

    def _point_tensors_name_changed(self, value):
        self._set_data_name('tensors', 'point', value)

    ########################Non Public##############################
    def _set_data_name(self, data_type, attr_type, value):
        if not value:
            return
        dataset = self.data
        data = None
        if attr_type == 'point':
            data = dataset.point_data
        elif attr_type == 'cell':
            data = dataset.cell_data
        meth = getattr(data, 'set_active_%s' % data_type)
        meth(value)
        self.update()
        # Fire an event, so the changes propagate.
        self.data_changed = True

    def _update_data(self):
        if not self.data:
            return
        else:
            trait = Trait('Temperature',
                          TraitPrefixList('Temperature', 'Viscosity'))
            self.add_trait('point_scalars_name', trait)
            trait = Trait('Velocity', TraitPrefixList('Velocity'))
            self.add_trait('point_vectors_name', trait)

    def thread_callback(self, hexagrid, vtk_viscosity, vtk_temperature):
        hexagrid.print_traits()
        self.data = hexagrid
        self.temperature = vtk_temperature
        self.viscosity = vtk_temperature
Esempio n. 16
0
    def __citcom2vtk(self,t,f,nproc_surf,nx_redu,ny_redu,nz_redu):
        """Method to convert one timestep from a hdf file to a Vtk file. This Method is used
        by the method initialize. Initialize reads the necessary meta information from the hdf file"""
        
        hexagrid = tvtk.UnstructuredGrid()
        hexagrid.allocate(1,1)
        
        vtkordered_velo = tvtk.FloatArray()
        
        nx = self._nx
        ny = self._ny
        nz = self._nz
        counter = 0
        el_nx_redu = nx_redu + 1
        el_ny_redu = ny_redu + 1
        el_nz_redu = nz_redu + 1
            
        ordered_points = [] #reset Sequences for points   
        ordered_temperature = []
        ordered_velocity = []
        ordered_viscosity = []
    
        for capnr in xrange(nproc_surf):
          
           
            cap = f.root._f_getChild("cap%02d" % capnr)
    
            temp_coords =  [] # reset Coordinates, Velocity, Temperature Sequence
            temp_vel = []     
            temp_temp = []
            temp_visc = []
    
            #Information from hdf
            hdf_coords = cap.coord[:]
            hdf_velocity = cap.velocity[t]
            hdf_temperature = cap.temperature[t]
            hdf_viscosity = cap.viscosity[t]
    

            #Create Iterator to change data representation
            nx_redu_iter = self.reduce_iter(nx,nx_redu)
            ny_redu_iter = self.reduce_iter(ny,ny_redu)
            nz_redu_iter = self.reduce_iter(nz,nz_redu)
      
            #vtk_i = self.vtk_iter(el_nx_redu,el_ny_redu,el_nz_redu)
             
         
            # read citcom data - zxy (z fastest)
            for j in xrange(el_ny_redu):
                j_redu = ny_redu_iter.next()
                nx_redu_iter = self.reduce_iter(nx,nx_redu)
                for i in xrange(el_nx_redu):
                    i_redu = nx_redu_iter.next()
                    nz_redu_iter = self.reduce_iter(nz,nz_redu)
                    for k in xrange(el_nz_redu):
                        k_redu = nz_redu_iter.next()
                
                        colat, lon, r = map(float,hdf_coords[i_redu,j_redu,k_redu])
                        x_coord, y_coord, z_coord = self.RTF2XYZ(colat,lon,r)
                        ordered_points.append((x_coord,y_coord,z_coord))
      
                        ordered_temperature.append(float(hdf_temperature[i_redu,j_redu,k_redu]))
                        ordered_viscosity.append(float(hdf_viscosity[i_redu,j_redu,k_redu]))
                
                    
                        vel_colat, vel_lon , vel_r = map(float,hdf_velocity[i_redu,j_redu,k_redu])
                        x_velo, y_velo, z_velo = self.velocity2cart(vel_colat,vel_lon,vel_r, colat,lon , r)
                    
                        ordered_velocity.append((x_velo,y_velo,z_velo))                        
        
        
            ##Delete Objects for GC
            del hdf_coords
            del hdf_velocity
            del hdf_temperature
            del hdf_viscosity
        

           
            #Create Connectivity info    
            if counter==0:
                 i=1    #Counts X Direction
                 j=1    #Counts Y Direction
                 k=1    #Counts Z Direction
    
                 for n in xrange((el_nx_redu*el_ny_redu*el_nz_redu)-(el_nz_redu*el_nx_redu)):
                     if (i%el_nz_redu)==0:            #X-Values!!!
                         j+=1                 #Count Y-Values
        
                     if (j%el_nx_redu)==0:
                         k+=1                #Count Z-Values
                  
                     if i%el_nz_redu!=0 and j%el_nx_redu!=0:            #Check if Box can be created
                         #Get Vertnumbers
                         n0 = n+(capnr*(el_nx_redu*el_ny_redu*el_nz_redu))
                         n1 = n0+el_nz_redu
                         n2 = n1+el_nz_redu*el_nx_redu
                         n3 = n0+el_nz_redu*el_nx_redu
                         n4 = n0+1
                         n5 = n4+el_nz_redu
                         n6 = n5+el_nz_redu*el_nx_redu
                         n7 = n4+el_nz_redu*el_nx_redu
                         #Created Polygon Box
                         hexagrid.insert_next_cell(12,[n0,n1,n2,n3,n4,n5,n6,n7])
             
                     i+=1
        
        
        #Store Arrays in Vtk conform Datastructures
        self.__vtkordered_temp.from_array(ordered_temperature)
        self.__vtkordered_visc.from_array(ordered_viscosity)                                    
        vtkordered_velo.from_array(ordered_velocity)
        
        self.__vtkordered_temp.name = 'Temperature'
        self.__vtkordered_visc.name = 'Viscosity'
        hexagrid.point_data.scalars = self.__vtkordered_temp
        vtkordered_velo.name = 'Velocity'
        hexagrid.point_data.vectors = vtkordered_velo
        hexagrid.points = ordered_points
            
        self.progress += 1
        
        return hexagrid
Esempio n. 17
0
def screenshot(figure=None, mode='rgb', antialiased=False):
    """ Return the current figure pixmap as an array.

        **Parameters**

        :figure: a figure instance or None, optional
            If specified, the figure instance to capture the view of.
        :mode: {'rgb', 'rgba'}
            The color mode of the array captured.
        :antialiased: {True, False}
            Use anti-aliasing for rendering the screenshot.
            Uses the number of aa frames set by 
            figure.scene.anti_aliasing_frames

        **Notes**

        On most systems, this works similarly to taking a screenshot of
        the rendering window. Thus if it is hidden by another window, you
        will capture the other window. This limitation is due to the
        heavy use of the hardware graphics system.

        **Examples**

        This function can be useful for integrating 3D plotting with
        Mayavi in a 2D plot created by matplotlib.

        >>> from enthought.mayavi import mlab
        >>> mlab.test_plot3d()
        >>> arr = mlab.screenshot()
        >>> import pylab as pl
        >>> pl.imshow(arr)
        >>> pl.axis('off')
        >>> pl.show()

    """
    if figure is None:
        figure = gcf()
    x, y = tuple(figure.scene.get_size())

    # Try to lift the window
    figure.scene._lift()
    if mode == 'rgb':
        out = tvtk.UnsignedCharArray()
        shape = (y, x, 3)
        pixel_getter = figure.scene.render_window.get_pixel_data
        pg_args = (0, 0, x - 1, y - 1, 1, out)

    elif mode == 'rgba':
        out = tvtk.FloatArray()
        shape = (y, x, 4)
        pixel_getter = figure.scene.render_window.get_rgba_pixel_data
        pg_args = (0, 0, x - 1, y - 1, 1, out)

    else:
        raise ValueError('mode type not understood')

    if antialiased:
        # save the current aa value to restore it later
        old_aa = figure.scene.render_window.aa_frames

        figure.scene.render_window.aa_frames = figure.scene.anti_aliasing_frames
        figure.scene.render()
        pixel_getter(*pg_args)
        figure.scene.render_window.aa_frames = old_aa
        figure.scene.render()

    else:
        pixel_getter(*pg_args)

    # Return the array in a way that pylab.imshow plots it right:
    out = out.to_array()
    out.shape = shape
    out = np.flipud(out)
    return out
Esempio n. 18
0
 def test_set_scalars(self):
     """Test if SetScalars works without a segfault."""
     mesh = tvtk.PolyData()
     sc = tvtk.FloatArray()
     # If this does not segfault, we are OK.
     mesh.point_data.scalars = sc