Esempio n. 1
0
    def _calcValueIn(self, N, M, ids, orientations, volumes):
        val = self._getArray().copy()
        
        inline._runIterateElementInline(self.modIn + """
            ITEM(val, i, vec) = 0.;

            int k;
            for (k = 0; k < M; k++) {
                int id = ITEM(ids, i, &k);
                ITEM(val, i, vec) += ITEM(orientations, i, &k) * ITEM(areaProj, id, vec) * ITEM(faceValues, id, NULL);
            }
                
            ITEM(val, i, vec) /= ITEM(volumes, i, NULL);
            ITEM(val, i, vec) = mod(ITEM(val, i, vec) * gridSpacing[vec[0]]) /  gridSpacing[vec[0]];
        """,val = val,
            ids = numerix.array(ids),
            orientations = numerix.array(orientations),
            volumes = numerix.array(volumes),
            areaProj = numerix.array(self.mesh._getAreaProjections()),
            faceValues = numerix.array(self.var.getArithmeticFaceValue()),
            M = M,
            ni = N, 
            gridSpacing = numerix.array(self.mesh._getMeshSpacing()),
            shape=numerix.array(numerix.shape(val)))
            
        return self._makeValue(value = val)
Esempio n. 2
0
    def _calcValueIn(self, N, M, ids, orientations, volumes):
        val = self._getArray().copy()

        inline._runIterateElementInline(
            """
            ITEM(val, i, vec) = 0.;

            int k;
            for (k = 0; k < M; k++) {
                int id = ITEM(ids, i, &k);
                ITEM(val, i, vec) += ITEM(orientations, i, &k) * ITEM(areaProj, id, vec) * ITEM(faceValues, id, NULL);
            }
                
            ITEM(val, i, vec) /= ITEM(volumes, i, NULL);
        """,
            val=val,
            ids=numerix.array(numerix.MA.filled(ids, 0)),
            orientations=numerix.array(numerix.MA.filled(orientations, 0)),
            volumes=numerix.array(volumes),
            areaProj=numerix.array(self.mesh._getAreaProjections()),
            faceValues=numerix.array(self.var.getArithmeticFaceValue()),
            M=M,
            ni=N,
            shape=numerix.array(numerix.shape(val)),
        )

        return self._makeValue(value=val)
Esempio n. 3
0
    def __mul__(self, factor):
        if numerix.shape(factor) is ():
            factor = numerix.resize(factor, (2, 1))

        return UniformGrid2D(dx=self.args['dx'] * numerix.array(factor[0]), nx=self.args['nx'],
                             dy=self.args['dy'] * numerix.array(factor[1]), ny=self.args['ny'],
                             origin=numerix.array(self.args['origin']) * factor, overlap=self.args['overlap'])
Esempio n. 4
0
 def __setitem__(self, index, value):
     N = self.mesh.numberOfCells
     for i, var in enumerate(self.vars):
         if numerix.shape(value) == ():
             var[index] = value
         else:
             var[index] = value[i * N:(i + 1) * N]
Esempio n. 5
0
 def __setitem__(self, index, value):
     N = self.mesh.numberOfCells
     for i, var in enumerate(self.vars):
         if numerix.shape(value) == ():
             var[index] = value
         else:
             var[index] = value[i * N:(i + 1) * N]
Esempio n. 6
0
    def _calcValueInline(self, N, M, ids, orientations, volumes):
        val = self._array.copy()

        inline._runIterateElementInline(
            self.modIn + """
            ITEM(val, i, vec) = 0.;

            int k;
            for (k = 0; k < M; k++) {
                int id = ITEM(ids, i, &k);
                ITEM(val, i, vec) += ITEM(orientations, i, &k) * ITEM(areaProj, id, vec) * ITEM(faceValues, id, NULL);
            }

            ITEM(val, i, vec) /= ITEM(volumes, i, NULL);
            ITEM(val, i, vec) = mod(ITEM(val, i, vec) * gridSpacing[vec[0]]) /  gridSpacing[vec[0]];
        """,
            val=val,
            ids=numerix.array(ids),
            orientations=numerix.array(orientations),
            volumes=numerix.array(volumes),
            areaProj=numerix.array(self.mesh._areaProjections),
            faceValues=numerix.array(self.var.arithmeticFaceValue),
            M=M,
            ni=N,
            gridSpacing=numerix.array(self.mesh._meshSpacing),
            shape=numerix.array(numerix.shape(val)))

        return self._makeValue(value=val)
        def _calcValue_(self, alpha, id1, id2):
            val = self._array.copy()

            inline._runIterateElementInline("""
                int ID1 = ITEM(id1, i, NULL);
                int ID2 = ITEM(id2, i, NULL);
                double cell1 = ITEM(var, ID1, vec);
                double cell2 = ITEM(var, ID2, vec);
                double cell1Xcell2 = cell1 * cell2;
                double tmp = ((cell2 - cell1) * ITEM(alpha, i, NULL) + cell1);
                if (tmp != 0 && cell1Xcell2 > 0.) {
                    ITEM(val, i, vec) = cell1Xcell2 / tmp;
                } else {
                    ITEM(val, i, vec) = 0.;
                }
            """,
                                            var=self.var.numericValue,
                                            val=val,
                                            alpha=alpha,
                                            id1=id1,
                                            id2=id2,
                                            shape=numerix.array(
                                                numerix.shape(val)),
                                            ni=self.mesh.numberOfFaces)

            return self._makeValue(value=val)
Esempio n. 8
0
    def __mul__(self, other):
        """
        Multiply a sparse matrix by another sparse matrix
        
            >>> L1 = _PETScMatrixFromShape(rows=3, cols=3, bandwidth=2)
            >>> L1.put([3.,10.,numerix.pi,2.5], [0,0,1,2], [2,1,1,0])
            >>> L2 = _PETScIdentityMatrix(size=3, bandwidth=3)
            >>> L2.put([4.38], [2], [1])
            >>> L2.put([4.38,12357.2,1.1], [2,1,0], [1,0,2])
            
            >>> tmp = numerix.array(((1.23572000e+05, 2.31400000e+01, 3.00000000e+00),
            ...                      (3.88212887e+04, 3.14159265e+00, 0.00000000e+00),
            ...                      (2.50000000e+00, 0.00000000e+00, 2.75000000e+00)))

            >>> numerix.allclose((L1 * L2).numpyArray, tmp)
            1

        or a sparse matrix by a vector

            >>> tmp = numerix.array((29., 6.28318531, 2.5))       
            >>> numerix.allclose(L1 * numerix.array((1,2,3),'d'), tmp)
            1
            
        or a vector by a sparse matrix

            >>> tmp = numerix.array((7.5, 16.28318531,  3.))  
            >>> numerix.allclose(numerix.array((1,2,3),'d') * L1, tmp) ## The multiplication is broken. Numpy is calling __rmul__ for every element instead of with  the whole array.
            1

            
        """
        N = self._shape[1]

        self.matrix.assemblyBegin()
        self.matrix.assemblyEnd()

        if isinstance(other, _PETScMatrix):
            other.matrix.assemblyBegin()
            other.matrix.assemblyEnd()
            copy = self.copy()
            copy.matrix = self.matrix.matMult(other.matrix)
            return copy
        elif isinstance(other, PETSc.Vec):
            y = other.duplicate()
            self.matrix.mult(other, y)
            return y
        else:
            shape = numerix.shape(other)
            if shape == ():
                result = self.copy()
                result.matrix = self.matrix * other
                return result
            elif shape == (N, ):
                y = PETSc.Vec().createWithArray(other, comm=self.matrix.comm)
                result = y.duplicate()
                self.matrix.mult(y, result)
                return result
            else:
                raise TypeError
