Пример #1
0
 def _calcValue(self):
     l = len(self.distribution)
     bins = self.mesh.cellCenters[0]
     n = numerix.searchsorted(numerix.sort(self.distribution), bins)
     n = numerix.concatenate([n, [l]])
     dx = bins[1:] - bins[:-1]
     return (n[1:] - n[:-1]) / numerix.concatenate([dx, [dx[-1]]]) / float(l)
Пример #2
0
    def run(self):
        MayaviDaemon._viewers.append(self)
        
        mlab.clf()

        bounds = zeros((0, 6), 'l')
        
        self.cellsource = self.setup_source(self.cellfname)
        if self.cellsource is not None:
            tmp = [out.cell_data.scalars for out in self.cellsource.outputs \
                   if out.cell_data.scalars is not None]
            self.has_cell_scalars = (len(tmp) > 0)
            tmp = [out.cell_data.vectors for out in self.cellsource.outputs \
                   if out.cell_data.vectors is not None]
            self.has_cell_vectors = (len(tmp) > 0)
            tmp = [out.cell_data.tensors for out in self.cellsource.outputs \
                   if out.cell_data.tensors is not None]
            self.has_cell_tensors = (len(tmp) > 0)

            bounds = concatenate((bounds, 
                                  [out.bounds for out in self.cellsource.outputs]),
                                 axis=0)


        self.facesource = self.setup_source(self.facefname)
        if self.facesource is not None:
            tmp = [out.point_data.scalars for out in self.facesource.outputs \
                   if out.point_data.scalars is not None]
            self.has_face_scalars = (len(tmp) > 0)
            tmp = [out.point_data.vectors for out in self.facesource.outputs \
                   if out.point_data.vectors is not None]
            self.has_face_vectors = (len(tmp) > 0)
            tmp = [out.point_data.tensors for out in self.facesource.outputs \
                   if out.point_data.tensors is not None]
            self.has_face_tensors = (len(tmp) > 0)
            
            bounds = concatenate((bounds, 
                                  [out.bounds for out in self.facesource.outputs]),
                                 axis=0)
                                 
        boundsmin = bounds.min(axis=0)
        boundsmax = bounds.max(axis=0)
        
        bounds = (boundsmin[0], boundsmax[1], 
                  boundsmin[2], boundsmax[3], 
                  boundsmin[4], boundsmax[5])

        self.bounds = where(self.bounds == array((None,)),
                            bounds, 
                            self.bounds).astype(float)

        self.view_data()

        # Poll the lock file.
        self.timer = Timer(1000 / self.fps, self.poll_file)
Пример #3
0
 def _getGlobalValue(self, localIDs, globalIDs):
     localValue = self.getValue()
     if self.getMesh().communicator.Nproc > 1:
         if localValue.shape[-1] != 0:
             localValue = localValue[..., localIDs]
         globalIDs = numerix.concatenate(self.getMesh().communicator.allgather(globalIDs))
         
         globalValue = numerix.empty(localValue.shape[:-1] + (max(globalIDs) + 1,), 
                                     dtype=numerix.obj2sctype(localValue))
         globalValue[..., globalIDs] = numerix.concatenate(self.getMesh().communicator.allgather(localValue), axis=-1)
         
         return globalValue
     else:
         return localValue
Пример #4
0
    def VTKFaceDataSet(self):
        """Returns a TVTK `DataSet` representing the face centers of this mesh
        """
        try:
            from tvtk.api import tvtk
        except ImportError as e:
            from enthought.tvtk.api import tvtk

        points = self.faceCenters
        points = self._toVTK3D(numerix.array(points))
        ug = tvtk.UnstructuredGrid(points=points)

        num = len(points)
        counts = numerix.array([1] * num)[..., numerix.newaxis]
        cells = numerix.arange(self.numberOfFaces)[..., numerix.newaxis]
        cells = numerix.concatenate((counts, cells), axis=1)
        cell_types = numerix.array([tvtk.Vertex().cell_type]*num)
        cell_array = tvtk.CellArray()
        cell_array.set_cells(num, cells)

        counts = numerix.array([1] * num)
        offset = numerix.cumsum(counts+1)
        if len(offset) > 0:
            offset -= offset[0]
        ug.set_cells(cell_types, offset, cell_array)

        return ug
Пример #5
0
    def _createFaces(self):
        """
        v1, v2 refer to the vertices.
        Horizontal faces are first
        """
        v1 = numerix.arange(self.numberOfVertices)
        v2 = v1 + 1

        horizontalFaces = vector.prune(numerix.array((v1, v2)), self.numberOfVerticalColumns, self.nx, axis=1)

        v1 = numerix.arange(self.numberOfVertices - self.numberOfVerticalColumns)
        v2 = v1 + self.numberOfVerticalColumns
        verticalFaces =  numerix.array((v1, v2))

        ## The cell normals must point out of the cell.
        ## The left and bottom faces have only one neighboring cell,
        ## in the 2nd neighbor position (there is nothing in the 1st).
        ## 
        ## reverse some of the face orientations to obtain the correct normals

        tmp = horizontalFaces.copy()
        horizontalFaces[0,:self.nx] = tmp[1,:self.nx]
        horizontalFaces[1,:self.nx] = tmp[0,:self.nx]

        self.numberOfHorizontalFaces = horizontalFaces.shape[-1]

        tmp = verticalFaces.copy()
        verticalFaces[0, :] = tmp[1, :]
        verticalFaces[1, :] = tmp[0, :]
        if self.numberOfVerticalColumns > 0:
            verticalFaces[0, ::self.numberOfVerticalColumns] = tmp[0, ::self.numberOfVerticalColumns]
            verticalFaces[1, ::self.numberOfVerticalColumns] = tmp[1,::self.numberOfVerticalColumns]

        return numerix.concatenate((horizontalFaces, verticalFaces), axis=1)
Пример #6
0
        def _adjacentCellIDs(self):
            Hids = numerix.zeros((self.numberOfHorizontalRows, self.nx, 2), 'l')
            indices = numerix.indices((self.numberOfHorizontalRows, self.nx))

            Hids[..., 1] = indices[1] + indices[0] * self.nx
            Hids[..., 0] = Hids[..., 1] - self.nx

            if self.numberOfHorizontalRows > 0:
                Hids[0, ..., 0] = Hids[0, ..., 1]
                Hids[0, ..., 1] = Hids[0, ..., 0]
                Hids[-1, ..., 1] = Hids[-1, ..., 0]

            Vids = numerix.zeros((self.ny, self.numberOfVerticalColumns, 2), 'l')
            indices = numerix.indices((self.ny, self.numberOfVerticalColumns))
            Vids[..., 1] = indices[1] + indices[0] * self.nx
            Vids[..., 0] = Vids[..., 1] - 1

            if self.numberOfVerticalColumns > 0:
                Vids[..., 0, 0] = Vids[..., 0, 1]
                Vids[..., 0, 1] = Vids[..., 0, 0]
                Vids[..., -1, 1] = Vids[..., -1, 0]

            faceCellIDs =  numerix.concatenate((numerix.reshape(Hids, (self.numberOfHorizontalFaces, 2)),
                                                numerix.reshape(Vids, (self.numberOfFaces - self.numberOfHorizontalFaces, 2))))

            return (faceCellIDs[:, 0], faceCellIDs[:, 1])
