Exemplo n.º 1
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
Exemplo n.º 2
0
    def _getWeight(self, var, transientGeomCoeff=None, diffusionGeomCoeff=None):
        """
        Test for a bug due to the sign operator not being updating
        correctly.

            >>> from fipy import *
            >>> m = Grid1D(nx=1)
            >>> v = CellVariable(mesh=m, value=1.)
            >>> eq = TransientTerm() == ImplicitSourceTerm(v)
            >>> eq.solve(v, dt=1.)
            >>> print(v)
            [ 2.]
            >>> v.setValue(-1.)
            >>> eq.solve(v, dt=1.)
            >>> print(v)
            [-0.5]

        """

        coeff = self._getGeomCoeff(var)
        diagonalSign = self._getDiagonalSign(transientGeomCoeff, diffusionGeomCoeff)
        combinedSign = numerix.array(diagonalSign)[..., numerix.newaxis] * numerix.sign(coeff)

        return {'diagonal' : (combinedSign >= 0),
                'old value' : numerix.zeros(var.shape, 'd'),
                'b vector' :  -var * (combinedSign < 0),
                'new value' : numerix.zeros(var.shape, 'd')}
Exemplo n.º 3
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])
Exemplo n.º 4
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])
Exemplo n.º 5
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)
Exemplo n.º 6
0
    def _buildMatrix(self, var, SparseMatrix, boundaryConditions=(), dt=None, equation=None, transientGeomCoeff=None, diffusionGeomCoeff=None):

        oldArray = var.old

        mesh = var.mesh
        NCells = mesh.numberOfCells
        NCellFaces = mesh._maxFacesPerCell

        cellValues = numerix.repeat(oldArray[numerix.newaxis, ...], NCellFaces, axis = 0)

        cellIDs = numerix.repeat(numerix.arange(NCells)[numerix.newaxis, ...], NCellFaces, axis = 0)
        cellToCellIDs = mesh._cellToCellIDs

        if NCells > 0:
            cellToCellIDs = MA.where(MA.getmask(cellToCellIDs), cellIDs, cellToCellIDs) 

            adjacentValues = numerix.take(oldArray, cellToCellIDs)

            differences = self._getDifferences(adjacentValues, cellValues, oldArray, cellToCellIDs, mesh)
            differences = MA.filled(differences, 0)

            minsq = numerix.sqrt(numerix.sum(numerix.minimum(differences, numerix.zeros((NCellFaces, NCells), 'l'))**2, axis=0))
            maxsq = numerix.sqrt(numerix.sum(numerix.maximum(differences, numerix.zeros((NCellFaces, NCells), 'l'))**2, axis=0))

            coeff = numerix.array(self._getGeomCoeff(var))

            coeffXdiffereneces = coeff * ((coeff > 0.) * minsq + (coeff < 0.) * maxsq)
        else:
            coeffXdiffereneces = 0.

        return (var, SparseMatrix(mesh=var.mesh), -coeffXdiffereneces * mesh.cellVolumes)
Exemplo n.º 7
0
    def _getWeight(self,
                   var,
                   transientGeomCoeff=None,
                   diffusionGeomCoeff=None):
        """
        Test for a bug due to the sign operator not being updating
        correctly.

            >>> from fipy import *
            >>> m = Grid1D(nx=1)
            >>> v = CellVariable(mesh=m, value=1.)
            >>> eq = TransientTerm() == ImplicitSourceTerm(v)
            >>> eq.solve(v, dt=1.)
            >>> print v
            [ 2.]
            >>> v.setValue(-1.)
            >>> eq.solve(v, dt=1.)
            >>> print v
            [-0.5]

        """

        coeff = self._getGeomCoeff(var)
        diagonalSign = self._getDiagonalSign(transientGeomCoeff,
                                             diffusionGeomCoeff)
        combinedSign = numerix.array(diagonalSign)[
            ..., numerix.newaxis] * numerix.sign(coeff)

        return {
            'diagonal': (combinedSign >= 0),
            'old value': numerix.zeros(var.shape, 'd'),
            'b vector': -var * (combinedSign < 0),
            'new value': numerix.zeros(var.shape, 'd')
        }
Exemplo n.º 8
0
        def _explicitBuildMatrixInline_(self, oldArray, id1, id2, b, coeffMatrix, mesh, interiorFaces, dt, weight):

            oldArrayId1, oldArrayId2 = self._getOldAdjacentValues(oldArray, id1, id2, dt)
            coeff = numerix.array(self._getGeomCoeff(oldArray))
            Nfac = mesh.numberOfFaces

            cell1Diag = numerix.zeros((Nfac,), 'd')
            cell1Diag[:] = weight['cell 1 diag']
            cell1OffDiag = numerix.zeros((Nfac,), 'd')
            cell1OffDiag[:] = weight['cell 1 offdiag']
            cell2Diag = numerix.zeros((Nfac,), 'd')
            cell2Diag[:] = weight['cell 2 diag']
            cell2OffDiag = numerix.zeros((Nfac,), 'd')
            cell2OffDiag[:] = weight['cell 2 offdiag']

            inline._runInline("""
                long int faceID = faceIDs[i];
                long int cellID1 = id1[i];
                long int cellID2 = id2[i];

                b[cellID1] += -coeff[faceID] * (cell1Diag[faceID] * oldArrayId1[i] + cell1OffDiag[faceID] * oldArrayId2[i]);
                b[cellID2] += -coeff[faceID] * (cell2Diag[faceID] * oldArrayId2[i] + cell2OffDiag[faceID] * oldArrayId1[i]);
            """, oldArrayId1 = numerix.array(oldArrayId1),
                oldArrayId2 = numerix.array(oldArrayId2),
                id1 = id1,
                id2 = id2,
                b = b,
                cell1Diag = cell1Diag,
                cell1OffDiag = cell1OffDiag,
                cell2Diag = cell2Diag,
                cell2OffDiag = cell2OffDiag,
                coeff = coeff,
                faceIDs = interiorFaces,
                ni = len(interiorFaces))