Esempio n. 9
0
    def __mul__(self, other):
        """Multiply a sparse matrix by another sparse matrix

            >>> L1 = _PETScMatrixFromShape(rows=3, cols=3, bandwidth=2)
            >>> L1.put([3.,10.,numerix.pi,2.5], [0,0,1,2], [2,1,1,0])
            >>> L2 = _PETScIdentityMatrix(size=3, bandwidth=3)
            >>> L2.put([4.38], [2], [1])
            >>> L2.put([4.38,12357.2,1.1], [2,1,0], [1,0,2])

            >>> tmp = numerix.array(((1.23572000e+05, 2.31400000e+01, 3.00000000e+00),
            ...                      (3.88212887e+04, 3.14159265e+00, 0.00000000e+00),
            ...                      (2.50000000e+00, 0.00000000e+00, 2.75000000e+00)))

            >>> numerix.allclose((L1 * L2).numpyArray, tmp)
            1

        or a sparse matrix by a vector

            >>> tmp = numerix.array((29., 6.28318531, 2.5))
            >>> vec = L1 * numerix.array((1,2,3),'d')
            >>> numerix.allclose(vec, tmp)
            1
            >>> _ = vec.destroy()

        or a vector by a sparse matrix

            >>> tmp = numerix.array((7.5, 16.28318531,  3.))
            >>> numerix.allclose(numerix.array((1,2,3),'d') * L1, tmp)
            1

        (The multiplication is broken.  Numpy is calling __rmul__ for every
        element instead of with the whole array.)
        """
        N = self._shape[1]

        self.matrix.assemble()

        if isinstance(other, (_PETScMatrix, PETSc.Vec)):
            return _PETScMatrixFromShape.__mul__(self, other=other)
        else:
            shape = numerix.shape(other)

            if shape == ():
                result = self.copy()
                result.matrix = self.matrix * other
                return result
            else:
                x = other[self._m2m.localNonOverlappingColIDs]
                x = PETSc.Vec().createWithArray(x, comm=self.matrix.comm)

                y = PETSc.Vec().createGhost(
                    ghosts=self._m2m.ghosts.astype('int32'),
                    size=(len(self._m2m.localNonOverlappingColIDs), None),
                    comm=self.matrix.comm)
                self.matrix.mult(x, y)
                arr = self._petsc2fipyGhost(vec=y)
                x.destroy()
                y.destroy()
                return arr
Esempio n. 10
0
 def __getitem__(self, index):
     self.matrix.assemblyBegin()
     self.matrix.assemblyEnd()
     m = self.matrix[index]
     if numerix.shape(m) == ():
         return m
     else:
         return _PETScMatrix(matrix=m)
Esempio n. 11
0
    def _calcValueInline(self):

        id1, id2 = self.mesh._adjacentCellIDs

        tangents1 = self.mesh._faceTangents1
        tangents2 = self.mesh._faceTangents2

        val = self._array.copy()

        faceNormals = self.mesh._orientedFaceNormals
        if numerix.MA.isMaskedArray(faceNormals):
            faceNormals = faceNormals.filled()

        inline._runIterateElementInline(
            """
            int j;
            double t1grad1, t1grad2, t2grad1, t2grad2, N, N2;
            int ID1 = ITEM(id1, i, NULL);
            int ID2 = ITEM(id2, i, NULL);

            if ITEM(exteriorFaces, i, NULL) {
                 N2 = ITEM(facevar, i, NULL);
            } else {
                 N2 = ITEM(var, ID2, NULL);
            }

            N = (N2 - ITEM(var, ID1, NULL)) / ITEM(dAP, i, NULL);

            t1grad1 = t1grad2 = t2grad1 = t2grad2 = 0.;

            t1grad1 += ITEM(tangents1, i, vec) * ITEM(cellGrad, ID1, vec);
            t1grad2 += ITEM(tangents1, i, vec) * ITEM(cellGrad, ID2, vec);
            t2grad1 += ITEM(tangents2, i, vec) * ITEM(cellGrad, ID1, vec);
            t2grad2 += ITEM(tangents2, i, vec) * ITEM(cellGrad, ID2, vec);

            ITEM(val, i, vec) =  ITEM(normals, i, vec) * N;
            ITEM(val, i, vec) += ITEM(tangents1, i, vec) * (t1grad1 + t1grad2) / 2.;
            ITEM(val, i, vec) += ITEM(tangents2, i, vec) * (t2grad1 + t2grad2) / 2.;
        """,
            tangents1=tangents1,
            tangents2=tangents2,
            cellGrad=self.var.grad.numericValue,
            normals=faceNormals,
            id1=id1,
            id2=id2,
            dAP=numerix.array(self.mesh._cellDistances),
            var=self.var.numericValue,
            facevar=self.var.faceValue.numericValue,
            exteriorFaces=self.mesh.exteriorFaces.numericValue,
            val=val,
            ni=tangents1.shape[1],
            shape=numerix.array(numerix.shape(tangents1)))

        return self._makeValue(value=val)
Esempio n. 12
0
    def _calcValueInline(self):

        id1, id2 = self.mesh._adjacentCellIDs

        tangents1 = self.mesh._faceTangents1
        tangents2 = self.mesh._faceTangents2

        val = self._array.copy()

        faceNormals = self.mesh._orientedFaceNormals
        if numerix.MA.isMaskedArray(faceNormals):
            faceNormals = faceNormals.filled()

        inline._runIterateElementInline("""
            int j;
            double t1grad1, t1grad2, t2grad1, t2grad2, N, N2;
            int ID1 = ITEM(id1, i, NULL);
            int ID2 = ITEM(id2, i, NULL);

            if ITEM(exteriorFaces, i, NULL) {
                 N2 = ITEM(facevar, i, NULL);
            } else {
                 N2 = ITEM(var, ID2, NULL);
            }

            N = (N2 - ITEM(var, ID1, NULL)) / ITEM(dAP, i, NULL);

            t1grad1 = t1grad2 = t2grad1 = t2grad2 = 0.;

            t1grad1 += ITEM(tangents1, i, vec) * ITEM(cellGrad, ID1, vec);
            t1grad2 += ITEM(tangents1, i, vec) * ITEM(cellGrad, ID2, vec);
            t2grad1 += ITEM(tangents2, i, vec) * ITEM(cellGrad, ID1, vec);
            t2grad2 += ITEM(tangents2, i, vec) * ITEM(cellGrad, ID2, vec);

            ITEM(val, i, vec) =  ITEM(normals, i, vec) * N;
            ITEM(val, i, vec) += ITEM(tangents1, i, vec) * (t1grad1 + t1grad2) / 2.;
            ITEM(val, i, vec) += ITEM(tangents2, i, vec) * (t2grad1 + t2grad2) / 2.;
        """, tangents1 = tangents1,
            tangents2 = tangents2,
            cellGrad = self.var.grad.numericValue,
            normals = faceNormals,
            id1 = id1,
            id2 = id2,
            dAP = numerix.array(self.mesh._cellDistances),
            var = self.var.numericValue,
            facevar = self.var.faceValue.numericValue,
            exteriorFaces = self.mesh.exteriorFaces.numericValue,
            val = val,
            ni = tangents1.shape[1],
            shape=numerix.array(numerix.shape(tangents1)))

        return self._makeValue(value = val)
Esempio n. 13
0
    def _dsUniformLen(self):
        """
        Return True if all entries in `self.ds` are the same length, False
        otherwise.

        Exists to get around the fact that `_calcPhysicalShape` and
        `_calcMeshSpacing` don't work for cylindrical grids.
        """

        # if the first entry in `ds` is non-scalar
        if numerix.shape(self.ds[0]) != ():
            lenDs = len(self.ds[0])

            for d in self.ds[1:]:
                if numerix.shape(d) == () or len(d) != lenDs:
                    return False

        # if any other entry in `ds` is non-scalar and first isn't
        elif True in [numerix.shape(d) != () for d in self.ds[1:]]:
            return False

        return True