Пример #7
0
Файл: mesh.py Проект: regmi/fipy
    def getVTKCellDataSet(self):
        """Returns a TVTK `DataSet` representing the cells of this mesh
        """
        cvi = self._getOrderedCellVertexIDs().swapaxes(0,1)
        from fipy.tools import numerix
        if type(cvi) is numerix.ma.masked_array:
            counts = cvi.count(axis=1)[:,None]
            cells = numerix.ma.concatenate((counts,cvi),axis=1).compressed()
        else:
            counts = numerix.array([cvi.shape[1]]*cvi.shape[0])[:,None]
            cells = numerix.concatenate((counts,cvi),axis=1).flatten()
        
        from enthought.tvtk.api import tvtk
        num = counts.shape[0]

        cps_type = self._getVTKCellType()
        cell_types = numerix.array([cps_type]*num)
        cell_array = tvtk.CellArray()
        cell_array.set_cells(num, cells)

        points = self.getVertexCoords()
        points = self._toVTK3D(points)
        ug = tvtk.UnstructuredGrid(points=points)
        
        offset = numerix.cumsum(counts[:,0]+1)
        if len(offset) > 0:
            offset -= offset[0]
        ug.set_cells(cell_types, offset, cell_array)

        return ug
Пример #8
0
 def _getGlobalValue(self, localIDs, globalIDs):
     from fipy.tools import parallel
     localValue = self.getValue()
     if parallel.Nproc > 1:
         from mpi4py import MPI
         comm = MPI.COMM_WORLD
         if localValue.shape[-1] != 0:
             localValue = localValue[..., localIDs]
         globalIDs = numerix.concatenate(comm.allgather(globalIDs))
         
         globalValue = numerix.empty(localValue.shape[:-1] + (max(globalIDs) + 1,), 
                                     dtype=numerix.obj2sctype(localValue))
         globalValue[..., globalIDs] = numerix.concatenate(comm.allgather(localValue), axis=-1)
         
         return globalValue
     else:
         return localValue
Пример #9
0
    def _calcBaseFaceVertexIDs(self):
        
        cellVertexIDs = self.cellVertexIDs
    ## compute the face vertex IDs.
        ### this assumes triangular grid
        #cellFaceVertexIDs = numerix.ones((self.dimensions, self.dimensions + 1, self.numCells))
        cellFaceVertexIDs = numerix.ones((self.dimensions,len(cellVertexIDs), self.numCells))
        cellFaceVertexIDs = -1 * cellFaceVertexIDs

        if (self.dimensions == 3):
            cellFaceVertexIDs[:, 0, :] = cellVertexIDs[:3]
            cellFaceVertexIDs[:, 1, :] = numerix.concatenate((cellVertexIDs[:2], cellVertexIDs[3:]), axis = 0)
            cellFaceVertexIDs[:, 2, :] = numerix.concatenate((cellVertexIDs[:1], cellVertexIDs[2:]), axis = 0)
            cellFaceVertexIDs[:, 3, :] = cellVertexIDs[1:]
        elif (self.dimensions == 2):#define face with vertex pairs
            ###This isn't very general.
            ###Would be nice to allow cells with different number of faces. 
            if len(cellVertexIDs)==3:
                cellFaceVertexIDs[:, 0, :] = cellVertexIDs[:2]
                cellFaceVertexIDs[:, 1, :] = numerix.concatenate((cellVertexIDs[2:], cellVertexIDs[:1]), axis = 0)
                cellFaceVertexIDs[:, 2, :] = cellVertexIDs[1:]
            elif len(cellVertexIDs)==4:
                cellFaceVertexIDs[:, 0, :] = cellVertexIDs[0:2]
                cellFaceVertexIDs[:, 1, :] = cellVertexIDs[1:3]
                cellFaceVertexIDs[:, 2, :] = cellVertexIDs[2:4]
                cellFaceVertexIDs[:, 3, :] = numerix.concatenate((cellVertexIDs[3:], cellVertexIDs[:1]), axis = 0)

        cellFaceVertexIDs = cellFaceVertexIDs[::-1]#reverses order of vertex pair

        #self.unsortedBaseIDs = numerix.reshape(cellFaceVertexIDs.swapaxes(1,2), 
        #                                       (self.dimensions, 
        #                                        self.numCells * (self.dimensions + 1)))
        
        self.unsortedBaseIDs = numerix.reshape(cellFaceVertexIDs.swapaxes(1,2), 
                                               (self.dimensions, 
                                                self.numCells * (len(cellVertexIDs))))
        cellFaceVertexIDs = numerix.sort(cellFaceVertexIDs, axis=0)
        baseFaceVertexIDs = numerix.reshape(cellFaceVertexIDs.swapaxes(1,2), 
                                            (self.dimensions, 
                                             self.numCells * (len(cellVertexIDs))))

        self.baseFaceVertexIDs = baseFaceVertexIDs       
        self.cellFaceVertexIDs = cellFaceVertexIDs
Пример #10
0
Файл: mesh.py Проект: regmi/fipy
 def _toVTK3D(self, arr, rank=1):
     if arr.dtype.name is 'bool':
         # VTK can't do bool, and the exception isn't properly
         # thrown back to the user
         arr = arr.astype('int')
     if rank == 0:
         return arr
     else:
         arr = numerix.concatenate((arr, 
                                    numerix.zeros((3 - self.dim,) 
                                                  + arr.shape[1:])))
         return arr.swapaxes(-2, -1)
Пример #11
0
    def _exteriorFaces(self):
        """
        Return only the faces that have one neighboring cell.
        """
        exteriorIDs = numerix.concatenate((numerix.arange(0, self.nx),
                                           numerix.arange(0, self.nx) + self.nx * self.ny,
                                           numerix.arange(0, self.ny) * self.numberOfVerticalColumns + self.numberOfHorizontalFaces,
                                           numerix.arange(0, self.ny) * self.numberOfVerticalColumns + self.numberOfHorizontalFaces + self.nx))

        from fipy.variables.faceVariable import FaceVariable
        exteriorFaces = FaceVariable(mesh=self, value=False)
        exteriorFaces[exteriorIDs] = True
        return exteriorFaces
Пример #12
0
    def _faceTangents2(self):
        XYtan = numerix.zeros((3, self.nx, self.ny, self.nz + 1), 'l')
        XYtan[1, ...] =  1

        XZtan = numerix.zeros((3, self.nx, self.ny + 1, self.nz), 'l')
        XZtan[0, ...] =  1

        YZtan = numerix.zeros((3, self.nx + 1, self.ny, self.nz), 'l')
        YZtan[0, ...] =  1

        return numerix.concatenate((numerix.reshape(XYtan[::-1].swapaxes(1, 3), (3, self.numberOfXYFaces)),
                                    numerix.reshape(XZtan[::-1].swapaxes(1, 3), (3, self.numberOfXZFaces)),
                                    numerix.reshape(YZtan[::-1].swapaxes(1, 3), (3, self.numberOfYZFaces))), axis=1)
Пример #13
0
    def _createVertices(self):

        x = numerix.arange(self.nx + 1) * self.dx
        y = numerix.arange(self.ny + 1) * self.dy
        x = numerix.resize(x, (self.numberOfCornerVertices,))
        y = numerix.repeat(y, self.nx + 1)
        boxCorners = numerix.array((x, y))
        x = numerix.arange(0.5, self.nx + 0.5) * self.dx
        y = numerix.arange(0.5, self.ny + 0.5) * self.dy
        x = numerix.resize(x, (self.numberOfCenterVertices,))
        y = numerix.repeat(y, self.nx)
        boxCenters = numerix.array((x, y))
        return numerix.concatenate((boxCorners, boxCenters), axis=1)
Пример #14
0
 def getFaceCenters(self):
     Hcen = numerix.zeros((2, self.nx, self.numberOfHorizontalRows), 'd')
     indices = numerix.indices((self.nx, self.numberOfHorizontalRows))
     Hcen[0,...] = (indices[0] + 0.5) * self.dx
     Hcen[1,...] = indices[1] * self.dy
     
     Vcen = numerix.zeros((2, self.numberOfVerticalColumns, self.ny), 'd')
     indices = numerix.indices((self.numberOfVerticalColumns, self.ny))
     Vcen[0,...] = indices[0] * self.dx
     Vcen[1,...] = (indices[1] + 0.5) * self.dy
     
     return numerix.concatenate((Hcen.reshape((2, self.numberOfHorizontalFaces), order="FORTRAN"),
                                 Vcen.reshape((2, self.numberOfVerticalFaces), order="FORTRAN")), axis=1) + self.origin