Exemplo n.º 9
0
    def _buildMatrix(self, var, SparseMatrix, boundaryConditions=(), dt=None, equation=None, transientGeomCoeff=None, diffusionGeomCoeff=None):

        oldArray = var.old

        mesh = var.mesh
        NCells = mesh.numberOfCells
        NCellFaces = mesh._maxFacesPerCell

        cellValues = numerix.repeat(oldArray[numerix.newaxis, ...], NCellFaces, axis = 0)

        cellIDs = numerix.repeat(numerix.arange(NCells)[numerix.newaxis, ...], NCellFaces, axis = 0)
        cellToCellIDs = mesh._cellToCellIDs

        if NCells > 0:
            cellToCellIDs = MA.where(MA.getmask(cellToCellIDs), cellIDs, cellToCellIDs)

            adjacentValues = numerix.take(oldArray, cellToCellIDs)

            differences = self._getDifferences(adjacentValues, cellValues, oldArray, cellToCellIDs, mesh)
            differences = MA.filled(differences, 0)

            minsq = numerix.sqrt(numerix.sum(numerix.minimum(differences, numerix.zeros((NCellFaces, NCells), 'l'))**2, axis=0))
            maxsq = numerix.sqrt(numerix.sum(numerix.maximum(differences, numerix.zeros((NCellFaces, NCells), 'l'))**2, axis=0))

            coeff = numerix.array(self._getGeomCoeff(var))

            coeffXdifferences = coeff * ((coeff > 0.) * minsq + (coeff < 0.) * maxsq)
        else:
            coeffXdifferences = 0.

        return (var, SparseMatrix(mesh=var.mesh), -coeffXdifferences * mesh.cellVolumes)
Exemplo n.º 10
0
    def _calcCoeffVectors(self, var, equation=None):
        """
        Test for a bug due to the sign operator not being updating
        correctly.

            >>> from fipy import *
            >>> m = Grid1D(nx=1)
            >>> v = CellVariable(mesh=m, value=1.)
            >>> eq = TransientTerm() == ImplicitSourceTerm(v)
            >>> eq.solve(v)
            >>> print v
            [ 2.]
            >>> v.setValue(-1.)
            >>> eq.solve(v)
            >>> print v
            [-0.5]
            
        """

        coeff = self._getGeomCoeff(var.getMesh())
        from fipy.tools.numerix import sign
        combinedSign = self._diagonalSign * sign(coeff)
        self.coeffVectors = {
            'diagonal': coeff * (combinedSign >= 0),
            'old value': numerix.zeros(var.getMesh().getNumberOfCells(), 'd'),
            'b vector': -coeff * var * (combinedSign < 0),
            'new value': numerix.zeros(var.getMesh().getNumberOfCells(), 'd')
        }
Exemplo n.º 11
0
    def _explicitBuildMatrixIn(self, oldArray, id1, id2, b, weightedStencilCoeff, mesh, interiorFaces, dt, weight):

        oldArrayId1, oldArrayId2 = self._getOldAdjacentValues(oldArray, id1, id2, dt)
        coeff = numerix.array(self._getGeomCoeff(mesh))
        Nfac = mesh._getNumberOfFaces()

        cell1Diag = numerix.zeros((Nfac,),'d')
        cell1Diag[:] = weight['cell 1 diag']
        cell1OffDiag = numerix.zeros((Nfac,),'d')
        cell1OffDiag[:] = weight['cell 1 offdiag']
        cell2Diag = numerix.zeros((Nfac,),'d')
        cell2Diag[:] = weight['cell 2 diag']
        cell2OffDiag = numerix.zeros((Nfac,),'d')
        cell2OffDiag[:] = weight['cell 2 offdiag']
        
        inline._runInline("""
            long int faceID = faceIDs[i];
            long int cellID1 = id1[i];
            long int cellID2 = id2[i];
            
            b[cellID1] += -coeff[faceID] * (cell1Diag[faceID] * oldArrayId1[i] + cell1OffDiag[faceID] * oldArrayId2[i]);
            b[cellID2] += -coeff[faceID] * (cell2Diag[faceID] * oldArrayId2[i] + cell2OffDiag[faceID] * oldArrayId1[i]);
        """,oldArrayId1 = numerix.array(oldArrayId1),
            oldArrayId2 = numerix.array(oldArrayId2),
            id1 = id1,
            id2 = id2,
            b = b,
            cell1Diag = cell1Diag,
            cell1OffDiag = cell1OffDiag,
            cell2Diag = cell2Diag,
            cell2OffDiag = cell2OffDiag,
            coeff = coeff,
            faceIDs = interiorFaces,
            ni = len(interiorFaces))