Esempio n. 14
0
    def _dsUniformLen(self):
        """
        Return True if all entries in `self.ds` are the same length, False
        otherwise.

        Exists to get around the fact that `_calcPhysicalShape` and
        `_calcMeshSpacing` don't work for cylindrical grids.
        """

        # if the first entry in `ds` is non-scalar
        if numerix.shape(self.ds[0]) != ():
            lenDs = len(self.ds[0])

            for d in self.ds[1:]:
                if numerix.shape(d) == () or len(d) != lenDs:
                    return False

        # if any other entry in `ds` is non-scalar and first isn't
        elif True in [numerix.shape(d) != () for d in self.ds[1:]]:
            return False

        return True
Esempio n. 15
0
    def _buildMatrix(self, var, SparseMatrix, boundaryConditions=(), dt=1., equation=None):

        L , b = self.term._buildMatrix(var,
                                       SparseMatrix,
                                       boundaryConditions=boundaryConditions,
                                       dt=dt,
                                       equation=equation)

        if len(numerix.shape(self.coeff)) == 0:
            matcoeff = float(self.coeff)
        else:
            matcoeff = SparseMatrix(size=len(var), bandwidth=1)
            matcoeff.addAtDiagonal(self.coeff)

        return (matcoeff * L, self.coeff * b)
Esempio n. 16
0
    def _calcFaceCenters(self):
        maskedFaceVertexIDs = MA.filled(self.faceVertexIDs, 0)

        faceVertexCoords = numerix.take(self.vertexCoords, maskedFaceVertexIDs, axis=1)

        if MA.getmask(self.faceVertexIDs) is False:
            faceVertexCoordsMask = numerix.zeros(numerix.shape(faceVertexCoords), 'l')
        else:
            faceVertexCoordsMask = \
              numerix.repeat(MA.getmaskarray(self.faceVertexIDs)[numerix.newaxis,...], 
                             self.dim, axis=0)
            
        faceVertexCoords = MA.array(data=faceVertexCoords, mask=faceVertexCoordsMask)

        return MA.filled(MA.average(faceVertexCoords, axis=1))
Esempio n. 17
0
    def __mul__(self, other):
        """
        Multiply a sparse matrix by another sparse matrix

            >>> L1 = _PysparseMatrixFromShape(rows=3, cols=3)
            >>> L1.put([3.,10.,numerix.pi,2.5], [0,0,1,2], [2,1,1,0])
            >>> L2 = _PysparseIdentityMatrix(size=3)
            >>> L2.put([4.38,12357.2,1.1], [2,1,0], [1,0,2])

            >>> tmp = numerix.array(((1.23572000e+05, 2.31400000e+01, 3.00000000e+00),
            ...                      (3.88212887e+04, 3.14159265e+00, 0.00000000e+00),
            ...                      (2.50000000e+00, 0.00000000e+00, 2.75000000e+00)))

            >>> numerix.allclose((L1 * L2).numpyArray, tmp)
            1

        or a sparse matrix by a vector

            >>> tmp = numerix.array((29., 6.28318531, 2.5))
            >>> numerix.allclose(L1 * numerix.array((1,2,3),'d'), tmp)
            1

        or a vector by a sparse matrix

            >>> tmp = numerix.array((7.5, 16.28318531,  3.))
            >>> numerix.allclose(numerix.array((1,2,3),'d') * L1, tmp) ## The multiplication is broken. Numpy is calling __rmul__ for every element instead of with  the whole array.
            1


        """
        N = self.matrix.shape[1]

        if isinstance(other, _PysparseMatrix):
            return _PysparseMatrix(
                matrix=spmatrix.matrixmultiply(self.matrix, other.matrix))
        else:
            shape = numerix.shape(other)
            if shape == ():
                L = spmatrix.ll_mat(N, N, N)
                L.put(other * numerix.ones(N, 'l'))
                return _PysparseMatrix(
                    matrix=spmatrix.matrixmultiply(self.matrix, L))
            elif shape == (N, ):
                y = numerix.empty((self.matrix.shape[0], ))
                self.matrix.matvec(other, y)
                return y
            else:
                raise TypeError
Esempio n. 18
0
    def __mul__(self, other):
        """
        Multiply a sparse matrix by another sparse matrix
        
            >>> L1 = _PysparseMatrix(size = 3)
            >>> L1.put([3.,10.,numerix.pi,2.5], [0,0,1,2], [2,1,1,0])
            >>> L2 = _PysparseIdentityMatrix(size = 3)
            >>> L2.put([4.38,12357.2,1.1], [2,1,0], [1,0,2])
            
            >>> tmp = numerix.array(((1.23572000e+05, 2.31400000e+01, 3.00000000e+00),
            ...                      (3.88212887e+04, 3.14159265e+00, 0.00000000e+00),
            ...                      (2.50000000e+00, 0.00000000e+00, 2.75000000e+00)))

            >>> numerix.allclose((L1 * L2).getNumpyArray(), tmp)
            1

        or a sparse matrix by a vector

            >>> tmp = numerix.array((29., 6.28318531, 2.5))       
            >>> numerix.allclose(L1 * numerix.array((1,2,3),'d'), tmp)
            1
            
        or a vector by a sparse matrix

            >>> tmp = numerix.array((7.5, 16.28318531,  3.))  
            >>> numerix.allclose(numerix.array((1,2,3),'d') * L1, tmp) ## The multiplication is broken. Numpy is calling __rmul__ for every element instead of with  the whole array.
            1

            
        """
        N = self.matrix.shape[0]

        if isinstance(other, _PysparseMatrix):
            return _PysparseMatrix(matrix = spmatrix.matrixmultiply(self.matrix, other._getMatrix()))
        else:
            shape = numerix.shape(other)
            if shape == ():
                L = spmatrix.ll_mat(N, N, N)
                L.put(other * numerix.ones(N))
                return _PysparseMatrix(matrix = spmatrix.matrixmultiply(self.matrix, L))
            elif shape == (N,):
                y = other.copy()
                self.matrix.matvec(other, y)
                return y
            else:
                raise TypeError
        def _calcValue_(self, alpha, id1, id2):
            val = self._array.copy()
            
            inline._runIterateElementInline("""
                int ID1 = ITEM(id1, i, NULL);
                int ID2 = ITEM(id2, i, NULL);
                double cell1 = ITEM(var, ID1, vec);
                double cell2 = ITEM(var, ID2, vec);
                ITEM(val, i, vec) = (cell2 - cell1) * ITEM(alpha, i, NULL) + cell1;
            """,
            var = self.var.numericValue,
            val = val, 
            alpha = alpha,
            id1 = id1, id2 = id2,
            shape=numerix.array(numerix.shape(val)),
            ni = self.mesh.numberOfFaces)

            return self._makeValue(value = val)