Пример #15
0
    def _getFaceVertexIDs(self):
        Hids = numerix.zeros((2, self.nx, self.numberOfHorizontalRows))
        indices = numerix.indices((self.nx, self.numberOfHorizontalRows))
        Hids[0] = indices[0] + indices[1] * self.numberOfVerticalColumns
        Hids[1] = Hids[0] + 1

        Vids = numerix.zeros((2, self.numberOfVerticalColumns, self.ny))
        indices = numerix.indices((self.numberOfVerticalColumns, self.ny))
        Vids[0] = indices[0] + indices[1] * self.numberOfVerticalColumns
        Vids[1] = Vids[0] + self.numberOfVerticalColumns
        
        return numerix.concatenate((Hids.reshape((2, self.numberOfHorizontalFaces), order="FORTRAN"), 
                                    Vids.reshape((2, self.numberOfFaces - self.numberOfHorizontalFaces), order="FORTRAN")),
                                   axis=1)
Пример #16
0
 def _calcFaceNormals(self):
     XYFaceNormals = numerix.zeros((3, self.numberOfXYFaces))
     XYFaceNormals[2, (self.nx * self.ny) :] = 1
     XYFaceNormals[2, : (self.nx * self.ny)] = -1
     XZFaceNormals = numerix.zeros((3, self.numberOfXZFaces))
     xzd = numerix.arange(self.numberOfXZFaces)
     xzd = xzd % (self.nx * (self.ny + 1))
     xzd = xzd < self.nx
     xzd = 1 - (2 * xzd)
     XZFaceNormals[1, :] = xzd
     YZFaceNormals = numerix.zeros((3, self.numberOfYZFaces))
     YZFaceNormals[0, :] = 1
     YZFaceNormals[0, :: self.nx + 1] = -1
     self.faceNormals = numerix.concatenate((XYFaceNormals, XZFaceNormals, YZFaceNormals), axis=-1)
Пример #17
0
    def _cellDistances(self):
        Hdis = numerix.repeat((self.dy,), self.numberOfHorizontalFaces)
        Hdis = numerix.reshape(Hdis, (self.nx, self.numberOfHorizontalRows))
        if self.numberOfHorizontalRows > 0:
            Hdis[..., 0] = self.dy / 2.
            Hdis[..., -1] = self.dy / 2.

        Vdis = numerix.repeat((self.dx,), self.numberOfFaces - self.numberOfHorizontalFaces)
        Vdis = numerix.reshape(Vdis, (self.numberOfVerticalColumns, self.ny))
        if self.numberOfVerticalColumns > 0:
            Vdis[0, ...] = self.dx / 2.
            Vdis[-1, ...] = self.dx / 2.

        return numerix.concatenate((numerix.reshape(numerix.swapaxes(Hdis, 0, 1), (self.numberOfHorizontalFaces,)),
                                    numerix.reshape(numerix.swapaxes(Vdis, 0, 1), (self.numberOfFaces - self.numberOfHorizontalFaces,))))
Пример #18
0
    def _interiorFaces(self):
        """
        Return only the faces that have two neighboring cells
        """
        XYids = self._XYFaceIDs
        XZids = self._XZFaceIDs
        YZids = self._YZFaceIDs

        interiorIDs = numerix.concatenate((numerix.ravel(XYids[ ..., 1:-1]),
                                           numerix.ravel(XZids[:, 1:-1,:]),
                                           numerix.ravel(YZids[1:-1,       ...].swapaxes(0, 1))))

        from fipy.variables.faceVariable import FaceVariable
        interiorFaces = FaceVariable(mesh=self, value=False)
        interiorFaces[interiorIDs] = True
        return interiorFaces
Пример #19
0
    def faceNormals(self):
        XYnor = numerix.zeros((3, self.nx, self.ny, self.nz + 1), 'l')
        XYnor[0,     ...] =  1
        XYnor[0,  ..., 0] = -1

        XZnor = numerix.zeros((3, self.nx, self.ny + 1, self.nz), 'l')
        XZnor[1,     ...] =  1
        XZnor[1,:, 0,:] = -1

        YZnor = numerix.zeros((3, self.nx + 1, self.ny, self.nz), 'l')
        YZnor[2,     ...] =  1
        YZnor[2, 0,  ...] = -1

        return numerix.concatenate((numerix.reshape(XYnor[::-1].swapaxes(1, 3), (3, self.numberOfXYFaces)),
                                    numerix.reshape(XZnor[::-1].swapaxes(1, 3), (3, self.numberOfXZFaces)),
                                    numerix.reshape(YZnor[::-1].swapaxes(1, 3), (3, self.numberOfYZFaces))), axis=1)
Пример #20
0
 def getVTKCellDataSet(self):
     """Returns a TVTK `DataSet` representing the cells of this mesh
     """
     cvi = self._getOrderedCellVertexIDs().swapaxes(0,1)
     from fipy.tools import numerix
     if type(cvi) is numerix.ma.masked_array:
         counts = cvi.count(axis=1)[:,None]
         cells = numerix.ma.concatenate((counts,cvi),axis=1).compressed()
     else:
         counts = numerix.array([cvi.shape[1]]*cvi.shape[0])[:,None]
         cells = numerix.concatenate((counts,cvi),axis=1).flatten()
     
     try: 
         from tvtk.api import tvtk 
     except ImportError, e: 
         from enthought.tvtk.api import tvtk
Пример #21
0
    def _createFaces(self):
        """
        XY faces are first, then XZ faces, then YZ faces
        """
        ## do the XY faces
        v1 = numerix.arange((self.nx + 1) * (self.ny))
        v1 = vector.prune(v1, self.nx + 1, self.nx)
        v1 = self._repeatWithOffset(v1, (self.nx + 1) * (self.ny + 1), self.nz + 1) 
        v2 = v1 + 1
        v3 = v1 + (self.nx + 2)
        v4 = v1 + (self.nx + 1)
        XYFaces = numerix.array((v1, v2, v3, v4))

        ## do the XZ faces
        v1 = numerix.arange((self.nx + 1) * (self.ny + 1))
        v1 = vector.prune(v1, self.nx + 1, self.nx)
        v1 = self._repeatWithOffset(v1, (self.nx + 1) * (self.ny + 1), self.nz)
        v2 = v1 + 1
        v3 = v1 + ((self.nx + 1)*(self.ny + 1)) + 1
        v4 = v1 + ((self.nx + 1)*(self.ny + 1))
        XZFaces = numerix.array((v1, v2, v3, v4))
        
        ## do the YZ faces
        v1 = numerix.arange((self.nx + 1) * self.ny)
        v1 = self._repeatWithOffset(v1, (self.nx + 1) * (self.ny + 1), self.nz)
        v2 = v1 + (self.nx + 1)
        v3 = v1 + ((self.nx + 1)*(self.ny + 1)) + (self.nx + 1)                                  
        v4 = v1 + ((self.nx + 1)*(self.ny + 1))
        YZFaces = numerix.array((v1, v2, v3, v4))

        ## reverse some of the face orientations to obtain the correct normals
        ##tmp = horizontalFaces.copy()
        ##horizontalFaces[:self.nx, 0] = tmp[:self.nx, 1]
        ##horizontalFaces[:self.nx, 1] = tmp[:self.nx, 0]
        ##tmp = verticalFaces.copy()
        ##verticalFaces[:, 0] = tmp[:, 1]
        ##verticalFaces[:, 1] = tmp[:, 0]
        ##verticalFaces[::(self.nx + 1), 0] = tmp[::(self.nx + 1), 0]
        ##verticalFaces[::(self.nx + 1), 1] = tmp[::(self.nx + 1), 1]

        self.numberOfXYFaces = (self.nx * self.ny * (self.nz + 1))
        self.numberOfXZFaces = (self.nx * (self.ny + 1) * self.nz)
        self.numberOfYZFaces = ((self.nx + 1) * self.ny * self.nz)
        self.numberOfFaces = self.numberOfXYFaces + self.numberOfXZFaces + self.numberOfYZFaces
        
        return numerix.concatenate((XYFaces, XZFaces, YZFaces), axis=1)