Exemplo n.º 12
0
def _getOrderedLines(IDs, coordinates, thresholdDistance = 0.0):
    """
    This function takes a set of IDs and corresponding coordinates and makes
    a set of closed curves.

    :Parameters:

      - `IDs`: An array of integers.
      - `coordinates`: An array of coordinates of the same length as IDs.

    The following are a general set of test cases.

       >>> _getOrderedLines((0, 1, 2, 3), ((0, 0), (2, 0), (0, 1), (2, 1)))
       [[0, 2, 3, 1]]
       >>> _getOrderedLines((0, 1, 2, 3, 4), ((-10, -10), (0, 0), (2, 0), (0, 1), (2, 1)))
       [[0], [1, 3, 4, 2]]
       >>> _getOrderedLines((0, 1, 2, 3), ((0, 0), (0.9, 0), (0, 1), (1, 1)))
       [[0, 1, 3, 2]]
       >>> _getOrderedLines((0, 1, 2, 3, 4, 5), ((0, 0), (1, 0), (2, 0), (0, 1.1), (1, 1.1), (2, 1.1)))
       [[0, 1, 2, 5, 4, 3]]
       >>> _getOrderedLines((4, 5, 0, 1, 3, 2, 6), ((0, 0), (1, 0), (3, 0), (0, 1.1), (1, 1.1), (3, 1), (4, 1)))
       [[4, 5, 3, 1], [0, 2, 6]]
       >>> _getOrderedLines((4, 5, 3, 2, 1, 0, 9, 8, 7, 6), ((0, 0), (1, 0), (0, 1.1), (1, 1.1), (0, 3), (1, 3), (-1, 4), (2, 4), (-2, 4), (3, 4)))
       [[4, 5, 2, 3], [7, 9, 1, 0, 8, 6]]
       >>> from builtins import range
       >>> _getOrderedLines(list(range(7)), ((-7, 0), (-6, 0), (-5, 0), (0, 0), (5, 0), (6, 0), (7, 0)))
       [[0, 1, 2], [3], [4, 5, 6]]
       >>> from builtins import range
       >>> _getOrderedLines(list(range(7)), ((-7, 0), (-6, 0), (-5, 0), (0, 0), (5, 0), (6, 0), (7, 0)), thresholdDistance = 5.5)
       [[0, 1, 2, 3, 4, 5, 6]]
    """

    from fipy.tools import numerix
    coordinates = numerix.array(coordinates)
    closeIDs = numerix.zeros((len(IDs), len(IDs)), 'l')
    vertices = []
    for ID in IDs:
        distances = numerix.zeros(len(IDs), 'd')
        for i in range(len(coordinates[0,:])):
            distances += (coordinates[:, i] - coordinates[ID, i])**2
        vertices.append(_Vertex(ID, coordinates[ID, 0], coordinates[ID, 1]))
        closeIDs[ID,:] = numerix.argsort(distances)


    for ID in IDs:
        i = 1
        closeVertices = []
        while i < 3 or vertices[ID].distance(vertices[closeIDs[ID, i]]) < thresholdDistance:
            closeVertices.append(vertices[closeIDs[ID, i]])
            i += 1

        vertices[ID].setCloseVertices(closeVertices)

    listOfVertexLists = []

    for vertex in vertices:
        if not vertex.getInLine():
            listOfVertexLists.append(_Line(vertex).getVertexListIDs())

    return listOfVertexLists
Exemplo n.º 13
0
    def _buildMatrix(self, var, SparseMatrix, boundaryCondtions=(), dt=None, equation=None):

        oldArray = var.getOld()

        mesh = var.getMesh()
        NCells = mesh.getNumberOfCells()
        NCellFaces = mesh._getMaxFacesPerCell()

        cellValues = numerix.repeat(oldArray[numerix.newaxis, ...], NCellFaces, axis = 0)
        
        cellIDs = numerix.repeat(numerix.arange(NCells)[numerix.newaxis, ...], NCellFaces, axis = 0)
        cellToCellIDs = mesh._getCellToCellIDs()

        if NCells > 0:
            cellToCellIDs = MA.where(MA.getmask(cellToCellIDs), cellIDs, cellToCellIDs) 

            adjacentValues = numerix.take(oldArray, cellToCellIDs)

            differences = self._getDifferences(adjacentValues, cellValues, oldArray, cellToCellIDs, mesh)
            differences = MA.filled(differences, 0)
            
            minsq = numerix.sqrt(numerix.sum(numerix.minimum(differences, numerix.zeros((NCellFaces, NCells)))**2, axis=0))
            maxsq = numerix.sqrt(numerix.sum(numerix.maximum(differences, numerix.zeros((NCellFaces, NCells)))**2, axis=0))

            coeff = numerix.array(self._getGeomCoeff(mesh))

            coeffXdiffereneces = coeff * ((coeff > 0.) * minsq + (coeff < 0.) * maxsq)
        else:
            coeffXdiffereneces = 0.

        return (SparseMatrix(mesh=var.getMesh()), -coeffXdiffereneces * mesh.getCellVolumes())
Exemplo n.º 14
0
    def _calcFaceTangents(self):
	faces = self.getFaces()
	N = len(faces)
	dim = len(faces[0].getCenter())
	self.faceTangents1 = numerix.zeros((N,dim),'d')
	self.faceTangents2 = numerix.zeros((N,dim),'d')
	# get the units right
	self.faceTangents1 = self.faceTangents1 * faces[0]._calcTangent1()
	self.faceTangents2 = self.faceTangents2 * faces[0]._calcTangent2()
	for i in range(N):
	    self.faceTangents1[i] = faces[i]._calcTangent1()
	    self.faceTangents2[i] = faces[i]._calcTangent2()
Exemplo n.º 15
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)
Exemplo n.º 16
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
Exemplo n.º 17
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)
Exemplo n.º 18
0
Arquivo: grid3D.py Projeto: regmi/fipy
 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)