Esempio n. 20
0
        def _calcValue(self):

            id1, id2 = self.mesh._adjacentCellIDs

            tangents1 = self.mesh._faceTangents1
            tangents2 = self.mesh._faceTangents2

            val = self._array.copy()

            inline._runIterateElementInline(
                self.modIn + """
            int j;
            double t1grad1, t1grad2, t2grad1, t2grad2, N;
            int ID1 = ITEM(id1, i, NULL);
            int ID2 = ITEM(id2, i, NULL);
            N = mod(ITEM(var, ID2, NULL) - ITEM(var, ID1, NULL)) / ITEM(dAP, i, NULL);

            t1grad1 = t1grad2 = t2grad1 = t2grad2 = 0.;
                
            t1grad1 += ITEM(tangents1, i, vec) * ITEM(cellGrad, ID1, vec);
            t1grad2 += ITEM(tangents1, i, vec) * ITEM(cellGrad, ID2, vec);
            t2grad1 += ITEM(tangents2, i, vec) * ITEM(cellGrad, ID1, vec);
            t2grad2 += ITEM(tangents2, i, vec) * ITEM(cellGrad, ID2, vec);
                
            ITEM(val, i, vec) =  ITEM(normals, i, vec) * N;
            ITEM(val, i, vec) += ITEM(tangents1, i, vec) * (t1grad1 + t1grad2) / 2.;
            ITEM(val, i, vec) += ITEM(tangents2, i, vec) * (t2grad1 + t2grad2) / 2.;

            """,
                tangents1=tangents1,
                tangents2=tangents2,
                cellGrad=self.var.grad.numericValue,
                normals=numerix.array(self.mesh._orientedFaceNormals),
                id1=numerix.array(id1),
                id2=numerix.array(id2),
                dAP=numerix.array(self.mesh._cellDistances),
                var=self.var.numericValue,
                val=val,
                ni=tangents1.shape[1],
                shape=numerix.array(numerix.shape(val)))

            return self._makeValue(value=val)
Esempio n. 21
0
    def _calcValueInline(self):

        id1, id2 = self.mesh._getAdjacentCellIDs()
        
        tangents1 = self.mesh._getFaceTangents1()
        tangents2 = self.mesh._getFaceTangents2()
 
        val = self._getArray().copy()

        inline._runIterateElementInline("""
            int j;
            double t1grad1, t1grad2, t2grad1, t2grad2, N;
            int ID1 = ITEM(id1, i, NULL);
            int ID2 = ITEM(id2, i, NULL);
            
            N = (ITEM(var, ID2, NULL) - ITEM(var, ID1, NULL)) / ITEM(dAP, i, NULL);

            t1grad1 = t1grad2 = t2grad1 = t2grad2 = 0.;
            
            t1grad1 += ITEM(tangents1, i, vec) * ITEM(cellGrad, ID1, vec);
            t1grad2 += ITEM(tangents1, i, vec) * ITEM(cellGrad, ID2, vec);
            t2grad1 += ITEM(tangents2, i, vec) * ITEM(cellGrad, ID1, vec);
            t2grad2 += ITEM(tangents2, i, vec) * ITEM(cellGrad, ID2, vec);
            
            ITEM(val, i, vec) =  ITEM(normals, i, vec) * N;
            ITEM(val, i, vec) += ITEM(tangents1, i, vec) * (t1grad1 + t1grad2) / 2.;
            ITEM(val, i, vec) += ITEM(tangents2, i, vec) * (t2grad1 + t2grad2) / 2.;
        """,tangents1 = tangents1,
            tangents2 = tangents2,
            cellGrad = self.var.getGrad().getNumericValue(),
            normals = self.mesh._getOrientedFaceNormals(),
            id1 = id1,
            id2 = id2,
            dAP = numerix.array(self.mesh._getCellDistances()),
            var = self.var.getNumericValue(),
            val = val,
            ni = tangents1.shape[1],
            shape=numerix.array(numerix.shape(tangents1)))
            
        return self._makeValue(value = val)
Esempio n. 22
0
    def __mul__(self, other):
        """
        Multiply a sparse matrix by another sparse matrix
    
        >>> L1 = _ScipyMatrixFromShape(size=3)
        >>> L1.put([3.,10.,numerix.pi,2.5], [0,0,1,2], [2,1,1,0])
        >>> L2 = _ScipyIdentityMatrix(size=3)
        >>> L2.put([4.38,12357.2,1.1], [2,1,0], [1,0,2])
        
        >>> tmp = numerix.array(((1.23572000e+05, 2.31400000e+01, 3.00000000e+00),
        ...                      (3.88212887e+04, 3.14159265e+00, 0.00000000e+00),
        ...                      (2.50000000e+00, 0.00000000e+00, 2.75000000e+00)))

        >>> numerix.allclose((L1 * L2).numpyArray, tmp)
        1

        or a sparse matrix by a vector

        >>> tmp = numerix.array((29., 6.28318531, 2.5))       
        >>> numerix.allclose(L1 * numerix.array((1,2,3),'d'), tmp)
        1
        
        or a vector by a sparse matrix

        >>> tmp = numerix.array((7.5, 16.28318531,  3.))  
        >>> numerix.allclose(numerix.array((1,2,3),'d') * L1, tmp) ## The multiplication is broken. Numpy is calling __rmul__ for every element instead of with  the whole array.
        1
        """
        N = self.matrix.shape[0]

        if isinstance(other, _ScipyMatrix):
            return _ScipyMatrix(matrix=(self.matrix * other.matrix))
        else:
            shape = numerix.shape(other)
            if shape == ():
                return _ScipyMatrix(matrix=(self.matrix * other))
            elif shape == (N,):
                return self.matrix * other
            else:
                raise TypeError
Esempio n. 23
0
        def _calcValue(self):

            id1, id2 = self.mesh._adjacentCellIDs
            
            tangents1 = self.mesh._faceTangents1
            tangents2 = self.mesh._faceTangents2
     
            val = self._array.copy()

            inline._runIterateElementInline(self.modIn + """
            int j;
            double t1grad1, t1grad2, t2grad1, t2grad2, N;
            int ID1 = ITEM(id1, i, NULL);
            int ID2 = ITEM(id2, i, NULL);
            N = mod(ITEM(var, ID2, NULL) - ITEM(var, ID1, NULL)) / ITEM(dAP, i, NULL);

            t1grad1 = t1grad2 = t2grad1 = t2grad2 = 0.;
                
            t1grad1 += ITEM(tangents1, i, vec) * ITEM(cellGrad, ID1, vec);
            t1grad2 += ITEM(tangents1, i, vec) * ITEM(cellGrad, ID2, vec);
            t2grad1 += ITEM(tangents2, i, vec) * ITEM(cellGrad, ID1, vec);
            t2grad2 += ITEM(tangents2, i, vec) * ITEM(cellGrad, ID2, vec);
                
            ITEM(val, i, vec) =  ITEM(normals, i, vec) * N;
            ITEM(val, i, vec) += ITEM(tangents1, i, vec) * (t1grad1 + t1grad2) / 2.;
            ITEM(val, i, vec) += ITEM(tangents2, i, vec) * (t2grad1 + t2grad2) / 2.;

            """,tangents1 = tangents1,
                tangents2 = tangents2,
                cellGrad = self.var.grad.numericValue,
                normals = numerix.array(self.mesh._orientedFaceNormals),
                id1 = numerix.array(id1),
                id2 = numerix.array(id2),
                dAP = numerix.array(self.mesh._cellDistances),
                var = self.var.numericValue,
                val = val,
                ni = tangents1.shape[1],
                shape=numerix.array(numerix.shape(val)))
                
            return self._makeValue(value = val)
    def _calcValueIn(self, alpha, id1, id2):
        val = self._getArray().copy()

        inline._runIterateElementInline("""
            int ID1 = ITEM(id1, i, NULL);
            int ID2 = ITEM(id2, i, NULL);
            double cell1 = ITEM(var, ID1, vec);
            double cell2 = ITEM(var, ID2, vec);
            double cell1Xcell2 = cell1 * cell2;
            double tmp = ((cell2 - cell1) * ITEM(alpha, i, NULL) + cell1);
            if (tmp != 0 && cell1Xcell2 > 0.) {
                ITEM(val, i, vec) = cell1Xcell2 / tmp;
            } else {
                ITEM(val, i, vec) = 0.;
            }
        """,
        var = self.var.getNumericValue(),
        val = val, 
        alpha = alpha,
        id1 = id1, id2 = id2,
        shape=numerix.array(numerix.shape(val)),
        ni = self.mesh._getNumberOfFaces())

        return self._makeValue(value = val)