Пример #22
0
        def faceCountsMatch(targetCounts):
            if len(targetCounts) > nodesPerFace.shape[0]:
                # pad nodesPerFace with zeros
                paddedNodesPerFace = numerix.zeros((len(targetCounts), nodesPerFace.shape[1]), dtype=numerix.INT_DTYPE)
                paddedNodesPerFace[:nodesPerFace.shape[0],:] = nodesPerFace

                paddedTargetCounts = numerix.array(targetCounts)[..., numerix.newaxis]
            else:
                # pad target face node count with zeros
                paddedTargetCounts = numerix.concatenate((targetCounts,
                                                          [0] * (self.mesh._maxFacesPerCell - len(targetCounts))))
                paddedTargetCounts = paddedTargetCounts[..., numerix.newaxis]

                paddedNodesPerFace = nodesPerFace

            return ((facesPerCell == len(targetCounts))
                    & (paddedNodesPerFace == paddedTargetCounts).all(axis=0))
Пример #23
0
    def _exteriorFaces(self):
        """
        Return only the faces that have one neighboring cell.
        """
        XYids = self._XYFaceIDs
        XZids = self._XZFaceIDs
        YZids = self._YZFaceIDs

        exteriorIDs = numerix.concatenate((numerix.ravel(XYids[...,      0].swapaxes(0, 1)),
                                           numerix.ravel(XYids[...,     -1].swapaxes(0, 1)),
                                           numerix.ravel(XZids[:,     0,:]),
                                           numerix.ravel(XZids[:,    -1,:]),
                                           numerix.ravel(YZids[ 0,     ...]),
                                           numerix.ravel(YZids[-1,     ...])))

        from fipy.variables.faceVariable import FaceVariable
        exteriorFaces = FaceVariable(mesh=self, value=False)
        exteriorFaces[exteriorIDs] = True
        return exteriorFaces
Пример #24
0
    def _cellDistances(self):
        XYdis = numerix.zeros((self.nz + 1, self.ny, self.nx), 'd')
        XYdis[:] = self.dz
        XYdis[ 0, ...] = self.dz / 2.
        XYdis[-1, ...] = self.dz / 2.

        XZdis = numerix.zeros((self.nz, self.ny + 1, self.nx), 'd')
        XZdis[:] = self.dy
        XZdis[:, 0,:] = self.dy / 2.
        XZdis[:, -1,:] = self.dy / 2.

        YZdis = numerix.zeros((self.nz, self.ny, self.nx + 1), 'd')
        YZdis[:] = self.dx
        YZdis[..., 0] = self.dx / 2.
        YZdis[..., -1] = self.dx / 2.

        return numerix.concatenate((numerix.ravel(XYdis),
                                    numerix.ravel(XZdis),
                                    numerix.ravel(YZdis)))
Пример #25
0
 def _faceToCellDistanceRatio(self):
     XYdis = numerix.zeros((self.nx, self.ny, self.nz + 1),'d')
     XYdis[:] = 0.5
     XYdis[..., 0] = 1
     XYdis[...,-1] = 1
     
     XZdis = numerix.zeros((self.nx, self.ny + 1, self.nz),'d')
     XZdis[:] = 0.5
     XZdis[..., 0,...] = 1
     XZdis[...,-1,...] = 1
     
     YZdis = numerix.zeros((self.nx + 1, self.ny, self.nz),'d')
     YZdis[:] = 0.5
     YZdis[ 0,...] = 1
     YZdis[-1,...] = 1
     
     return numerix.concatenate((numerix.ravel(XYdis.swapaxes(0,2)),
                                 numerix.ravel(XZdis.swapaxes(0,2)),
                                 numerix.ravel(YZdis.swapaxes(0,2))), axis=1)
Пример #26
0
    def _interiorFaces(self):
        """
        Return only the faces that have two neighboring cells.
        """
        Hids = numerix.arange(0, self.numberOfHorizontalFaces)
        Hids = numerix.reshape(Hids, (self.numberOfHorizontalRows, self.nx))
        Hids = Hids[1:-1, ...]

        Vids = numerix.arange(self.numberOfHorizontalFaces, self.numberOfFaces)
        Vids = numerix.reshape(Vids, (self.ny, self.numberOfVerticalColumns))
        Vids = Vids[..., 1:-1]

        interiorIDs = numerix.concatenate((numerix.reshape(Hids, (self.nx * (self.ny - 1),)),
                                           numerix.reshape(Vids, ((self.nx - 1) * self.ny,))))

        from fipy.variables.faceVariable import FaceVariable
        interiorFaces = FaceVariable(mesh=self, value=False)
        interiorFaces[interiorIDs] = True
        return interiorFaces
Пример #27
0
 def _createCells(self):
     """
     cells = (f1, f2, f3, f4) going anticlockwise.
     f1 etc. refer to the faces
     """
     bottomFaces = numerix.arange(0, self.numberOfHorizontalFaces - self.nx)
     topFaces = numerix.arange(self.nx, self.numberOfHorizontalFaces)
     leftFaces = vector.prune(numerix.arange(self.numberOfHorizontalFaces, self.numberOfHorizontalFaces + self.numberOfVerticalFaces), self.nx + 1, self.nx)
     rightFaces = vector.prune(numerix.arange(self.numberOfHorizontalFaces, self.numberOfHorizontalFaces + self.numberOfVerticalFaces), self.nx + 1, 0)
     lowerLeftDiagonalFaces = numerix.arange(self.numberOfHorizontalFaces + self.numberOfVerticalFaces, self.numberOfHorizontalFaces + self.numberOfVerticalFaces + self.numberOfEachDiagonalFaces)
     lowerRightDiagonalFaces = lowerLeftDiagonalFaces + self.numberOfEachDiagonalFaces
     upperLeftDiagonalFaces = lowerRightDiagonalFaces + self.numberOfEachDiagonalFaces
     upperRightDiagonalFaces = upperLeftDiagonalFaces + self.numberOfEachDiagonalFaces
     ##faces in arrays, now get the cells
     bottomOfBoxCells = numerix.array([bottomFaces, lowerRightDiagonalFaces, lowerLeftDiagonalFaces])
     rightOfBoxCells = numerix.array([rightFaces, upperRightDiagonalFaces, lowerRightDiagonalFaces])
     topOfBoxCells = numerix.array([topFaces, upperLeftDiagonalFaces, upperRightDiagonalFaces])
     leftOfBoxCells = numerix.array([leftFaces, lowerLeftDiagonalFaces, upperLeftDiagonalFaces])
     return numerix.concatenate((rightOfBoxCells, topOfBoxCells, leftOfBoxCells, bottomOfBoxCells), axis=1)
Пример #28
0
        def faceCellIDs(self):
            Hids = numerix.zeros((2, self.nx, self.numberOfHorizontalRows), 'l')
            indices = numerix.indices((self.nx, self.numberOfHorizontalRows))
            Hids[1] = indices[0] + indices[1] * self.nx
            Hids[0] = Hids[1] - self.nx
            if self.numberOfHorizontalRows > 0:
                Hids[0, ..., 0] = Hids[1, ..., 0]
                Hids[1, ..., 0] = -1
                Hids[1, ..., -1] = -1

            Vids = numerix.zeros((2, self.numberOfVerticalColumns, self.ny), 'l')
            indices = numerix.indices((self.numberOfVerticalColumns, self.ny))
            Vids[1] = indices[0] + indices[1] * self.nx
            Vids[0] = Vids[1] - 1
            if self.numberOfVerticalColumns > 0:
                Vids[0, 0] = Vids[1, 0]
                Vids[1, 0] = -1
                Vids[1, -1] = -1

            return MA.masked_values(numerix.concatenate((Hids.reshape((2, self.numberOfHorizontalFaces), order="FORTRAN"),
                                                         Vids.reshape((2, self.numberOfFaces - self.numberOfHorizontalFaces), order="FORTRAN")), axis=1), value = -1)