Exemplo n.º 19
0
    def __init__(self, polyData):
        vertices3D = convert.vtk_to_numpy(polyData.GetPoints().GetData())
        # FiPy needs its coordinates in an array like:
        # [[x0, x1, ..., xn-1],
        #  [y0, y1, ..., yn-1]]
        # VTK gives us:
        # [[x0, y0, z0],
        #  [x1, y1, z1],
        #  ...,
        #  [xn-1, yn-1, zn-1]]
        self.vertices = vertices3D[:, 0:2].transpose()

        # VTK gives us a flat array of cells like
        # [nPoints, pId0, pId1, pId2, ... nPoints,... ]
        cells = convert.vtk_to_numpy(polyData.GetPolys().GetData())
        self.nTris = nTris = polyData.GetPolys().GetNumberOfCells()
        cells.shape = (nTris, 4)
        # So now cells[i] contains (3, id0, id1, id2) for triangle i

        # FiPy requires a list of the FACES (in 2D the lines) making up each
        # cell. Make the array the maximum possible size for now.
        self.faces = np.zeros((2, 3 * nTris), dtype=np2.int)

        # Since these have to be unique, construct a sparse lookup matrix
        # (a dictionary is very sloooooow)
        ############################################################
        # SUPER IMPORTANT- since the default value of the matrix is
        # zero, we're going to use 1-indexing for these so +1 when
        # writing and -1 when reading.
        ############################################################
        self.faceCache = lil_matrix((nTris, nTris), dtype=np2.int)
        # Track the number of faces added.
        self.nFaces = 0

        # A cell is defined by the IDs of its faces
        self.cells = np.zeros((3, nTris), dtype=np2.int)
        # Track the number added
        self.nCells = 0

        for triPtIds in cells[:, 1:]:
            for i in xrange(3):
                self.cells[i, self.nCells] = self._InsertUniqueFace(
                    triPtIds[i], triPtIds[(i + 1) % 3])
                continue
            self.nCells += 1
            continue

        # Trim the unused face rows
        self.faces = self.faces[:, :self.nFaces]
        return
Exemplo n.º 20
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)
Exemplo n.º 21
0
 def _calcFaceTangents(self):
     ## need to see whether order matters.
     faceTangents1 = numerix.zeros((3, self.numberOfFaces), 'd')
     faceTangents2 = numerix.zeros((3, self.numberOfFaces), 'd')
     ## XY faces
     faceTangents1[0, :self.numberOfXYFaces] = 1.
     faceTangents2[1, :self.numberOfXYFaces] = 1.
     ## XZ faces
     faceTangents1[0, self.numberOfXYFaces:self.numberOfXYFaces + self.numberOfXZFaces] = 1.
     faceTangents2[2, self.numberOfXYFaces:self.numberOfXYFaces + self.numberOfXZFaces] = 1.
     ## YZ faces
     faceTangents1[1, self.numberOfXYFaces + self.numberOfXZFaces:] = 1.
     faceTangents2[2, self.numberOfXYFaces + self.numberOfXZFaces:] = 1.
     return faceTangents1, faceTangents2
Exemplo n.º 22
0
 def _calcFaceTangents(self):
     ## need to see whether order matters.
     faceTangents1 = numerix.zeros((3, self.numberOfFaces), 'd')
     faceTangents2 = numerix.zeros((3, self.numberOfFaces), 'd')
     ## XY faces
     faceTangents1[0, :self.numberOfXYFaces] = 1.
     faceTangents2[1, :self.numberOfXYFaces] = 1.
     ## XZ faces
     faceTangents1[0, self.numberOfXYFaces:self.numberOfXYFaces + self.numberOfXZFaces] = 1.
     faceTangents2[2, self.numberOfXYFaces:self.numberOfXYFaces + self.numberOfXZFaces] = 1.
     ## YZ faces
     faceTangents1[1, self.numberOfXYFaces + self.numberOfXZFaces:] = 1.
     faceTangents2[2, self.numberOfXYFaces + self.numberOfXZFaces:] = 1.
     return faceTangents1, faceTangents2                                     
Exemplo n.º 23
0
    def _faceCenters(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
Exemplo n.º 24
0
Arquivo: grid3D.py Projeto: regmi/fipy
 def _calcFaceTangents(self):
     ## need to see whether order matters.
     faceTangents1 = numerix.zeros((3, self.numberOfFaces), "d")
     faceTangents2 = numerix.zeros((3, self.numberOfFaces), "d")
     ## XY faces
     faceTangents1[0, : self.numberOfXYFaces] = 1.0
     faceTangents2[1, : self.numberOfXYFaces] = 1.0
     ## XZ faces
     faceTangents1[0, self.numberOfXYFaces : self.numberOfXYFaces + self.numberOfXZFaces] = 1.0
     faceTangents2[2, self.numberOfXYFaces : self.numberOfXYFaces + self.numberOfXZFaces] = 1.0
     ## YZ faces
     faceTangents1[1, self.numberOfXYFaces + self.numberOfXZFaces :] = 1.0
     faceTangents2[2, self.numberOfXYFaces + self.numberOfXZFaces :] = 1.0
     self.faceTangents1 = faceTangents1
     self.faceTangents2 = faceTangents2
Exemplo n.º 25
0
    def faceVertexIDs(self):
        Hids = numerix.zeros((2, self.nx, self.numberOfHorizontalRows), 'l')
        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), 'l')
        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)
Exemplo n.º 26
0
 def _calcFaceNormals(self):
     XYFaceNormals = numerix.zeros((3, self.numberOfXYFaces), 'l')
     XYFaceNormals[2, (self.nx * self.ny):] = 1
     XYFaceNormals[2, :(self.nx * self.ny)] = -1
     XZFaceNormals = numerix.zeros((3, self.numberOfXZFaces), 'l')
     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), 'l')
     YZFaceNormals[0, :] = 1
     YZFaceNormals[0, ::self.nx + 1] = -1
     return numerix.concatenate(
         (XYFaceNormals, XZFaceNormals, YZFaceNormals), axis=-1)