Esempio n. 25
0
    def _calcNumPts(d, n = None, axis = "x"):
        """
        Calculate the number of cells along the specified axis, based
        on either the specified number or on the number elements in the
        cell  `d` spacings.

        Used by the `Grid` meshes.

        This tests a bug that was occurring with PeriodicGrid1D when
        using a numpy float as the argument for the grid spacing.

           >>> from fipy.meshes.periodicGrid1D import PeriodicGrid1D
           >>> PeriodicGrid1D(nx=2, dx=numerix.float32(1.))
           PeriodicGrid1D(dx=1.0, nx=2)
        """

        if type(d) in [int, float] or numerix.shape(d) == ():
            n = int(n or 1)
        else:
            n = int(n or len(d))
            if n != len(d) and len(d) != 1:
                raise IndexError("n%s != len(d%s)" % (axis, axis))

        return n
Esempio n. 26
0
    def __mul__(self, other):
        """
        Multiply a sparse matrix by another sparse matrix.

            >>> L1 = _TrilinosMatrix(size=3)
            >>> L1.addAt((3,10,numerix.pi,2.5), (0,0,1,2), (2,1,1,0))
            >>> L2 = _TrilinosIdentityMatrix(size=3)
            >>> L2.addAt((4.38,12357.2,1.1), (2,1,0), (1,0,2))

            >>> tmp = numerix.array(((1.23572000e+05, 2.31400000e+01, 3.00000000e+00),
            ...                      (3.88212887e+04, 3.14159265e+00, 0.00000000e+00),
            ...                      (2.50000000e+00, 0.00000000e+00, 2.75000000e+00)))

            >>> for i in range(0,3):
            ...     for j in range(0,3):
            ...         numerix.allclose(((L1*L2)[i,j],), tmp[i,j])
            True
            True
            True
            True
            True
            True
            True
            True
            True

        or a sparse matrix by a vector

            >>> tmp = numerix.array((29., 6.28318531, 2.5))
            >>> numerix.allclose(L1 * numerix.array((1,2,3),'d'), tmp)
            1

        or a vector by a sparse matrix

            >>> tmp = numerix.array((7.5, 16.28318531,  3.))
            >>> numerix.allclose(numerix.array((1,2,3),'d') * L1, tmp)
            1


        """
        N = self._getMatrix().NumMyCols()

        if isinstance(other, _TrilinosMatrixBase):
            if isinstance(other._getMatrix(), Epetra.RowMatrix):

                if not self._getMatrix().Filled():
                    self._getMatrix().FillComplete()

                if not other._getMatrix().Filled():
                    other._getMatrix().FillComplete()

                result = Epetra.CrsMatrix(Epetra.Copy, self.nonOverlappingMap, 0)

                EpetraExt.Multiply(self._getMatrix(), False, other._getMatrix(), False, result)
                copy = self.copy()
                copy.matrix = result
                return copy
            else:
                raise TypeError

        else:
            shape = numerix.shape(other)
            if shape == ():
                result = self.copy()
                result._getMatrix().Scale(other)
                return result
            elif shape == (N,):

                if not self._getMatrix().Filled():
                    self._getMatrix().FillComplete()

                y = _numpyToTrilinosVector(other, self.nonOverlappingMap)
                result = Epetra.Vector(self.nonOverlappingMap)
                self._getMatrix().Multiply(False, y, result)
                return _trilinosToNumpyVector(result)
            else:
                raise TypeError
    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
Esempio n. 28
0
    def constrain(self, value, where=None):
        r"""
        Constrains the `CellVariable` to `value` at a location specified by `where`. 

            >>> from fipy import *
            >>> m = Grid1D(nx=3)
            >>> v = CellVariable(mesh=m, value=m.cellCenters[0])
            >>> v.constrain(0., where=m.facesLeft)
            >>> v.faceGrad.constrain([1.], where=m.facesRight)
            >>> print v.faceGrad
            [[ 1.  1.  1.  1.]]
            >>> print v.faceValue
            [ 0.   1.   2.   2.5]
            
        Changing the constraint changes the dependencies
        
            >>> v.constrain(1., where=m.facesLeft)
            >>> print v.faceGrad
            [[-1.  1.  1.  1.]]
            >>> print v.faceValue
            [ 1.   1.   2.   2.5]

        Constraints can be `Variable`
        
            >>> c = Variable(0.)
            >>> v.constrain(c, where=m.facesLeft)
            >>> print v.faceGrad
            [[ 1.  1.  1.  1.]]
            >>> print v.faceValue
            [ 0.   1.   2.   2.5]
            >>> c.value = 1.
            >>> print v.faceGrad
            [[-1.  1.  1.  1.]]
            >>> print v.faceValue
            [ 1.   1.   2.   2.5]

        Constraints can have a `Variable` mask.

            >>> v = CellVariable(mesh=m)
            >>> mask = FaceVariable(mesh=m, value=m.facesLeft)
            >>> v.constrain(1., where=mask)
            >>> print v.faceValue
            [ 1.  0.  0.  0.]
            >>> mask[:] = mask | m.facesRight
            >>> print v.faceValue
            [ 1.  0.  0.  1.]
            
        """
        from fipy.boundaryConditions.constraint import Constraint
        if not isinstance(value, Constraint):
            value = Constraint(value=value, where=where)
            
        if numerix.shape(value.where)[-1] == self.mesh.numberOfFaces:
            
            if not hasattr(self, 'faceConstraints'):
                self.faceConstraints = []
            self.faceConstraints.append(value)
            self._requires(value.value)
            # self._requires(value.where) ???
            self._markStale()
        else:
##            _MeshVariable.constrain(value, where)
            super(CellVariable, self).constrain(value, where)
Esempio n. 29
0
    def __mul__(self, other):
        """
        Multiply a sparse matrix by another sparse matrix.

            >>> L1 = _TrilinosMatrix(size=3)
            >>> L1.addAt((3,10,numerix.pi,2.5), (0,0,1,2), (2,1,1,0))
            >>> L2 = _TrilinosIdentityMatrix(size=3)
            >>> L2.addAt((4.38,12357.2,1.1), (2,1,0), (1,0,2))

            >>> tmp = numerix.array(((1.23572000e+05, 2.31400000e+01, 3.00000000e+00),
            ...                      (3.88212887e+04, 3.14159265e+00, 0.00000000e+00),
            ...                      (2.50000000e+00, 0.00000000e+00, 2.75000000e+00)))

            >>> for i in range(0,3):
            ...     for j in range(0,3):
            ...         numerix.allclose(((L1*L2)[i,j],), tmp[i,j])
            True
            True
            True
            True
            True
            True
            True
            True
            True

        or a sparse matrix by a vector

            >>> tmp = numerix.array((29., 6.28318531, 2.5))
            >>> numerix.allclose(L1 * numerix.array((1,2,3),'d'), tmp)
            1

        or a vector by a sparse matrix

            >>> tmp = numerix.array((7.5, 16.28318531,  3.))
            >>> numerix.allclose(numerix.array((1,2,3),'d') * L1, tmp)
            1


        """
        if not self._getMatrix().Filled():
            self._getMatrix().FillComplete()

        N = self._getMatrix().NumMyCols()

        if isinstance(other, _TrilinosMatrixBase):
            return _TrilinosMatrix.__mul__(self, other=other)
        else:
            shape = numerix.shape(other)
            if shape == ():
                result = self.copy()
                result._getMatrix().Scale(other)
                return result
            else:
                if isinstance(other, Epetra.Vector):
                    other_map = other.Map()
                else:
                    other_map = self.overlappingMap

                if other_map.SameAs(self.overlappingMap):
                    localNonOverlappingCellIDs = self.mesh._getLocalNonOverlappingCellIDs()
                    other = Epetra.Vector(self.nonOverlappingMap,
                                          other[localNonOverlappingCellIDs])

                if other.Map().SameAs(self.matrix.RowMap()):

                    nonoverlapping_result = Epetra.Vector(self.nonOverlappingMap)

                    self._getMatrix().Multiply(False, other, nonoverlapping_result)

                    if other_map.SameAs(self.overlappingMap):
                        overlapping_result = Epetra.Vector(self.overlappingMap)
                        overlapping_result.Import(nonoverlapping_result,
                                                  Epetra.Import(self.overlappingMap,
                                                                self.nonOverlappingMap),
                                                  Epetra.Insert)

                        return overlapping_result
                    else:
                        return nonoverlapping_result
                else:
                    raise TypeError("%s: %s != (%d,)" % (self.__class__, str(shape), N))