Пример #29
0
    def createFaces(nx, ny, nz):
        """
        XY faces are first, then XZ faces, then YZ faces
        """
        ## do the XY faces
        v1 = numerix.arange((nx + 1) * (ny))
        v1 = vector.prune(v1, nx + 1, nx)
        v1 = _Grid3DBuilder._repeatWithOffset(v1, (nx + 1) * (ny + 1), nz + 1)
        v2 = v1 + 1
        v3 = v1 + (nx + 2)
        v4 = v1 + (nx + 1)
        XYFaces = numerix.array((v1, v2, v3, v4))

        ## do the XZ faces
        v1 = numerix.arange((nx + 1) * (ny + 1))
        v1 = vector.prune(v1, nx + 1, nx)
        v1 = _Grid3DBuilder._repeatWithOffset(v1, (nx + 1) * (ny + 1), nz)
        v2 = v1 + 1
        v3 = v1 + ((nx + 1) * (ny + 1)) + 1
        v4 = v1 + ((nx + 1) * (ny + 1))
        XZFaces = numerix.array((v1, v2, v3, v4))

        ## do the YZ faces
        v1 = numerix.arange((nx + 1) * ny)
        v1 = _Grid3DBuilder._repeatWithOffset(v1, (nx + 1) * (ny + 1), nz)
        v2 = v1 + (nx + 1)
        v3 = v1 + ((nx + 1) * (ny + 1)) + (nx + 1)
        v4 = v1 + ((nx + 1) * (ny + 1))
        YZFaces = numerix.array((v1, v2, v3, v4))

        numberOfXYFaces = nx * ny * (nz + 1)
        numberOfXZFaces = nx * (ny + 1) * nz
        numberOfYZFaces = (nx + 1) * ny * nz
        numberOfFaces = numberOfXYFaces + numberOfXZFaces + numberOfYZFaces

        return (
            [numberOfXYFaces, numberOfXZFaces, numberOfYZFaces, numberOfFaces],
            numerix.concatenate((XYFaces, XZFaces, YZFaces), axis=1),
        )
Пример #30
0
    def _faceCenters(self):

        XYcen = numerix.zeros((3, self.nx, self.ny, self.nz + 1), 'd')
        indices = numerix.indices((self.nx, self.ny, self.nz + 1))
        XYcen[0] = (indices[0] + 0.5) * self.dx
        XYcen[1] = (indices[1] + 0.5) * self.dy
        XYcen[2] = indices[2] * self.dz

        XZcen = numerix.zeros((3, self.nx, self.ny + 1, self.nz), 'd')
        indices = numerix.indices((self.nx, self.ny + 1, self.nz))
        XZcen[0] = (indices[0] + 0.5) * self.dx
        XZcen[1] = indices[1] * self.dy
        XZcen[2] = (indices[2] + 0.5) * self.dz

        YZcen = numerix.zeros((3, self.nx + 1, self.ny, self.nz), 'd')
        indices = numerix.indices((self.nx + 1, self.ny, self.nz))
        YZcen[0] = indices[0] * self.dx
        YZcen[1] = (indices[1] + 0.5) * self.dy
        YZcen[2] = (indices[2] + 0.5) * self.dz

        return numerix.concatenate((numerix.reshape(XYcen.swapaxes(1, 3), (3, self.numberOfXYFaces)),
                                    numerix.reshape(XZcen.swapaxes(1, 3), (3, self.numberOfXZFaces)),
                                    numerix.reshape(YZcen.swapaxes(1, 3), (3, self.numberOfYZFaces))), axis=1) + self.origin
Пример #31
0
    def _getAddedMeshValues(self, other, resolution=1e-2):
        """Calculate the parameters to define a concatenation of `other` with `self`

        Parameters
        ----------
        other : ~fipy.meshes.mesh.Mesh
             The `Mesh` to concatenate with `self`
        resolution : float
            How close vertices have to be (relative to the smallest
            cell-to-cell distance in either mesh) to be considered the same

        Returns
        -------
        dict
            (`vertexCoords`, `faceVertexIDs`, `cellFaceIDs`) for the new mesh.
        """

        selfc = self._concatenableMesh
        otherc = other._concatenableMesh

        selfNumFaces = selfc.faceVertexIDs.shape[-1]
        selfNumVertices = selfc.vertexCoords.shape[-1]
        otherNumFaces = otherc.faceVertexIDs.shape[-1]
        otherNumVertices = otherc.vertexCoords.shape[-1]
        ## check dimensions
        if (selfc.vertexCoords.shape[0] != otherc.vertexCoords.shape[0]):
            raise MeshAdditionError("Dimensions do not match")

        ## compute vertex correlates


#         from fipy.tools.debug import PRINT
#         PRINT("selfNumFaces", selfNumFaces)
#         PRINT("otherNumFaces", otherNumVertices)
#         PRINT("selfNumVertices", selfNumVertices)
#         PRINT("otherNumVertices", otherNumVertices)
#
#         from fipy.tools.debug import PRINT
#         from fipy.tools.debug import PRINT
#         PRINT("otherExt", otherc.exteriorFaces.value)
#         raw_input()
#         PRINT("selfExt", selfc.exteriorFaces.value)
#
#         PRINT("self filled", selfc.faceVertexIDs.filled())
#         PRINT("othe filled", otherc.faceVertexIDs.filled())
#         raw_input()
#
#         PRINT("selfc.faceVertexIDs.filled()\n",selfc.faceVertexIDs.filled())
#         PRINT("flat\n",selfc.faceVertexIDs.filled()[...,
#             selfc.exteriorFaces.value].flatten())
#         PRINT("selfc.exteriorFaces.value\n",selfc.exteriorFaces.value)
#         PRINT("extfaces type", type(selfc.exteriorFaces))
#         PRINT("extfaces mesh", selfc.exteriorFaces.mesh)