Exemplo n.º 27
0
    def _calcVertexCoords(self, coordDimensions):
        if self.fileType == 1:
            nodeLines = self.getTagData("$NOD", "$ENDNOD")
        else:
            nodeLines = self.getTagData("$Nodes", "$EndNodes")

    ## get the vertex coordinates
        nodeToVertexIDdict = {}
        
        numVertices = int(nodeLines[0])
        if numVertices != len(nodeLines[1:]):
            raise IndexError, "Number of nodes (%d) does not match number promised (%d)" % (numVertices, len(nodeLines[1:]))

        vertexCoords = []
        for node, i in zip(nodeLines[1:], range(len(nodeLines[1:]))):
            nodeInfo = node.split()
            nodeToVertexIDdict[int(nodeInfo[0])] = i
            vertexCoords.append([float(n) for n in nodeInfo[1:]])

        vertexCoords = numerix.array(vertexCoords, 'd')
        
        maxNode = max(nodeToVertexIDdict.keys())
        nodeToVertexIDs = numerix.zeros((maxNode + 1,))
        for i in nodeToVertexIDdict.keys():
            nodeToVertexIDs[i] = nodeToVertexIDdict[i]
        self.nodeToVertexIDs = nodeToVertexIDs
        return vertexCoords[:,:coordDimensions].swapaxes(0,1)
Exemplo n.º 28
0
def H_UniaxialAnisotropy(mUnit, uAxis, Ku2, Msat):
    global mu0
    ############ calculate normalized direction #####
    uAxisNorm = numerix.linalg.norm(uAxis)
    uAxisUnit = uAxis / uAxisNorm
    #################################################
    mArray = mUnit
    #################################################
    #################################################
    # repeat uniaxial direction vector for n times
    # where n= number of cells. uAxisUnit=3X1
    # uAxisArr=nX3, represents uniaxial direction for
    # each cells in the unit sphere
    #################################################
    uAxisArr = numerix.tile(uAxisUnit, (len(mUnit[0]), 1))
    uAxisArr = numerix.transpose(uAxisArr)  # converted to 3Xn
    mdotu = numerix.dot(mArray,
                        uAxisArr)  # projection of m along uniaxial direction
    scaleFac = numerix.multiply(
        mdotu, (2.0 * Ku2 / (mu0 * Msat)))  # calculate the magnitude in A/m
    Heff = numerix.zeros((3, len(scaleFac)),
                         'd')  # Uniaxial vector for each cell
    Heff[0] = numerix.multiply(scaleFac, uAxisArr[0])
    Heff[1] = numerix.multiply(scaleFac, uAxisArr[1])
    Heff[2] = numerix.multiply(scaleFac, uAxisArr[2])
    # unit is in A/m
    return Heff
Exemplo n.º 29
0
    def _buildMatrix(self, var, SparseMatrix, boundaryConditions=(), dt=1., equation=None):
        """Implicit portion considers
        """

        mesh = var.getMesh()
        id1, id2 = mesh._getAdjacentCellIDs()
        interiorFaces = numerix.nonzero(mesh.getInteriorFaces())[0]
        
        id1 = numerix.take(id1, interiorFaces)
        id2 = numerix.take(id2, interiorFaces)
        
        N = len(var)
        b = numerix.zeros((N),'d')
        L = SparseMatrix(size = N)

        if equation is not None:
            from fipy.tools.numerix import sign, add
            self._diagonalSign.setValue(sign(add.reduce(equation.matrix.takeDiagonal())))
        else:
            self._diagonalSign.setValue(1)

        weight = self._getWeight(mesh, equation=equation)

        if weight.has_key('implicit'):
            self._implicitBuildMatrix(SparseMatrix, L, id1, id2, b, weight['implicit'], mesh, boundaryConditions, interiorFaces, dt)

        if weight.has_key('explicit'):
            self._explicitBuildMatrix(SparseMatrix, var.getOld(), id1, id2, b, weight['explicit'], mesh, boundaryConditions, interiorFaces, dt)

        return (L, b)
Exemplo n.º 30
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)
Exemplo n.º 31
0
    def run(self):
        MayaviDaemon._viewers.append(self)

        mlab.clf()

        self.cellsource = self.setup_source(self.cellfname)
        self.has_cell, bounds = self._examine_data(source=self.cellsource,
                                                   datatype="cell_data",
                                                   bounds=zeros((0, 6), 'l'))

        self.facesource = self.setup_source(self.facefname)
        self.has_face, bounds = self._examine_data(source=self.facesource,
                                                   datatype="point_data",
                                                   bounds=bounds)

        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)
Exemplo n.º 32
0
    def _solve_(self, L, x, b):
        diag = L.takeDiagonal()
        maxdiag = max(numerix.absolute(diag))

        L = L * (1 / maxdiag)
        b = b * (1 / maxdiag)

        LU = superlu.factorize(L.matrix.to_csr())

        if DEBUG:
            import sys
            print >> sys.stderr, L.matrix

        error0 = numerix.sqrt(numerix.sum((L * x - b)**2))

        for iteration in range(self.iterations):
            errorVector = L * x - b

            if (numerix.sqrt(numerix.sum(errorVector**2)) / error0)  <= self.tolerance:
                break

            xError = numerix.zeros(len(b),'d')
            LU.solve(errorVector, xError)
            x[:] = x - xError
            
        if 'FIPY_VERBOSE_SOLVER' in os.environ:
            from fipy.tools.debug import PRINT        
            PRINT('iterations: %d / %d' % (iteration+1, self.iterations))
            PRINT('residual:', numerix.sqrt(numerix.sum(errorVector**2)))