Esempio n. 30
0
# Calculate H-field for uniaxial anisotropy
HuniaxBase = HeffUniaxialAnisotropyKM(gridCoor, uAxis, Ku2, Msat)

HeffBase = HuniaxBase

TuniaxBase = calculateDampingTerm(gridCoor / numerix.linalg.norm(gridCoor), HeffBase)
TuniaxBase = numerix.multiply(TuniaxBase, alphaDamping)
TuniaxBase = TuniaxBase + calculatePrecessionTerm(gridCoor / numerix.linalg.norm(gridCoor), HeffBase)
TuniaxBase = numerix.multiply(TuniaxBase, (-1.0 * gamFac))

TeffBase = TuniaxBase
Teff = CellVariable(mesh=mesh, value=TeffBase)
#phi = CellVariable(name=r"$\Phi$", mesh=mesh) # doctest: +GMSH
phi = CellVariable(mesh=mesh, value=0.25 / numerix.pi)
print(numerix.shape(TeffBase))
print(max(numerix.linalg.norm(TeffBase,axis=0)))

if __name__ == "__main__":
    try:
        print("\n done") #Intermediate Print Statement
        viewer = VTKViewer(vars=phi,datamin=0., datamax=1.) #Changed Statement
        print("\n Daemon file") #Intermediate Print Statement
    except (NameError,ImportError,SystemError,TypeError):
        viewer = VTKViewer(vars=phi,datamin=0., datamax=1.) #Changed Statement


viewer.plot(filename="trial.vtk") #It will only save the final vtk file. You can change the name