## only try to match along the operation manifold
        if hasattr(self, "opManifold"):
            self_faces = self.opManifold(selfc)
        else:
            self_faces = selfc.exteriorFaces.value
        if hasattr(other, "opManifold"):
            other_faces = other.opManifold(otherc)
        else:
            other_faces = otherc.exteriorFaces.value

        ## only try to match exterior (X) vertices
        self_Xvertices = numerix.unique(
            selfc.faceVertexIDs.filled()[..., self_faces].flatten())
        other_Xvertices = numerix.unique(
            otherc.faceVertexIDs.filled()[..., other_faces].flatten())

        self_XvertexCoords = selfc.vertexCoords[..., self_Xvertices]
        other_XvertexCoords = otherc.vertexCoords[..., other_Xvertices]

        closest = numerix.nearest(self_XvertexCoords, other_XvertexCoords)

        # just because they're closest, doesn't mean they're close
        tmp = self_XvertexCoords[..., closest] - other_XvertexCoords
        distance = numerix.sqrtDot(tmp, tmp)
        # only want vertex pairs that are 100x closer than the smallest
        # cell-to-cell distance
        close = distance < resolution * min(selfc._cellToCellDistances.min(),
                                            otherc._cellToCellDistances.min())
        vertexCorrelates = numerix.array(
            (self_Xvertices[closest[close]], other_Xvertices[close]))

        # warn if meshes don't touch, but allow it
        if (selfc._numberOfVertices > 0 and otherc._numberOfVertices > 0
                and vertexCorrelates.shape[-1] == 0):
            import warnings
            warnings.warn("Vertices are not aligned",
                          UserWarning,
                          stacklevel=4)

        ## compute face correlates

        # ensure that both sets of faceVertexIDs have the same maximum number of (masked) elements
        self_faceVertexIDs = selfc.faceVertexIDs
        other_faceVertexIDs = otherc.faceVertexIDs

        diff = self_faceVertexIDs.shape[0] - other_faceVertexIDs.shape[0]
        if diff > 0:
            other_faceVertexIDs = numerix.append(
                other_faceVertexIDs,
                -1 * numerix.ones(
                    (diff, ) + other_faceVertexIDs.shape[1:], 'l'),
                axis=0)
            other_faceVertexIDs = MA.masked_values(other_faceVertexIDs, -1)
        elif diff < 0:
            self_faceVertexIDs = numerix.append(
                self_faceVertexIDs,
                -1 * numerix.ones(
                    (-diff, ) + self_faceVertexIDs.shape[1:], 'l'),
                axis=0)
            self_faceVertexIDs = MA.masked_values(self_faceVertexIDs, -1)

        # want self's Faces for which all faceVertexIDs are in vertexCorrelates
        self_matchingFaces = numerix.in1d(
            self_faceVertexIDs, vertexCorrelates[0]).reshape(
                self_faceVertexIDs.shape).all(axis=0).nonzero()[0]

        # want other's Faces for which all faceVertexIDs are in vertexCorrelates
        other_matchingFaces = numerix.in1d(
            other_faceVertexIDs, vertexCorrelates[1]).reshape(
                other_faceVertexIDs.shape).all(axis=0).nonzero()[0]

        # map other's Vertex IDs to new Vertex IDs,
        # accounting for overlaps with self's Vertex IDs
        vertex_map = numerix.empty(otherNumVertices, dtype=numerix.INT_DTYPE)
        verticesToAdd = numerix.delete(numerix.arange(otherNumVertices),
                                       vertexCorrelates[1])
        vertex_map[verticesToAdd] = numerix.arange(
            otherNumVertices - len(vertexCorrelates[1])) + selfNumVertices
        vertex_map[vertexCorrelates[1]] = vertexCorrelates[0]

        # calculate hashes of faceVertexIDs for comparing Faces

        if self_matchingFaces.shape[-1] == 0:
            self_faceHash = numerix.empty(self_matchingFaces.shape[:-1] +
                                          (0, ),
                                          dtype="str")
        else:
            # sort each of self's Face's vertexIDs for canonical comparison
            self_faceHash = numerix.sort(
                self_faceVertexIDs[..., self_matchingFaces], axis=0)
            # then hash the Faces for comparison (NumPy set operations are only for 1D arrays)
            self_faceHash = numerix.apply_along_axis(str,
                                                     axis=0,
                                                     arr=self_faceHash)

        face_sort = numerix.argsort(self_faceHash)
        self_faceHash = self_faceHash[face_sort]
        self_matchingFaces = self_matchingFaces[face_sort]

        if other_matchingFaces.shape[-1] == 0:
            other_faceHash = numerix.empty(other_matchingFaces.shape[:-1] +
                                           (0, ),
                                           dtype="str")
        else:
            # convert each of other's Face's vertexIDs to new IDs
            other_faceHash = vertex_map[other_faceVertexIDs[
                ..., other_matchingFaces]]
            # sort each of other's Face's vertexIDs for canonical comparison
            other_faceHash = numerix.sort(other_faceHash, axis=0)
            # then hash the Faces for comparison (NumPy set operations are only for 1D arrays)
            other_faceHash = numerix.apply_along_axis(str,
                                                      axis=0,
                                                      arr=other_faceHash)

        face_sort = numerix.argsort(other_faceHash)
        other_faceHash = other_faceHash[face_sort]
        other_matchingFaces = other_matchingFaces[face_sort]

        self_matchingFaces = self_matchingFaces[numerix.in1d(
            self_faceHash, other_faceHash)]
        other_matchingFaces = other_matchingFaces[numerix.in1d(
            other_faceHash, self_faceHash)]

        faceCorrelates = numerix.array(
            (self_matchingFaces, other_matchingFaces))

        # warn if meshes don't touch, but allow it
        if (selfc.numberOfFaces > 0 and otherc.numberOfFaces > 0
                and faceCorrelates.shape[-1] == 0):
            import warnings
            warnings.warn("Faces are not aligned", UserWarning, stacklevel=4)

        # map other's Face IDs to new Face IDs,
        # accounting for overlaps with self's Face IDs
        face_map = numerix.empty(otherNumFaces, dtype=numerix.INT_DTYPE)
        facesToAdd = numerix.delete(numerix.arange(otherNumFaces),
                                    faceCorrelates[1])
        face_map[facesToAdd] = numerix.arange(
            otherNumFaces - len(faceCorrelates[1])) + selfNumFaces
        face_map[faceCorrelates[1]] = faceCorrelates[0]

        other_faceVertexIDs = vertex_map[otherc.faceVertexIDs[..., facesToAdd]]

        # ensure that both sets of cellFaceIDs have the same maximum number of (masked) elements
        self_cellFaceIDs = selfc.cellFaceIDs
        other_cellFaceIDs = face_map[otherc.cellFaceIDs]
        diff = self_cellFaceIDs.shape[0] - other_cellFaceIDs.shape[0]
        if diff > 0:
            other_cellFaceIDs = numerix.append(
                other_cellFaceIDs,
                -1 * numerix.ones((diff, ) + other_cellFaceIDs.shape[1:], 'l'),
                axis=0)
            other_cellFaceIDs = MA.masked_values(other_cellFaceIDs, -1)
        elif diff < 0:
            self_cellFaceIDs = numerix.append(
                self_cellFaceIDs,
                -1 * numerix.ones((-diff, ) + self_cellFaceIDs.shape[1:], 'l'),
                axis=0)
            self_cellFaceIDs = MA.masked_values(self_cellFaceIDs, -1)

        # concatenate everything and return
        return {
            'vertexCoords':
            numerix.concatenate(
                (selfc.vertexCoords, otherc.vertexCoords[..., verticesToAdd]),
                axis=1),
            'faceVertexIDs':
            numerix.concatenate((self_faceVertexIDs, other_faceVertexIDs),
                                axis=1),
            'cellFaceIDs':
            MA.concatenate((self_cellFaceIDs, other_cellFaceIDs), axis=1)
        }
Пример #32
0
 def _getValue(self):
     return numerix.concatenate(
         [numerix.array(var.value) for var in self.vars])
Пример #33
0
 def __getitem__(self, index):
     return numerix.concatenate(
         [numerix.array(var[index]) for var in self.vars])
Пример #34
0
    def VTKFaceDataSet(self):
        """Returns a TVTK `DataSet` representing the face centers of this mesh
        """
        try:
            from tvtk.api import tvtk
        except ImportError, e:
            from enthought.tvtk.api import tvtk

        points = self.faceCenters
        points = self._toVTK3D(numerix.array(points))
        ug = tvtk.UnstructuredGrid(points=points)

        num = len(points)
        counts = numerix.array([1] * num)[..., numerix.newaxis]
        cells = numerix.arange(self.numberOfFaces)[..., numerix.newaxis]
        cells = numerix.concatenate((counts, cells), axis=1)
        cell_types = numerix.array([tvtk.Vertex().cell_type] * num)
        cell_array = tvtk.CellArray()
        cell_array.set_cells(num, cells)

        counts = numerix.array([1] * num)
        offset = numerix.cumsum(counts + 1)
        if len(offset) > 0:
            offset -= offset[0]
        ug.set_cells(cell_types, offset, cell_array)

        return ug

    def _toVTK3D(self, arr, rank=1):
        if arr.dtype.name is 'bool':
            # VTK can't do bool, and the exception isn't properly
Пример #35
0
    def _extrude(self, mesh, extrudeFunc, layers):
        ## should extrude self rather than creating a new mesh?

        ## the following allows the 2D mesh to be in 3D space, this can be the case for a
        ## Gmsh2DIn3DSpace which would then be extruded.
        oldVertices = mesh.vertexCoords
        if oldVertices.shape[0] == 2:
            oldVertices = numerix.resize(oldVertices, (3, len(oldVertices[0])))
            oldVertices[2] = 0

        NCells = mesh.numberOfCells
        NFac = mesh.numberOfFaces
        NFacPerCell =  mesh._maxFacesPerCell

        ## set up the initial data arrays
        new_shape = (max(NFacPerCell, 4), (1 + layers)*NCells + layers*NFac)
        faces = numerix.MA.masked_values(-numerix.ones(new_shape, 'l'), value = -1)
        orderedVertices = mesh._orderedCellVertexIDs
        faces[:NFacPerCell, :NCells] = orderedVertices
        vertices = oldVertices
        vert0 = mesh.faceVertexIDs
        faceCount = NCells

        for layer in range(layers):

            ## need this later
            initialFaceCount = faceCount

            ## build the vertices
            newVertices = extrudeFunc(oldVertices)
            vertices = numerix.concatenate((vertices, newVertices), axis=1)

            ## build the faces along the layers
            faces[:NFacPerCell, faceCount: faceCount + NCells] = orderedVertices + len(oldVertices[0]) * (layer + 1)
            try:
                # numpy 1.1 doesn't copy right side before assigning slice
                # See: http://www.mail-archive.com/[email protected]/msg09843.html
                faces[:NFacPerCell, faceCount: faceCount + NCells] = faces[:NFacPerCell, faceCount: faceCount + NCells][::-1,:].copy()
            except:
                faces[:NFacPerCell, faceCount: faceCount + NCells] = faces[:NFacPerCell, faceCount: faceCount + NCells][::-1,:]

            faceCount = faceCount + NCells

            vert1 = (vert0 + len(oldVertices[0]))[::-1,:]

            ## build the faces between the layers
            faces[:4, faceCount: faceCount + NFac] = numerix.concatenate((vert0, vert1), axis = 0)[::-1,:]

            vert0 = vert0 + len(oldVertices[0])

            NCells = mesh.numberOfCells


            ## build the cells, the first layer has slightly different ordering
            if layer == 0:
                c0 =  numerix.reshape(numerix.arange(NCells), (1, NCells))
                cells = numerix.concatenate((c0, c0 + NCells, mesh.cellFaceIDs + 2 * NCells), axis = 0)
            else:
                newCells = numerix.concatenate((c0, c0 + initialFaceCount, mesh.cellFaceIDs + faceCount), axis=0)
                newCells[0] = cells[1, -NCells:]
                cells = numerix.concatenate((cells, newCells), axis=1)

            ## keep a count of things for the next layer
            faceCount = faceCount + NFac
            oldVertices = newVertices

        ## return a new mesh, extrude could just as easily act on self
        return Mesh(vertices, faces, cells, communicator=mesh.communicator)
Пример #36
0
    def _getStructure(self):

        ##maxX = self.distanceVar.mesh.faceCenters[0].max()
        ##minX = self.distanceVar.mesh.faceCenters[0].min()

        IDs = numerix.nonzero(self.distanceVar._cellInterfaceFlag)[0]
        coordinates = numerix.take(
            numerix.array(self.distanceVar.mesh.cellCenters).swapaxes(0, 1),
            IDs)

        coordinates -= numerix.take(
            numerix.array(self.distanceVar.grad * self.distanceVar).swapaxes(
                0, 1), IDs)

        coordinates *= self.zoomFactor

        shiftedCoords = coordinates.copy()
        shiftedCoords[:, 0] = -coordinates[:, 0]  ##+ (maxX - minX)
        coordinates = numerix.concatenate((coordinates, shiftedCoords))

        from .lines import _getOrderedLines

        lines = _getOrderedLines(
            list(range(2 * len(IDs))),
            coordinates,
            thresholdDistance=self.distanceVar.mesh._cellDistances.min() * 10)

        data = numerix.take(self.surfactantVar, IDs)

        data = numerix.concatenate((data, data))

        tmpIDs = numerix.nonzero(data > 0.0001)[0]
        if len(tmpIDs) > 0:
            val = numerix.take(data, tmpIDs).min()
        else:
            val = 0.0001

        data = numerix.where(data < 0.0001, val, data)

        for line in lines:
            if len(line) > 2:
                for smooth in range(self.smooth):
                    for arr in (coordinates, data):
                        tmp = numerix.take(arr, line)
                        tmp[1:-1] = tmp[2:] * 0.25 + tmp[:-2] * 0.25 + tmp[
                            1:-1] * 0.5
                        if len(arr.shape) > 1:
                            for i in range(len(arr[0])):
                                arrI = arr[:, i].copy()
                                numerix.put(arrI, line, tmp[:, i])
                                arr[:, i] = arrI
                        else:
                            numerix.put(arrI, line, tmp)

        name = self.title
        name = name.strip()
        if name == '':
            name = None

        coords = numerix.zeros((coordinates.shape[0], 3), 'd')
        coords[:, :coordinates.shape[1]] = coordinates

        import pyvtk

        ## making lists as pyvtk doesn't know what to do with numpy arrays

        coords = list(coords)
        coords = [[float(coord[0]),
                   float(coord[1]),
                   float(coord[2])] for coord in coords]

        data = list(data)
        data = [float(item) for item in data]

        return (pyvtk.UnstructuredGrid(points=coords, poly_line=lines),
                pyvtk.PointData(pyvtk.Scalars(data, name=name)))
    def plot(self, filename=None):
        """
        "plot" the coordinates and values of the variables to `filename`. 
        If `filename` is not provided, "plots" to stdout.
        
        >>> from fipy.meshes import Grid1D
        >>> m = Grid1D(nx = 3, dx = 0.4)
        >>> from fipy.variables.cellVariable import CellVariable
        >>> v = CellVariable(mesh = m, name = "var", value = (0, 2, 5))
        >>> TSVViewer(vars = (v, v.grad)).plot() #doctest: +NORMALIZE_WHITESPACE
        x       var     var_gauss_grad_x
        0.2     0       2.5
        0.6     2       6.25
        1       5       3.75
        
        >>> from fipy.meshes import Grid2D
        >>> m = Grid2D(nx = 2, dx = .1, ny = 2, dy = 0.3)
        >>> v = CellVariable(mesh = m, name = "var", value = (0, 2, -2, 5))
        >>> TSVViewer(vars = (v, v.grad)).plot() #doctest: +NORMALIZE_WHITESPACE
        x       y       var     var_gauss_grad_x        var_gauss_grad_y
        0.05    0.15    0       10      -3.33333333333333
        0.15    0.15    2       10      5
        0.05    0.45    -2      35      -3.33333333333333
        0.15    0.45    5       35      5
        
        :Parameters:
          filename
            If not `None`, the name of a file to save the image into.
        """

        mesh = self.vars[0].mesh
        dim = mesh.dim

        if filename is not None:
            import os
            if mesh.communicator.procID == 0:
                if os.path.splitext(filename)[1] == ".gz":
                    import gzip
                    f = gzip.GzipFile(filename=filename,
                                      mode='w',
                                      fileobj=None)
                else:
                    f = open(filename, "w")
            else:
                f = open(os.devnull, mode='w')
        else:
            f = sys.stdout

        if self.title and len(self.title) > 0:
            f.write(self.title)
            f.write("\n")

        headings = []
        for index in range(dim):
            headings.extend(self._axis[index])

        for var in self.vars:
            name = var.name
            if (isinstance(var, CellVariable)
                    or isinstance(var, FaceVariable)) and var.rank == 1:
                for index in range(dim):
                    headings.extend(["%s_%s" % (name, self._axis[index])])
            else:
                headings.extend([name])

        f.write("\t".join(headings))
        f.write("\n")

        cellVars = [var for var in self.vars if isinstance(var, CellVariable)]
        faceVars = [var for var in self.vars if isinstance(var, FaceVariable)]

        if len(cellVars) > 0:
            values = mesh.cellCenters.globalValue
            for var in self.vars:
                if isinstance(var, CellVariable) and var.rank == 1:
                    values = numerix.concatenate(
                        (values, numerix.array(var.globalValue)))
                else:
                    values = numerix.concatenate(
                        (values, (numerix.array(var.globalValue), )))

            self._plot(values, f, dim)

        if len(faceVars) > 0:
            values = mesh.faceCenters.globalValue
            for var in self.vars:
                if isinstance(var, FaceVariable) and var.rank == 1:
                    values = numerix.concatenate(
                        (values, numerix.array(var.globalValue)))
                else:
                    values = numerix.concatenate(
                        (values, (numerix.array(var.globalValue), )))

            self._plot(values, f, dim)

        if f is not sys.stdout:
            f.close()
Пример #38
0
 def globalValue(self):
     return numerix.concatenate(
         [numerix.array(var.globalValue) for var in self.vars])
Пример #39
0
    def plot(self, matrix, RHSvector, log='auto'):
        import tempfile
        import os

        if "print" in os.environ['FIPY_DISPLAY_MATRIX'].lower().split():
            print("-" * 75)
            print(self.title)
            print("-" * 75)
            print("L:")
            print(matrix)
            print("b:", RHSvector)

        (f, mtxName) = tempfile.mkstemp(suffix='.mtx')
        matrix.exportMmf(mtxName)
        mtx = mmio.mmread(mtxName)
        os.remove(mtxName)

        pyplot.ion()

        c = mtx.tocoo()
        y = c.row
        x = c.col
        z = c.data
        N = matrix._shape[0]

        b = RHSvector
        if numerix.shape(b) == ():
            b = numerix.zeros((N, ), 'l')

        if len(z) == 0:
            y = numerix.zeros((1, ), 'l')
            x = numerix.zeros((1, ), 'l')
            z = numerix.zeros((1, ), 'l')

        def signed_to_logs(v):
            return (numerix.where(v > 0, numerix.log10(v), numerix.nan),
                    numerix.where(v < 0, numerix.log10(-v), numerix.nan))

        def logs_to_signed(v, plus, minus):
            v = numerix.where(v > 0, plus, -minus)
            v = numerix.where(numerix.isnan(v), 0., v)

            return v

        zPlus, zMinus = signed_to_logs(z)
        bPlus, bMinus = signed_to_logs(b)

        logs = (zPlus, zMinus, bPlus, bMinus)

        log = ((log == True)
               or (log == 'auto' and
                   (numerix.nanmax(numerix.concatenate(logs)) -
                    numerix.nanmin(numerix.concatenate(logs)) > 2)))

        if log:
            zMin = numerix.nanmin(numerix.concatenate(logs))
            zMax = numerix.nanmax(numerix.concatenate(logs))

            zMin -= 0.5

            numdec = numerix.floor(zMax) - numerix.ceil(zMin)
            if numdec < 0:
                zMax += 0.5

            for v in logs:
                v -= zMin

            zRange = zMax - zMin

            if zRange == 0:
                zRange = numerix.nanmax(zPlus) + 1

            z = logs_to_signed(z, zPlus, zMinus)
            b = logs_to_signed(b, bPlus, bMinus)

            fmt = SignedLogFormatter(threshold=zMin)
            loc = SignedLogLocator(threshold=zMin)

        else:
            zRange = max(abs(numerix.concatenate((z, b))))

            if zRange == 0:
                zRange = 1

            fmt = None
            loc = None

        pyplot.ioff()

        fig = pyplot.figure(self.id)
        fig.clf()

        usetex = rcParams['text.usetex']
        rcParams['text.usetex'] = False

        cmap = cm.RdBu

        norm = Normalize(vmin=-zRange, vmax=zRange)

        x0 = self.margin
        L_ax = fig.add_axes([
            x0 / self.aspect, self.margin, self.L_width / self.aspect,
            self.L_width
        ])
        L_ax.text(0.5,
                  -0.1,
                  "L",
                  transform=L_ax.transAxes,
                  horizontalalignment='center',
                  verticalalignment='baseline')

        x0 += self.L_width + self.buffer
        c_ax = fig.add_axes([
            x0 / self.aspect, self.margin, self.c_width / self.aspect,
            self.L_width
        ])

        x0 += self.c_width + self.buffer
        b_ax = fig.add_axes([
            x0 / self.aspect, self.margin, self.b_width / self.aspect,
            self.L_width
        ],
                            sharey=L_ax)
        b_ax.text(0.5,
                  -0.1,
                  "b",
                  transform=b_ax.transAxes,
                  horizontalalignment='center',
                  verticalalignment='baseline')

        def scatterRectangles(x, y, z, norm=None, cmap=None):
            patches = [
                Rectangle(numerix.array([X - 0.5, Y - 0.5]),
                          1.,
                          1.,
                          edgecolor='none') for X, Y in zip(x, y)
            ]

            collection = PatchCollection(patches,
                                         norm=norm,
                                         cmap=cmap,
                                         edgecolors='none')
            collection.set_array(z)

            return collection

        L_ax.add_collection(
            scatterRectangles(x=x, y=y, z=z, norm=norm, cmap=cmap))

        b_ax.add_collection(
            scatterRectangles(x=numerix.zeros((N, ), 'l'),
                              y=numerix.arange(N),
                              z=b,
                              norm=norm,
                              cmap=cmap))

        ColorbarBase(ax=c_ax,
                     cmap=cmap,
                     norm=norm,
                     orientation='vertical',
                     format=fmt,
                     ticks=loc)

        pyplot.setp((b_ax.get_xticklabels(), b_ax.get_yticklabels(),
                     b_ax.get_xticklines(), b_ax.get_yticklines()),
                    visible=False)

        L_ax.set_xlim(xmin=-0.5, xmax=N - 0.5)
        L_ax.set_ylim(ymax=-0.5, ymin=N - 0.5)

        b_ax.set_xlim(xmin=-0.5, xmax=0.5)
        b_ax.set_ylim(ymax=-0.5, ymin=N - 0.5)

        fig.suptitle(self.title, x=0.5, y=0.95, fontsize=14)

        pyplot.draw()

        rcParams['text.usetex'] = usetex
Пример #40
0
 def _faceAreas(self):
     return numerix.concatenate(
         (numerix.repeat((self.dx * self.dy, ), self.numberOfXYFaces),
          numerix.repeat((self.dx * self.dz, ), self.numberOfXZFaces),
          numerix.repeat((self.dy * self.dz, ), self.numberOfYZFaces)))
Пример #41
0
 def numericValue(self):
     return numerix.concatenate([var.numericValue for var in self.vars])
Пример #42
0
        ####
        if(len(organGr) > 1):
            pl.setCWGr(organGr ) 
        pl.simulate(timeSinceLastLeuning/(60*60*24) , False) #time span in days
        
        phl = PhloemFluxPython(pl)
        segs = pl.getPolylines() #segments regrouped per organ
        ####
        #
        # xylem
        #
        ####
        
        nodes = phl.get_nodes()
        tiproots, tipstem, tipleaf = phl.get_organ_nodes_tips() #end node of end segment of each organ
        node_tips = np.concatenate((tiproots, tipstem, tipleaf))
        tiproots, tipstem, tipleaf = phl.get_organ_segments_tips() #end segment of each organ
        seg_tips = np.concatenate((tiproots, tipstem, tipleaf))


        phl.setKr([[kr],[kr_stem],[gmax]]) #att: check units
        phl.setKx([[kz]])
        phl.airPressure = p_a

        phl.seg_ind = seg_tips # segment indices for Neumann b.c.
        phl.node_ind = node_tips
        rx = phl.solve_leuning( sim_time = dt,sxx=[p_s], cells = True, Qlight = Q,VPD = VPD,
            Tl = TairK,p_linit = p_s,ci_init = cs,cs=cs, soil_k = [], log = False)
        fluxes = phl.radial_fluxes(timeSinceLastLeuning/(60*60*24), rx, [p_s], k_soil, True)  # cm3/day
        
        timeSinceLastLeuning  = 0