Exemplo n.º 33
0
    def numpyArray(self):
        import tempfile
        import os
        from scipy.io import mmio
        from fipy.tools import parallelComm

        if parallelComm.procID == 0:
            (_, mtxName) = tempfile.mkstemp(suffix='.mtx')
        else:
            mtxName = None

        mtxName = parallelComm.bcast(mtxName)

        self.exportMmf(mtxName)

        parallelComm.Barrier()
        mtx = mmio.mmread(mtxName)
        parallelComm.Barrier()

        if parallelComm.procID == 0:
            os.remove(mtxName)

        coo = mtx.tocoo()
        trilinosMatrix = self.matrix
        numpyArray = numerix.zeros(
            (trilinosMatrix.NumGlobalRows(), trilinosMatrix.NumGlobalCols()),
            'd')
        numpyArray[coo.row, coo.col] = coo.data
        return numpyArray
Exemplo n.º 34
0
Arquivo: mesh2D.py Projeto: regmi/fipy
 def _calcFaceTangents(self):
     tmp = numerix.array((-self.faceNormals[1], self.faceNormals[0]))
     ## copy required to get internal memory ordering correct for inlining.
     tmp = tmp.copy()
     mag = numerix.sqrtDot(tmp, tmp)
     self.faceTangents1 = tmp / mag
     self.faceTangents2 = numerix.zeros(self.faceTangents1.shape, 'd')
Exemplo n.º 35
0
        def _areaProjections(self):
            areaProjections = numerix.zeros((2, self.numberOfFaces), 'd')

            inline._runInline(
                """
                              if (i < nx) {
                                  areaProjections[i + 1 * ni] = faceAreas[i] * faceNormals[i + 1 * ni];
                              } else if (i < Nhor) {
                                  areaProjections[i + 1 * ni] = faceAreas[i] * faceNormals[i + 1 * ni];
                              } else if ( (i - Nhor) % (nx + 1) == 0 ) {
                                  areaProjections[i + 0 * ni] = faceAreas[i] * faceNormals[i + 0 * ni];
                              } else {
                                  areaProjections[i + 0 * ni] = faceAreas[i] * faceNormals[i + 0 * ni];
                              }
                              """,
                dx=float(self.dx),  # horrible hack to get around
                dy=float(
                    self.dy),  # http://www.scipy.org/scipy/scipy/ticket/496
                nx=self.nx,
                Nhor=self.numberOfHorizontalFaces,
                areaProjections=areaProjections,
                ni=self.numberOfFaces,
                faceNormals=self.faceNormals,
                faceAreas=self._faceAreas)

            return areaProjections
Exemplo n.º 36
0
 def addAtDiagonal(self, vector):
     if type(vector) in [type(1), type(1.)]:
         tmp = numerix.zeros((self.mesh.numberOfCells,), 'd')
         tmp[:] = vector
         SparseMatrix.addAtDiagonal(self, tmp)
     else:
         SparseMatrix.addAtDiagonal(self, vector)
Exemplo n.º 37
0
    def _calcFaceOrientations(self):
	faces = self.getFaces()
	N = len(faces)
	orientations = numerix.zeros((N),'d')
	for i in range(N):
	    orientations[i] = faces[i]._getOrientation()
	self.faceOrientations = orientations
Exemplo n.º 38
0
    def _calcValue(self):

        Nfaces = self.mesh.numberOfFaces
        M = self.mesh._maxFacesPerCell
        dim = self.mesh.dim
        cellFaceIDs = self.mesh.cellFaceIDs

        faceNormalAreas = self.distanceVar._levelSetNormals * self.mesh._faceAreas

        cellFaceNormalAreas = numerix.array(MA.filled(numerix.take(faceNormalAreas, cellFaceIDs, axis=-1), 0))
        norms = numerix.array(MA.filled(MA.array(self.mesh._cellNormals), 0))

        alpha = numerix.dot(cellFaceNormalAreas, norms)
        alpha = numerix.where(alpha > 0, alpha, 0)

        alphasum = numerix.sum(alpha, axis=0)
        alphasum += (alphasum < 1e-100) * 1.0
        alpha = alpha / alphasum

        phi = numerix.repeat(self.distanceVar[numerix.newaxis, ...], M, axis=0)
        alpha = numerix.where(phi > 0., 0, alpha)

        volumes = numerix.array(self.mesh.cellVolumes)
        alpha = alpha * volumes * norms

        value = numerix.zeros((dim, Nfaces), 'd')

        vector._putAdd(value, cellFaceIDs, alpha, mask=MA.getmask(MA.array(cellFaceIDs)))

##         value = numerix.reshape(value, (dim, Nfaces, dim))

        return -value / self.mesh._faceAreas
Exemplo n.º 39
0
    def _ao(self):
        """Application Ordering to relate FiPy matrix rows to PETSc matrix rows
        
        FiPy naturally blocks matrix rows, one set of Equations (or Variables) at a time.
        PETSc requires that all rows pertaining to a particular MPI node be contiguous.
        This PETSc `AO` (Application Ordering) object converts between them.
        
        Only needed for FiPy to PETSc. We can efficiently slice from PETSc to
        FiPy, but PETSc requires us to know the row IDs. 
        """
        if not hasattr(self, "_ao_"):
            comm = self.mesh.communicator

            from mpi4py import MPI

            fipyIDs = self._globalNonOverlappingColIDs
            N = len(fipyIDs)

            count = numerix.zeros((comm.Nproc, ), dtype=int)
            count[comm.procID] = N
            comm.mpi4py_comm.Allreduce(sendbuf=MPI.IN_PLACE,
                                       recvbuf=count,
                                       op=MPI.MAX)

            petscIDs = numerix.arange(N) + numerix.sum(count[:comm.procID])

            self._ao_ = PETSc.AO().createBasic(petsc=petscIDs.astype('int32'),
                                               app=fipyIDs.astype('int32'),
                                               comm=comm.petsc4py_comm)
        return self._ao_
Exemplo n.º 40
0
    def putDiagonal(self, vector):
        """
        Put elements of `vector` along diagonal of matrix

            >>> L = _TrilinosMatrixFromShape(rows=3, cols=3)
            >>> L.putDiagonal((3., 10., numerix.pi))
            >>> print(L)
             3.000000      ---        ---    
                ---    10.000000      ---    
                ---        ---     3.141593  
            >>> L.putDiagonal((10., 3.))
            >>> print(L)
            10.000000      ---        ---    
                ---     3.000000      ---    
                ---        ---     3.141593  
        """

        if type(vector) in [type(1), type(1.)]:
            ids = numerix.arange(self.matrix.NumGlobalRows())
            tmp = numerix.zeros((self.matrix.NumGlobalRows), 'd')
            tmp[:] = vector
            if ids.dtype.name == 'int64':
                ids = ids.astype('int32')
            self.put(tmp, ids, ids)
        else:
            ids = numerix.arange(len(vector))
            if ids.dtype.name == 'int64':
                ids = ids.astype('int32')
            self.put(vector, ids, ids)
Exemplo n.º 41
0
    def _buildMatrix(self,
                     var,
                     SparseMatrix,
                     boundaryConditions=(),
                     dt=None,
                     transientGeomCoeff=None,
                     diffusionGeomCoeff=None):

        b = numerix.zeros(var.shape, 'd').ravel()
        L = SparseMatrix(mesh=var.mesh)

        coeffVectors = self._getCoeffVectors_(
            var=var,
            transientGeomCoeff=transientGeomCoeff,
            diffusionGeomCoeff=diffusionGeomCoeff)

        dt = self._checkDt(dt)

        if inline.doInline and var.rank == 0:
            self._buildMatrixInline_(L=L,
                                     oldArray=var.old,
                                     b=b,
                                     dt=dt,
                                     coeffVectors=coeffVectors)
        else:
            self._buildMatrixNoInline_(L=L,
                                       oldArray=var.old,
                                       b=b,
                                       dt=dt,
                                       coeffVectors=coeffVectors)

        return (var, L, b)
Exemplo n.º 42
0
    def _buildMatrix(self, var, SparseMatrix,  boundaryConditions, dt, equation=None):
        from fipy.tools import numerix

        N = len(var)
        self.RHSvector = numerix.zeros((N,),'d')
        self.matrix = SparseMatrix(size=N)

        for term in self._getTerms():
            if term is not None:
                termMatrix, termRHSvector = term._buildMatrix(var, SparseMatrix,
                                                              boundaryConditions, 
                                                              dt, self)

                if (os.environ.has_key('FIPY_DISPLAY_MATRIX') 
                    and os.environ['FIPY_DISPLAY_MATRIX'].lower() == "terms"):
                    self._viewer.title = "%s %s" % (var.name, term.__class__.__name__)
                    self._viewer.plot(matrix=termMatrix)
                    raw_input()

                self.matrix += termMatrix
                self.RHSvector += termRHSvector
	
        matrix = self.matrix
        RHSvector = self.RHSvector
        if not self._cacheMatrix:
            self.matrix = None
        if not self._cacheRHSvector:
            self.RHSvector = None
            
	return (matrix, RHSvector)
Exemplo n.º 43
0
 def _getFaceToCellDistances(self):
     faceToCellDistances = numerix.zeros((2, self.numberOfFaces), 'd')
     distances = self._getCellDistances()
     ratios = self._getFaceToCellDistanceRatio()
     faceToCellDistances[0] = distances * ratios
     faceToCellDistances[1] = distances * (1 - ratios)
     return faceToCellDistances
Exemplo n.º 44
0
    def _buildMatrix(self,
                     var,
                     SparseMatrix,
                     boundaryConditions=(),
                     dt=None,
                     transientGeomCoeff=None,
                     diffusionGeomCoeff=None):
        """Implicit portion considers
        """
        mesh = var.mesh
        id1, id2 = mesh._adjacentCellIDs
        interiorFaces = numerix.nonzero(mesh.interiorFaces)[0]

        id1 = numerix.take(id1, interiorFaces)
        id2 = numerix.take(id2, interiorFaces)

        b = numerix.zeros(var.shape, 'd').ravel()
        L = SparseMatrix(mesh=mesh)

        weight = self._getWeight(var, transientGeomCoeff, diffusionGeomCoeff)

        if 'implicit' in weight:
            self._implicitBuildMatrix_(SparseMatrix, L, id1, id2, b,
                                       weight['implicit'], var,
                                       boundaryConditions, interiorFaces, dt)

        if 'explicit' in weight:
            self._explicitBuildMatrix_(SparseMatrix, var.old, id1, id2, b,
                                       weight['explicit'], var,
                                       boundaryConditions, interiorFaces, dt)

        return (var, L, b)
Exemplo n.º 45
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)
Exemplo n.º 46
0
 def addAtDiagonal(self, vector):
     if type(vector) in [type(1), type(1.)]:
         tmp = numerix.zeros((self.mesh.numberOfCells, ), 'd')
         tmp[:] = vector
         SparseMatrix.addAtDiagonal(self, tmp)
     else:
         SparseMatrix.addAtDiagonal(self, vector)
Exemplo n.º 47
0
    def _solve_(self, L, x, b):
        diag = L.takeDiagonal()
        maxdiag = max(numerix.absolute(diag))

        L = L * (1 / maxdiag)
        b = b * (1 / maxdiag)

        LU = superlu.factorize(L.matrix.to_csr())

        if DEBUG:
            import sys
            print(L.matrix, file=sys.stderr)

        error0 = numerix.sqrt(numerix.sum((L * x - b)**2))

        for iteration in range(self.iterations):
            errorVector = L * x - b

            if (numerix.sqrt(numerix.sum(errorVector**2)) / error0)  <= self.tolerance:
                break

            xError = numerix.zeros(len(b), 'd')
            LU.solve(errorVector, xError)
            x[:] = x - xError

        if 'FIPY_VERBOSE_SOLVER' in os.environ:
            from fipy.tools.debug import PRINT
            PRINT('iterations: %d / %d' % (iteration+1, self.iterations))
            PRINT('residual:', numerix.sqrt(numerix.sum(errorVector**2)))
Exemplo n.º 48
0
 def putDiagonal(self, vector):
     """
     Put elements of `vector` along diagonal of matrix
     
         >>> L = _TrilinosMatrix(size=3)
         >>> L.putDiagonal((3.,10.,numerix.pi))
         >>> print L
          3.000000      ---        ---    
             ---    10.000000      ---    
             ---        ---     3.141593  
         >>> L.putDiagonal((10.,3.))
         >>> print L
         10.000000      ---        ---    
             ---     3.000000      ---    
             ---        ---     3.141593  
     """
     
     
     if type(vector) in [type(1), type(1.)]:
         ids = numerix.arange(self._getMatrix().NumGlobalRows())
         tmp = numerix.zeros((self._getMatrix().NumGlobalRows), 'd')
         tmp[:] = vector
         if ids.dtype.name == 'int64':
             ids = ids.astype('int32')
         self.put(tmp, ids, ids)
     else:
         ids = numerix.arange(len(vector))
         if ids.dtype.name == 'int64':
             ids = ids.astype('int32')
         self.put(vector, ids, ids)
Exemplo n.º 49
0
    def _calcCellCenters(self):
	cells = self.getCells()
	N = len(cells)
	self.cellCenters = numerix.zeros((N,self.dim),'d')
	# get the units right
	self.cellCenters = self.cellCenters * cells[0].getCenter()
	for i in range(N):
	    self.cellCenters[i] = cells[i].getCenter()	    
Exemplo n.º 50
0
 def _cellCenters(self):
     centers = numerix.zeros((3, self.nx, self.ny, self.nz), 'd')
     indices = numerix.indices((self.nx, self.ny, self.nz))
     centers[0] = (indices[0] + 0.5) * self.dx
     centers[1] = (indices[1] + 0.5) * self.dy
     centers[2] = (indices[2] + 0.5) * self.dz
     ccs = numerix.reshape(centers.swapaxes(1, 3), (3, self.numberOfCells)) + self.origin
     return ccs
Exemplo n.º 51
0
 def _cellCenters(self):
     centers = numerix.zeros((2, self.nx, self.ny), 'd')
     indices = numerix.indices((self.nx, self.ny))
     centers[0] = (indices[0] + 0.5) * self.dx
     centers[1] = (indices[1] + 0.5) * self.dy
     ccs = centers.reshape(
         (2, self.numberOfCells), order="FORTRAN") + self.origin
     return ccs
Exemplo n.º 52
0
    def _cellNormals(self):
        normals = numerix.zeros((2, 4, self.numberOfCells), 'd')
        normals[:, 0] = [[0], [-1]]
        normals[:, 1] = [[1], [0]]
        normals[:, 2] = [[0], [1]]
        normals[:, 3] = [[-1], [0]]

        return normals
Exemplo n.º 53
0
    def _calcFaceToCellDistances(self):
	faces = self.getFaces()
	N = len(faces)
	self.faceToCellDistances = numerix.zeros((N),'d')
	# get the units right
	self.faceToCellDistances = self.faceToCellDistances * faces[0]._getFaceToCellDistance()
	for i in range(N):
	    self.faceToCellDistances[i] = faces[i]._getFaceToCellDistance()
Exemplo n.º 54
0
    def _calcFaceAreas(self):
	faces = self.getFaces()
	N = len(faces)
	self.faceAreas = numerix.zeros((N),'d')
	# get the units right
	self.faceAreas = self.faceAreas * faces[0].getArea()
	for i in range(N):
	    self.faceAreas[i] = faces[i].getArea()
Exemplo n.º 55
0
 def _cellCenters(self):
     centers = numerix.zeros((3, self.nx, self.ny, self.nz), 'd')
     indices = numerix.indices((self.nx, self.ny, self.nz))
     centers[0] = (indices[0] + 0.5) * self.dx
     centers[1] = (indices[1] + 0.5) * self.dy
     centers[2] = (indices[2] + 0.5) * self.dz
     ccs = numerix.reshape(centers.swapaxes(1,3), (3, self.numberOfCells)) + self.origin
     return ccs
Exemplo n.º 56
0
    def _calcCellVolumes(self):
	cells = self.getCells()
	N = len(cells)
	self.cellVolumes = numerix.zeros((N),'d')
	# get the units right
	self.cellVolumes = self.cellVolumes * cells[0].getVolume()	    
	for i in range(N):
	    self.cellVolumes[i] = cells[i].getVolume()	    
Exemplo n.º 57
0
 def addAtDiagonal(self, vector):
     if type(vector) in [type(1), type(1.)]:
         ids = numerix.arange(self._shape[0])
         tmp = numerix.zeros((self._shape[0],), 'd')
         tmp[:] = vector
         self.addAt(tmp, ids, ids)
     else:
         ids = numerix.arange(len(vector))
         self.addAt(vector, ids, ids)
Exemplo n.º 58
0
 def addAtDiagonal(self, vector):
     if isinstance(vector, (int, float)):
         ids = numerix.arange(self._shape[0])
         tmp = numerix.zeros((self._shape[0],), 'd')
         tmp[:] = vector
         self.addAt(tmp, ids, ids)
     else:
         ids = numerix.arange(len(vector))
         self.addAt(vector, ids, ids)