eqI = (TransientTerm()
      == DiffusionTerm(coeff=D)
Esempio n. 31
0
    def constrain(self, value, where=None):
        r"""
        Constrains the `CellVariable` to `value` at a location specified by `where`. 

            >>> from fipy import *
            >>> m = Grid1D(nx=3)
            >>> v = CellVariable(mesh=m, value=m.cellCenters[0])
            >>> v.constrain(0., where=m.facesLeft)
            >>> v.faceGrad.constrain([1.], where=m.facesRight)
            >>> print v.faceGrad
            [[ 1.  1.  1.  1.]]
            >>> print v.faceValue
            [ 0.   1.   2.   2.5]
            
        Changing the constraint changes the dependencies
        
            >>> v.constrain(1., where=m.facesLeft)
            >>> print v.faceGrad
            [[-1.  1.  1.  1.]]
            >>> print v.faceValue
            [ 1.   1.   2.   2.5]

        Constraints can be `Variable`
        
            >>> c = Variable(0.)
            >>> v.constrain(c, where=m.facesLeft)
            >>> print v.faceGrad
            [[ 1.  1.  1.  1.]]
            >>> print v.faceValue
            [ 0.   1.   2.   2.5]
            >>> c.value = 1.
            >>> print v.faceGrad
            [[-1.  1.  1.  1.]]
            >>> print v.faceValue
            [ 1.   1.   2.   2.5]

        Constraints can have a `Variable` mask.

            >>> v = CellVariable(mesh=m)
            >>> mask = FaceVariable(mesh=m, value=m.facesLeft)
            >>> v.constrain(1., where=mask)
            >>> print v.faceValue
            [ 1.  0.  0.  0.]
            >>> mask[:] = mask | m.facesRight
            >>> print v.faceValue
            [ 1.  0.  0.  1.]
            
        """
        from fipy.boundaryConditions.constraint import Constraint
        if not isinstance(value, Constraint):
            value = Constraint(value=value, where=where)

        if numerix.shape(value.where)[-1] == self.mesh.numberOfFaces:

            if not hasattr(self, 'faceConstraints'):
                self.faceConstraints = []
            self.faceConstraints.append(value)
            self._requires(value.value)
            # self._requires(value.where) ???
            self._markStale()
        else:
            ##            _MeshVariable.constrain(value, where)
            super(CellVariable, self).constrain(value, where)
Esempio n. 32
0
    def __init__(self, mesh, name='', value=0., rank=None, elementshape=None, 
                 unit=None, cached=1):
        """
        :Parameters:
          - `mesh`: the mesh that defines the geometry of this `Variable`
          - `name`: the user-readable name of the `Variable`
          - `value`: the initial value
          - `rank`: the rank (number of dimensions) of each element of this 
            `Variable`. Default: 0
          - `elementshape`: the shape of each element of this variable
             Default: `rank * (mesh.getDim(),)`
          - `unit`: the physical units of the `Variable`
        """
        from fipy.tools import debug

        if isinstance(value, (list, tuple)):
            value = numerix.array(value)
            
        if isinstance(value, _MeshVariable):
            if mesh is None:
                mesh = value.mesh
            elif mesh != value.mesh:
                raise ValueError, "The new 'Variable' must use the same mesh as the supplied value"

        self.mesh = mesh
        value = self._globalToLocalValue(value)
        
        if value is None:
            array = None
        elif not isinstance(value, _Constant) and isinstance(value, Variable):
            name = name or value.name
            unit = None
            if isinstance(value, _MeshVariable):
                if not isinstance(value, self._getVariableClass()):
                    raise TypeError, "A '%s' cannot be cast to a '%s'" % (value._getVariableClass().__name__, 
                                                                          self._getVariableClass().__name__)
                if elementshape is not None and elementshape != value.shape[:-1]:
                    raise ValueError, "'elementshape' != shape of elements of 'value'"

                if rank is not None and rank != value.getRank():
                    raise ValueError, "'rank' != rank of 'value'"

                elementshape = value.shape[:-1]
                array = None

#             value = value._copyValue()

        if elementshape is None:
            valueShape = numerix.getShape(value)
            if valueShape != () and valueShape[-1] == self._getShapeFromMesh(mesh)[-1]:
                if elementshape is not None and elementshape != valueShape[:-1]:
                    raise ValueError, "'elementshape' != shape of elements of 'value'"

                if rank is not None and rank != len(valueShape[:-1]):
                    raise ValueError, "'rank' != rank of 'value'"
                elementshape = valueShape[:-1]
            elif rank is None and elementshape is None:
                elementshape = valueShape

        if rank is None:
            if elementshape is None:
                elementshape = ()
        elif elementshape is None:
            elementshape = rank * (mesh.getDim(),)
        elif len(elementshape) != rank:
            raise ValueError, 'len(elementshape) != rank'
                
        self.elementshape = elementshape
        
        if not locals().has_key("array"):
            if numerix._isPhysical(value):
                dtype = numerix.obj2sctype(value.value)
            else:
                dtype = numerix.obj2sctype(value)
            array = numerix.zeros(self.elementshape 
                                  + self._getShapeFromMesh(mesh),
                                  dtype)
            if numerix._broadcastShape(array.shape, numerix.shape(value)) is None:
                if not isinstance(value, Variable):
                    value = _Constant(value)
                value = value[..., numerix.newaxis]
                                  
        Variable.__init__(self, name=name, value=value, unit=unit, 
                          array=array, cached=cached)
Esempio n. 33
0
    def __mul__(self, other):
        """
        Multiply a sparse matrix by another sparse matrix.

            >>> L1 = _TrilinosMatrixFromShape(rows=3, cols=3)
            >>> L1.addAt((3, 10, numerix.pi, 2.5), (0, 0, 1, 2), (2, 1, 1, 0))
            >>> L2 = _TrilinosIdentityMatrix(size=3)
            >>> L2.addAt((4.38, 12357.2, 1.1), (2, 1, 0), (1, 0, 2))

            >>> tmp = numerix.array(((1.23572000e+05, 2.31400000e+01, 3.00000000e+00),
            ...                      (3.88212887e+04, 3.14159265e+00, 0.00000000e+00),
            ...                      (2.50000000e+00, 0.00000000e+00, 2.75000000e+00)))

            >>> L = (L1 * L2).numpyArray

            >>> print(numerix.allclose(tmp, L))
            True

        or a sparse matrix by a vector

            >>> tmp = numerix.array((29., 6.28318531, 2.5))
            >>> print(numerix.allclose(L1 * numerix.array((1, 2, 3), 'd'), tmp)) # doctest: +SERIAL
            True

        or a vector by a sparse matrix

            >>> tmp = numerix.array((7.5, 16.28318531,  3.))
            >>> numerix.allclose(numerix.array((1, 2, 3), 'd') * L1, tmp) # doctest: +SERIAL
            True

        Should be able to multiply an overlapping value obtained from a
        `CellVariable`. This is required to make the `--no-pysparse` flag
        work correctly.

            >>> from fipy import *
            >>> m = Grid1D(nx=6)
            >>> v0 = CellVariable(mesh=m, value=numerix.arange(m.globalNumberOfCells, dtype=float))
            >>> v1 = CellVariable(mesh=m, value=_TrilinosIdentityMeshMatrix(mesh=m) * v0.value)
            >>> print(numerix.allclose(v0, v1))
            True

        """
        self.fillComplete()

        N = self.matrix.NumMyCols()

        if isinstance(other, _TrilinosMatrix):
            return super(_TrilinosMeshMatrix, self).__mul__(other=other)
        else:
            shape = numerix.shape(other)

            if shape == ():
                result = self.copy()
                result.matrix.Scale(other)
                return result
            else:

                if isinstance(other, Epetra.Vector):
                    other_map = other.Map()
                else:
                    other_map = self.colMap

                if other_map.SameAs(self.colMap):
                    localNonOverlappingColIDs = self._m2m.localNonOverlappingColIDs

                    other = Epetra.Vector(self.domainMap,
                                          other[localNonOverlappingColIDs])

                if other.Map().SameAs(self.matrix.DomainMap()):
                    nonoverlapping_result = Epetra.Vector(self.rangeMap)
                    self.matrix.Multiply(False, other, nonoverlapping_result)

                    if other_map.SameAs(self.colMap):
                        overlapping_result = Epetra.Vector(self.colMap)
                        overlapping_result.Import(
                            nonoverlapping_result,
                            Epetra.Import(self.colMap, self.domainMap),
                            Epetra.Insert)

                        return overlapping_result
                    else:
                        return nonoverlapping_result

                else:
                    raise TypeError("%s: %s != (%d,)" %
                                    (self.__class__, str(shape), N))
Esempio n. 34
0
    def __mul__(self, other):
        """
        Multiply a sparse matrix by another sparse matrix.
        
            >>> L1 = _TrilinosMatrix(size=3)
            >>> L1.addAt((3,10,numerix.pi,2.5), (0,0,1,2), (2,1,1,0))
            >>> L2 = _TrilinosIdentityMatrix(size=3)
            >>> L2.addAt((4.38,12357.2,1.1), (2,1,0), (1,0,2))
            
            >>> tmp = numerix.array(((1.23572000e+05, 2.31400000e+01, 3.00000000e+00),
            ...                      (3.88212887e+04, 3.14159265e+00, 0.00000000e+00),
            ...                      (2.50000000e+00, 0.00000000e+00, 2.75000000e+00)))

            >>> for i in range(0,3):
            ...     for j in range(0,3):
            ...         numerix.allclose(((L1*L2)[i,j],), tmp[i,j])
            True
            True
            True
            True
            True
            True
            True
            True
            True

        or a sparse matrix by a vector

            >>> tmp = numerix.array((29., 6.28318531, 2.5))       
            >>> numerix.allclose(L1 * numerix.array((1,2,3),'d'), tmp)
            1
            
        or a vector by a sparse matrix

            >>> tmp = numerix.array((7.5, 16.28318531,  3.))  
            >>> numerix.allclose(numerix.array((1,2,3),'d') * L1, tmp) 
            1

            
        """
        if not self._getMatrix().Filled():
            self._getMatrix().FillComplete()

        N = self._getMatrix().NumMyCols()

        if isinstance(other, _TrilinosMatrixBase):
            return _TrilinosMatrix.__mul__(self, other=other)
        else:
            shape = numerix.shape(other)
            if shape == ():
                result = self.copy()
                result._getMatrix().Scale(other)
                return result
            else:
                if isinstance(other, Epetra.Vector):
                    other_map = other.Map()
                else:
                    other_map = self.overlappingMap

                if other_map.SameAs(self.overlappingMap):
                    localNonOverlappingCellIDs = self.mesh._getLocalNonOverlappingCellIDs()
                    other = Epetra.Vector(self.nonOverlappingMap, 
                                          other[localNonOverlappingCellIDs])

                if other.Map().SameAs(self.matrix.RowMap()):

                    nonoverlapping_result = Epetra.Vector(self.nonOverlappingMap)
                    
                    self._getMatrix().Multiply(False, other, nonoverlapping_result)
                
                    if other_map.SameAs(self.overlappingMap):
                        overlapping_result = Epetra.Vector(self.overlappingMap)
                        overlapping_result.Import(nonoverlapping_result, 
                                                  Epetra.Import(self.overlappingMap, 
                                                                self.nonOverlappingMap), 
                                                  Epetra.Insert)

                        return overlapping_result
                    else:
                        return nonoverlapping_result
                else:
                    raise TypeError("%s: %s != (%d,)" % (self.__class__, str(shape), N))
Esempio n. 35
0
    def __mul__(self, other):
        """
        Multiply a sparse matrix by another sparse matrix.

        >>> L1 = _TrilinosMatrixFromShape(rows=3, cols=3)
        >>> L1.addAt((3, 10, numerix.pi, 2.5), (0, 0, 1, 2), (2, 1, 1, 0))
        >>> L2 = _TrilinosIdentityMatrix(size=3)
        >>> L2.addAt((4.38, 12357.2, 1.1), (2, 1, 0), (1, 0, 2))

        >>> tmp = numerix.array(((1.23572000e+05, 2.31400000e+01, 3.00000000e+00),
        ...                      (3.88212887e+04, 3.14159265e+00, 0.00000000e+00),
        ...                      (2.50000000e+00, 0.00000000e+00, 2.75000000e+00)))

        >>> L = (L1 * L2).numpyArray

        >>> print(numerix.allclose(tmp, L)) # doctest: +SERIAL
        True

        or a sparse matrix by a vector

        >>> tmp = numerix.array((29., 6.28318531, 2.5))
        >>> print(numerix.allclose(L1 * numerix.array((1, 2, 3), 'd'), tmp)) # doctest: +SERIAL
        True

        or a vector by a sparse matrix

        >>> tmp = numerix.array((7.5, 16.28318531,  3.))
        >>> print(numerix.allclose(numerix.array((1, 2, 3), 'd') * L1, tmp))  # doctest: +SERIAL
        True


        """
        N = self.matrix.NumMyCols()

        if isinstance(other, _TrilinosMatrix):
            if isinstance(other.matrix, Epetra.RowMatrix):
                self.fillComplete()
                other.fillComplete()

                result = Epetra.CrsMatrix(Epetra.Copy, self.rowMap, 0)

                EpetraExt.Multiply(self.matrix, False, other.matrix, False,
                                   result)
                copy = self.copy()
                copy.matrix = result
                return copy
            else:
                raise TypeError

        else:
            shape = numerix.shape(other)
            if shape == ():
                result = self.copy()
                result.matrix.Scale(other)
                return result
            elif shape == (N, ):
                self.fillComplete()

                y = Epetra.Vector(self.domainMap, other)
                result = Epetra.Vector(self.rangeMap)
                self.matrix.Multiply(False, y, result)
                return numerix.array(result)
            else:
                raise TypeError
Esempio n. 36
0
    def __mul__(self, other):
        """
        Multiply a sparse matrix by another sparse matrix.
        
            >>> L1 = _TrilinosMatrix(size=3)
            >>> L1.addAt((3,10,numerix.pi,2.5), (0,0,1,2), (2,1,1,0))
            >>> L2 = _TrilinosIdentityMatrix(size=3)
            >>> L2.addAt((4.38,12357.2,1.1), (2,1,0), (1,0,2))
            
            >>> tmp = numerix.array(((1.23572000e+05, 2.31400000e+01, 3.00000000e+00),
            ...                      (3.88212887e+04, 3.14159265e+00, 0.00000000e+00),
            ...                      (2.50000000e+00, 0.00000000e+00, 2.75000000e+00)))

            >>> for i in range(0,3):
            ...     for j in range(0,3):
            ...         numerix.allclose(((L1*L2)[i,j],), tmp[i,j])
            True
            True
            True
            True
            True
            True
            True
            True
            True

        or a sparse matrix by a vector

            >>> tmp = numerix.array((29., 6.28318531, 2.5))       
            >>> numerix.allclose(L1 * numerix.array((1,2,3),'d'), tmp)
            1
            
        or a vector by a sparse matrix

            >>> tmp = numerix.array((7.5, 16.28318531,  3.))  
            >>> numerix.allclose(numerix.array((1,2,3),'d') * L1, tmp) 
            1

            
        """
        N = self._getMatrix().NumMyCols()

        if isinstance(other, _TrilinosMatrixBase):
            if isinstance(other._getMatrix(), Epetra.RowMatrix):
            
                if not self._getMatrix().Filled():
                    self._getMatrix().FillComplete()
                    
                if not other._getMatrix().Filled():
                    other._getMatrix().FillComplete()

                result = Epetra.CrsMatrix(Epetra.Copy, self.nonOverlappingMap, 0)

                EpetraExt.Multiply(self._getMatrix(), False, other._getMatrix(), False, result)
                copy = self.copy()
                copy.matrix = result
                return copy
            else:
                raise TypeError
                
        else:
            shape = numerix.shape(other)
            if shape == ():
                result = self.copy()
                result._getMatrix().Scale(other)
                return result
            elif shape == (N,):

                if not self._getMatrix().Filled():
                    self._getMatrix().FillComplete()

                y = _numpyToTrilinosVector(other, self.nonOverlappingMap)
                result = Epetra.Vector(self.nonOverlappingMap)
                self._getMatrix().Multiply(False, y, result)
                return _trilinosToNumpyVector(result)
            else:
                raise TypeError
Esempio n. 37
0
 def __getitem__(self, index):
     self.matrix.assemble()
     m = self.matrix[index]
     if numerix.shape(m) != ():
         m = _PETScMatrix(matrix=m)
     return m
    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
Esempio n. 39
0
    def __init__(self,
                 mesh,
                 name='',
                 value=0.,
                 rank=None,
                 elementshape=None,
                 unit=None,
                 cached=1):
        """
        :Parameters:
          - `mesh`: the mesh that defines the geometry of this `Variable`
          - `name`: the user-readable name of the `Variable`
          - `value`: the initial value
          - `rank`: the rank (number of dimensions) of each element of this 
            `Variable`. Default: 0
          - `elementshape`: the shape of each element of this variable
             Default: `rank * (mesh.dim,)`
          - `unit`: the physical units of the `Variable`
        """
        if isinstance(value, (list, tuple)):
            value = numerix.array(value)

        if isinstance(value, _MeshVariable):
            if mesh is None:
                mesh = value.mesh
            elif mesh != value.mesh:
                raise ValueError, "The new 'Variable' must use the same mesh as the supplied value"

        self.mesh = mesh
        value = self._globalToLocalValue(value)

        if value is None:
            array = None
        elif not isinstance(value, _Constant) and isinstance(value, Variable):
            name = name or value.name
            unit = None
            if isinstance(value, _MeshVariable):
                if not isinstance(value, self._variableClass):
                    raise TypeError, "A '%s' cannot be cast to a '%s'" % (
                        value._variableClass.__name__,
                        self._variableClass.__name__)
                if elementshape is not None and elementshape != value.shape[:
                                                                            -1]:
                    raise ValueError, "'elementshape' != shape of elements of 'value'"

                if rank is not None and rank != value.rank:
                    raise ValueError, "'rank' != rank of 'value'"

                elementshape = value.shape[:-1]
                array = None

#             value = value._copyValue()

        if elementshape is None:
            valueShape = numerix.getShape(value)
            if valueShape != () and valueShape[-1] == self._getShapeFromMesh(
                    mesh)[-1]:
                if elementshape is not None and elementshape != valueShape[:-1]:
                    raise ValueError, "'elementshape' != shape of elements of 'value'"

                if rank is not None and rank != len(valueShape[:-1]):
                    raise ValueError, "'rank' != rank of 'value'"
                elementshape = valueShape[:-1]
            elif rank is None and elementshape is None:
                elementshape = valueShape

        if rank is None:
            if elementshape is None:
                elementshape = ()
        elif elementshape is None:
            elementshape = rank * (mesh.dim, )
        elif len(elementshape) != rank:
            raise ValueError, 'len(elementshape) != rank'

        self.elementshape = elementshape

        if not "array" in locals():
            if numerix._isPhysical(value):
                dtype = numerix.obj2sctype(value.value)
            else:
                dtype = numerix.obj2sctype(value)
            #print "meshvariable elshape: ",self.elementshape
            #print "meshvariable _getShapeFromMesh: ",self._getShapeFromMesh(mesh)
            array = numerix.zeros(
                self.elementshape + self._getShapeFromMesh(mesh), dtype)
            if numerix._broadcastShape(array.shape,
                                       numerix.shape(value)) is None:
                if not isinstance(value, Variable):
                    value = _Constant(value)
                value = value[..., numerix.newaxis]

        Variable.__init__(self,
                          name=name,
                          value=value,
                          unit=unit,
                          array=array,
                          cached=cached)
Esempio n. 40
0
# ### Load mesh details from a saved file

# In[411]:

mesh = pickle.load(
    open("mesh_details_cellsize_0pt008_extrude_1pt00001.p", "rb"))
gridCoor = mesh.cellCenters
mUnit = gridCoor
mNorm = numerix.linalg.norm(mUnit, axis=0)
print('max mNorm=' + str(max(mNorm)))
print('min mNorm=' + str(min(mNorm)))
mAllCell = mUnit / mNorm

# In[412]:

msize = numerix.shape(mAllCell)
number_of_cells = msize[1]
print(number_of_cells)

# ### Loading phi values from a saved file

# In[413]:

phi_value = get_phi_tuple(
    number_of_cells)  # get phi values from a previous .vtk file
phi = CellVariable(name=r"$\Phi$", mesh=mesh, value=phi_value)

# ### To convert into numpy array, save it in numpy file and again store it in a variable

# In[414]: