Exemple #1
0
    def _solve_(self, L, x, b):
        diag = L.takeDiagonal()
        maxdiag = max(numerix.absolute(diag))

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

        LU = splu(L.matrix.asformat("csc"),
                  diag_pivot_thresh=1.,
                  drop_tol=0.,
                  relax=1,
                  panel_size=10,
                  permc_spec=3)

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

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

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

            xError = LU.solve(errorVector)
            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)))

        return x
Exemple #2
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)))
Exemple #3
0
    def _plot(self):

        self.g('set cbrange [' + self._getLimit(('datamin', 'zmin'))  + ':' + self._getLimit(('datamax', 'zmax')) + ']')
        self.g('set view map')
        self.g('set style data pm3d')
        self.g('set pm3d at st solid')
        mesh = self.vars[0].mesh

        if self.vars[0]._variableClass is FaceVariable:
            x, y = mesh.faceCenters
            if isinstance(mesh, Grid2D.__class__):
                nx, ny = mesh.shape
            else:
                N = int(numerix.sqrt(mesh.numberOfCells))
                nx, ny = N, N
        else:
            x, y = mesh.cellCenters
            N = int(numerix.sqrt(mesh.numberOfFaces))
            nx, ny = N, N

        self.g('set dgrid3d %i, %i, 2' % (ny, nx))

        import Gnuplot
        data = Gnuplot.Data(numerix.array(x), numerix.array(y),
                            self.vars[0].value)

        self.g.splot(data)
Exemple #4
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())
Exemple #5
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)))
Exemple #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)
    def _plot(self):

        self.g('set cbrange [' + self._getLimit(('datamin', 'zmin')) + ':' +
               self._getLimit(('datamax', 'zmax')) + ']')
        self.g('set view map')
        self.g('set style data pm3d')
        self.g('set pm3d at st solid')
        mesh = self.vars[0].mesh

        if self.vars[0]._variableClass is FaceVariable:
            x, y = mesh.faceCenters
            if isinstance(mesh, Grid2D.__class__):
                nx, ny = mesh.shape
            else:
                N = int(numerix.sqrt(mesh.numberOfCells))
                nx, ny = N, N
        else:
            x, y = mesh.cellCenters
            N = int(numerix.sqrt(mesh.numberOfFaces))
            nx, ny = N, N

        self.g('set dgrid3d %i, %i, 2' % (ny, nx))

        import Gnuplot
        data = Gnuplot.Data(numerix.array(x), numerix.array(y),
                            self.vars[0].value)

        self.g.splot(data)
    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)
Exemple #9
0
    def _solve_(self, L, x, b):
        diag = L.takeDiagonal()
        maxdiag = max(numerix.absolute(diag))

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

        LU = splu(L.matrix.asformat("csc"), diag_pivot_thresh=1.,
                                            relax=1,
                                            panel_size=10,
                                            permc_spec=3)

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

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

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

            xError = LU.solve(errorVector)
            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)))

        return x
    def _plot(self):

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

        U, V = var.numericValue

        U = numerix.take(U, self.indices)
        V = numerix.take(V, self.indices)
        
        ang = numerix.arctan2(V, U)
        mag = numerix.sqrt(U**2 + V**2)
        
        datamin, datamax = self._autoscale(vars=(mag,),
                                           datamin=self._getLimit('datamin'),
                                           datamax=self._getLimit('datamax'))
        
        mag = numerix.where(mag > datamax, datamax, mag)
        mag = numerix.ma.masked_array(mag, mag < datamin)
        
        if self.log:
            mag = numerix.log10(mag)
            mag = numerix.ma.masked_array(mag, numerix.isnan(mag))
            
        U = mag * numerix.cos(ang)
        V = mag * numerix.sin(ang)

        self._quiver.set_UVC(U, V)
        
        self.axes.set_xlim(xmin=self._getLimit('xmin'),
                           xmax=self._getLimit('xmax'))
        self.axes.set_ylim(ymin=self._getLimit('ymin'),
                           ymax=self._getLimit('ymax'))
Exemple #11
0
    def _getRotationTensor(self, mesh):
        if not hasattr(self, 'rotationTensor'):

            from fipy.variables.faceVariable import FaceVariable
            rotationTensor = FaceVariable(mesh=mesh, rank=2)
            
            rotationTensor[:, 0] = self._getNormals(mesh)

            if mesh.getDim() == 2:
                rotationTensor[:,1] = rotationTensor[:,0].dot((((0, 1), (-1, 0))))
            elif mesh.getDim() ==3:
                epsilon = 1e-20

                div = numerix.sqrt(1 - rotationTensor[2,0]**2)
                flag = numerix.resize(div > epsilon, (mesh.getDim(), mesh._getNumberOfFaces()))

                rotationTensor[0, 1] = 1
                rotationTensor[:, 1] = numerix.where(flag,
                                                     rotationTensor[:,0].dot((((0, 1, 0), (-1, 0, 0), (0, 0, 0)))) / div,
                                                     rotationTensor[:, 1])

                rotationTensor[1, 2] = 1
                rotationTensor[:, 2] = numerix.where(flag,
                                                     rotationTensor[:,0] * rotationTensor[2,0] / div,
                                                     rotationTensor[:, 2])
                rotationTensor[2, 2] = -div
                
            self.rotationTensor = rotationTensor

        return self.rotationTensor
Exemple #12
0
    def __getRotationTensor(self, mesh):
        if not hasattr(self, 'rotationTensor'):

            rotationTensor = FaceVariable(mesh=mesh, rank=2)

            rotationTensor[:, 0] = self._getNormals(mesh)

            if mesh.dim == 2:
                rotationTensor[:, 1] = rotationTensor[:, 0].dot(
                    (((0, 1), (-1, 0))))
            elif mesh.dim == 3:
                epsilon = 1e-20

                div = numerix.sqrt(1 - rotationTensor[2, 0]**2)
                flag = numerix.resize(div > epsilon,
                                      (mesh.dim, mesh.numberOfFaces))

                rotationTensor[0, 1] = 1
                rotationTensor[:, 1] = numerix.where(
                    flag, rotationTensor[:, 0].dot(
                        (((0, 1, 0), (-1, 0, 0), (0, 0, 0)))) / div,
                    rotationTensor[:, 1])

                rotationTensor[1, 2] = 1
                rotationTensor[:, 2] = numerix.where(
                    flag, rotationTensor[:, 0] * rotationTensor[2, 0] / div,
                    rotationTensor[:, 2])
                rotationTensor[2, 2] = -div

            self.rotationTensor = rotationTensor

        return self.rotationTensor
Exemple #13
0
    def _plot(self):

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

        U, V = var.numericValue

        U = numerix.take(U, self.indices)
        V = numerix.take(V, self.indices)

        ang = numerix.arctan2(V, U)
        mag = numerix.sqrt(U**2 + V**2)

        datamin, datamax = self._autoscale(vars=(mag, ),
                                           datamin=self._getLimit('datamin'),
                                           datamax=self._getLimit('datamax'))

        mag = numerix.where(mag > datamax, datamax, mag)
        mag = numerix.ma.masked_array(mag, mag < datamin)

        if self.log:
            mag = numerix.log10(mag)
            mag = numerix.ma.masked_array(mag, numerix.isnan(mag))

        U = mag * numerix.cos(ang)
        V = mag * numerix.sin(ang)

        self._quiver.set_UVC(U, V)

        self.axes.set_xlim(xmin=self._getLimit('xmin'),
                           xmax=self._getLimit('xmax'))
        self.axes.set_ylim(ymin=self._getLimit('ymin'),
                           ymax=self._getLimit('ymax'))
Exemple #14
0
    def _calcFaceNormals(self):
        faceVertexCoords = numerix.take(self.vertexCoords, self.faceVertexIDs, axis=1)
        t1 = faceVertexCoords[:, 1,:] - faceVertexCoords[:, 0,:]
        faceNormals = t1.copy()
        mag = numerix.sqrt(t1[1]**2 + t1[0]**2)
        faceNormals[0] = -t1[1] / mag
        faceNormals[1] = t1[0] / mag

        orientation = 1 - 2 * (numerix.dot(faceNormals, self.cellDistanceVectors) < 0)
        return faceNormals * orientation
Exemple #15
0
 def _calcFaceNormals(self):
     faceVertexCoords = numerix.take(self.vertexCoords, self.faceVertexIDs, axis=1)
     t1 = faceVertexCoords[:,1,:] - faceVertexCoords[:,0,:]
     faceNormals = t1.copy()
     mag = numerix.sqrt(t1[1]**2 + t1[0]**2)
     faceNormals[0] = -t1[1] / mag
     faceNormals[1] = t1[0] / mag
     
     orientation = 1 - 2 * (numerix.dot(faceNormals, self.cellDistanceVectors) < 0)
     return faceNormals * orientation
Exemple #16
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._getMatrix().to_csr())

        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
Exemple #17
0
    def getElectrolyteMask(self):
        x, y = self.getCellCenters()
        
        Y = (y - (self.heightBelowTrench + self.trenchDepth / 2))

        ## taper
        taper = numerix.tan(self.angle) * Y

        ## bow
        if abs(self.bowWidth) > 1e-12 and (-self.trenchDepth / 2 < Y < self.trenchDepth / 2):
            param1 = self.trenchDepth**2 / 8 / self.bowWidth
            param2 = self.bowWidth / 2
            bow = -numerix.sqrt((param1 + param2)**2 - Y**2) + param1 - param2
        else:
            bow = 0

        ## over hang
        Y = y - (self.heightBelowTrench + self.trenchDepth - self.overBumpRadius)

        overBump = 0

        if self.overBumpRadius > 1e-12:            
            overBump += numerix.where(Y > -self.overBumpRadius,
                                      self.overBumpWidth / 2 * (1 + numerix.cos(Y * numerix.pi / self.overBumpRadius)),
                                      0)

        tmp = self.overBumpRadius**2 - Y**2
        tmp = (tmp > 0) * tmp
        overBump += numerix.where((Y > -self.overBumpRadius) & (Y > 0),
                                  numerix.where(Y > self.overBumpRadius,
                                                -self.overBumpRadius,
                                                -(self.overBumpRadius - numerix.sqrt(tmp))),
                                  0)

        return numerix.where(y > self.trenchDepth + self.heightBelowTrench,
                             1,
                             numerix.where(y < self.heightBelowTrench,
                                           0,
                                           numerix.where(x > self.trenchWidth / 2 + taper - bow - overBump,
                                                         0,
                                                         1)))
    def parallelRandom(self):

        if hasattr(self.variance, 'getGlobalValue'):
            variance = self.variance.getGlobalValue()
        else:
            variance = self.variance

        if self.getMesh().communicator.procID == 0:
            return random.normal(self.mean, sqrt(variance),
                                 size = [self.getMesh().globalNumberOfCells])
        else:
            return None
Exemple #19
0
    def parallelRandom(self):

        if hasattr(self.variance, 'globalValue'):
            variance = self.variance.globalValue
        else:
            variance = self.variance

        if self.mesh.communicator.procID == 0:
            return random.normal(self.mean, sqrt(variance),
                                 size = [self.mesh.globalNumberOfCells])
        else:
            return None
Exemple #20
0
    def sqrt(self):
        """
        
            >>> from fipy.meshes.grid1D import Grid1D
            >>> mesh= Grid1D(nx=3)

            >>> from fipy.variables.cellVariable import CellVariable
            >>> var = CellVariable(mesh=mesh, value=((0., 2., 3.),), rank=1)
            >>> print (var.dot(var)).sqrt()
            [ 0.  2.  3.]
            
        """
        return self._UnaryOperatorVariable(lambda a: numerix.sqrt(a))
Exemple #21
0
    def parallelRandom(self):
        from fipy.tools import parallel

        if hasattr(self.variance, 'getGlobalValue'):
            variance = self.variance.getGlobalValue()
        else:
            variance = self.variance

        if parallel.procID == 0:
            return random.normal(self.mean, sqrt(variance),
                                 size = [self.getMesh().globalNumberOfCells])
        else:
            return None
Exemple #22
0
    def _calcFaceCellToCellNormals(self):
        faceCellCentersUp = numerix.take(self._cellCenters, self.faceCellIDs[1], axis=1)
        faceCellCentersDown = numerix.take(self._cellCenters, self.faceCellIDs[0], axis=1)
        faceCellCentersUp = numerix.where(MA.getmaskarray(faceCellCentersUp),
                                          self._faceCenters,
                                          faceCellCentersUp)

        diff = faceCellCentersDown - faceCellCentersUp
        mag = numerix.sqrt(numerix.sum(diff**2))
        faceCellToCellNormals = diff / numerix.resize(mag, (self.dim, len(mag)))

        orientation = 1 - 2 * (numerix.dot(self.faceNormals, faceCellToCellNormals) < 0)
        return faceCellToCellNormals * orientation
    def test_seed_normal(self, unit, loc, scale, coeff, error):

        create = dict(value=3., unit=unit, hasOld=True)
        name = 'MyVar'
        seed = dict(profile='normal',
                    params=dict(loc=loc, scale=scale, coeff=coeff))
        v = ModelVariable(name=name, create=create, seed=seed)

        domain = SedimentDBLDomain()
        v.domain = domain
        if error:
            with pytest.raises(error):
                v.setup()
            return

        else:

            v.setup()

            from scipy.stats import norm
            from fipy.tools import numerix

            C = 1.0 / numerix.sqrt(2 * numerix.pi)

            # loc and scale should be in units of the domain mesh
            if hasattr(loc, 'unit'):
                loc_ = loc.inUnitsOf(domain.depths.unit).value
            else:
                loc_ = loc

            if hasattr(scale, 'unit'):
                scale_ = scale.inUnitsOf(domain.depths.unit).value
            else:
                scale_ = scale

            if unit:
                coeff = PF(coeff, unit)

            normrv = norm(loc=loc_, scale=C**2 * scale_)
            val = coeff * normrv.pdf(domain.depths) * C * scale_

            # from pprint import pprint
            # pprint(zip(v.var, val))
            print(type(val), type(v.var))
            if unit:
                # array comparison between variable & physicalfield is problematic
                val = val.numericValue

            assert numerix.allclose(v.var.numericValue, val)
    def _plot(self):

        self.g('set cbrange [' + self._getLimit(('datamin', 'zmin'))  + ':' + self._getLimit(('datamax', 'zmax')) + ']')
        self.g('set view map')
        self.g('set style data pm3d')
        self.g('set pm3d at st solid')
        mesh = self.vars[0].getMesh()

        if isinstance(mesh, Grid2D.__class__):
            nx, ny = mesh.getShape()
        else:
            N = int(numerix.sqrt(mesh.getNumberOfCells()))
            nx, ny = N, N
            
        self.g('set dgrid3d %i, %i, 2' % (ny, nx))

        x, y = mesh.getCellCenters()
        import Gnuplot
        data = Gnuplot.Data(numerix.array(x), numerix.array(y),
                            self.vars[0].getValue())

        self.g.splot(data)
Exemple #25
0
import os
import sys
import re
from tempfile import mkstemp
from subprocess import Popen, PIPE
from textwrap import dedent

from fipy.tools.parser import parse
from fipy.tools.numerix import sqrt
from fipy.tests import doctestPlus

import examples.phase.anisotropy

numberOfElements = parse('--numberOfElements', action='store',
                         type='int', default=10000)
N = int(sqrt(numberOfElements))

steps = parse('--numberOfSteps', action='store',
              type='int', default=20)

start = parse('--startingStep', action='store',
              type='int', default=0)

cpu0 = parse('--cpuBaseLine', action='store',
              type='float', default=0.)

args = tuple(sys.argv[1:])

dir = os.path.dirname(__file__)

script = doctestPlus._getScript("examples.phase.anisotropy")
Exemple #26
0
 def distance(self, vertex):
     from fipy.tools import numerix
     return numerix.sqrt((vertex.getX() - self.getX())**2 + (vertex.getY() - self.getY())**2)
Exemple #27
0
                             type='int',
                             default=-1)

    from benchmarker import Benchmarker
    bench = Benchmarker()

    numberOfSteps = 5

    bench.start()

    import fipy.tools.numerix as numerix
    if numberOfElements != -1:
        pos = trenchSpacing * cellsBelowTrench / 4 / numberOfElements
        sqr = trenchSpacing * (trenchDepth + boundaryLayerDepth) \
              / (2 * numberOfElements)
        cellSize = pos + numerix.sqrt(pos**2 + sqr)
    else:
        cellSize = 0.1e-7

    yCells = cellsBelowTrench \
             + int((trenchDepth + boundaryLayerDepth) / cellSize)

    xCells = int(trenchSpacing / 2 / cellSize)
    from fipy.meshes.grid2D import Grid2D
    mesh = Grid2D(dx=cellSize, dy=cellSize, nx=xCells, ny=yCells)

    bench.stop('mesh')

    bench.start()

    narrowBandWidth = numberOfCellsInNarrowBand * cellSize
Exemple #28
0
    numberOfElements = parse('--numberOfElements', action = 'store',
        type = 'int', default = -1)

    from benchmarker import Benchmarker
    bench = Benchmarker()

    numberOfSteps = 5

    bench.start()

    import fipy.tools.numerix as numerix
    if numberOfElements != -1:
        pos = trenchSpacing * cellsBelowTrench / 4 / numberOfElements
        sqr = trenchSpacing * (trenchDepth + boundaryLayerDepth) \
              / (2 * numberOfElements)
        cellSize = pos + numerix.sqrt(pos**2 + sqr)
    else:
        cellSize = 0.1e-7

    yCells = cellsBelowTrench \
             + int((trenchDepth + boundaryLayerDepth) / cellSize)

    xCells = int(trenchSpacing / 2 / cellSize)
    from fipy.meshes.grid2D import Grid2D
    mesh = Grid2D(dx = cellSize,
                  dy = cellSize,
                  nx = xCells,
                  ny = yCells)

    bench.stop('mesh')
Exemple #29
0
    KMView.setName('KM')
    KMViewer = make(KMView, limits={'datamax': 2., 'datamin': 0.}, title='')

    TMView = TMVar / TMVar.getCellVolumeAverage()
    TMView.setName('TM')
    TMViewer = make(TMView, limits={'datamax': 2., 'datamin': 0.}, title='')

    for i in range(100):
        for var, eqn in eqs:
            var.updateOld()
        for var, eqn in eqs:
            eqn.solve(var, dt=1.)

    x = mesh.getCellCenters()[:, 0]
    y = mesh.getCellCenters()[:, 1]

    from fipy.tools.numerix import sqrt
    RVar[:] = L / sqrt((x - L / 2)**2 + (y - 2 * L)**2)

    for i in range(100):
        for var, eqn in eqs:
            var.updateOld()
        for var, eqn in eqs:
            eqn.solve(var, dt=1.)

        PNViewer.plot()
        KMViewer.plot()
        TMViewer.plot()

    raw_input("finished")
Exemple #30
0
initialRadius = L / 4.

dx = L / nx
timeStepDuration = cfl * dx / velocity
steps = int(distanceToTravel / dx / cfl)

mesh = Grid2D(dx = dx, dy = dx, nx = nx, ny = nx)

distanceVariable = DistanceVariable(
    name = 'level set variable',
    mesh = mesh,
    value = 1.,
    hasOld = 1
    )

cellRadius = numerix.sqrt((mesh.getCellCenters()[:,0] - L / 2.)**2 + (mesh.getCellCenters()[:,1] - L / 2.)**2)
distanceVariable.setValue(cellRadius - initialRadius)

initialSurfactantValue =  1.

surfactantVariable = SurfactantVariable(
    value = initialSurfactantValue,
    distanceVar = distanceVariable
    )

advectionEquation = buildHigherOrderAdvectionEquation(
    advectionCoeff = velocity)

surfactantEquation = SurfactantEquation(
    distanceVar = distanceVariable)
Exemple #31
0
import re
from tempfile import mkstemp
from subprocess import Popen, PIPE
from textwrap import dedent

from fipy.tools.parser import parse
from fipy.tools.numerix import sqrt
from fipy.tests import doctestPlus

import examples.phase.anisotropy

numberOfElements = parse('--numberOfElements',
                         action='store',
                         type='int',
                         default=10000)
N = int(sqrt(numberOfElements))

steps = parse('--numberOfSteps', action='store', type='int', default=20)

start = parse('--startingStep', action='store', type='int', default=0)

cpu0 = parse('--cpuBaseLine', action='store', type='float', default=0.)

args = tuple(sys.argv[1:])

dir = os.path.dirname(__file__)

script = doctestPlus._getScript("examples.phase.anisotropy")

script = script.replace("__main__", "__DONT_RUN_THIS__")
Exemple #32
0
from fipy import Grid1D, CellVariable, Viewer
from fipy.tools import numerix, dump

import numpy
from scipy.special import wofz


# ----------------- Mesh Generation -----------------------
L = 4.0
nx = 100
mesh = Grid1D(nx=nx, Lx=L)
x = mesh.cellCenters[0] # Cell position

plasma_disp_real = CellVariable(name=r"Re$(X(z))$", mesh=mesh)
plasma_disp_imag = CellVariable(name=r"Im$(X(z))$", mesh=mesh)

full_plasma_disp = numpy.array(1j*numerix.sqrt(numerix.pi)\
		* numerix.exp(-x**2)*wofz(x))
print full_plasma_disp

plasma_disp_real.setValue(full_plasma_disp.real)
plasma_disp_imag.setValue(full_plasma_disp.imag)

initial_viewer = Viewer((plasma_disp_real, plasma_disp_imag),\
		xmin=0.0, legend='best')
raw_input("Pause for Initial Conditions")

Exemple #33
0
    def __init__(self,
                 hours_total=24,
                 day_fraction=0.5,
                 channels=None,
                 **kwargs):
        """
        Initialize an irradiance source in the model domain

        Args:
            hours_total (int, float, PhysicalField): Number of hours in a diel period

            day_fraction (float): Fraction (between 0 and 1) of diel period which is illuminated
                (default: 0.5)

            channels: See :meth:`.create_channel`

            **kwargs: passed to superclass

        """
        self.logger = kwargs.get('logger') or logging.getLogger(__name__)
        self.logger.debug('Init in {}'.format(self.__class__.__name__))
        kwargs['logger'] = self.logger
        super(Irradiance, self).__init__(**kwargs)

        #: the channels in the irradiance entity
        self.channels = {}

        #: the number of hours in a diel period
        self.hours_total = PhysicalField(hours_total, 'h')
        if not (1 <= self.hours_total.value <= 48):
            raise ValueError('Hours total {} should be between (1, 48)'.format(
                self.hours_total))
        # TODO: remove (1, 48) hour constraint on hours_total

        day_fraction = float(day_fraction)
        if not (0 < day_fraction < 1):
            raise ValueError("Day fraction should be between 0 and 1")

        #: fraction of diel period that is illuminated
        self.day_fraction = day_fraction
        #: numer of hours in the illuminated fraction
        self.hours_day = day_fraction * self.hours_total
        #: the time within the diel period which is the zenith of radiation
        self.zenith_time = self.hours_day
        #: the intensity level at the zenith time
        self.zenith_level = 100.0

        C = 1.0 / numerix.sqrt(2 * numerix.pi)
        # to scale the cosine distribution from 0 to 1 (at zenith)

        self._profile = cosine(loc=self.zenith_time,
                               scale=C**2 * self.hours_day)
        # This profile with loc=zenith means that the day starts at "midnight" and zenith occurs
        # in the center of the daylength

        #: a :class:`Variable` for the momentary radiance level at the surface
        self.surface_irrad = Variable(name='irrad_surface',
                                      value=0.0,
                                      unit=None)

        if channels:
            for chinfo in channels:
                self.create_channel(**chinfo)

        self.logger.debug('Created Irradiance: {}'.format(self))
Exemple #34
0
from fipy.variables.cellVariable import CellVariable

L = 1.
nx = 50
cfl = 0.1
initialRadius = L / 4.
k = 1
dx = L / nx
steps = 20

mesh = Grid2D(dx=dx, dy=dx, nx=nx, ny=nx)

distanceVariable = DistanceVariable(
    name='level set variable',
    mesh=mesh,
    value=numerix.sqrt((mesh.getCellCenters()[:, 0] - L / 2.)**2 +
                       (mesh.getCellCenters()[:, 1] - L / 2.)**2) -
    initialRadius,
    hasOld=1)

initialSurfactantValue = 1.

surfactantVariable = SurfactantVariable(value=initialSurfactantValue,
                                        distanceVar=distanceVariable)

velocity = CellVariable(
    name='velocity',
    mesh=mesh,
    value=1.,
)

advectionEquation = buildHigherOrderAdvectionEquation(advectionCoeff=velocity)
Exemple #35
0
L = 1.
nx = 50
cfl = 0.1
initialRadius = L / 4.
k = 1
dx = L / nx
steps = 20

from fipy.tools import serialComm
mesh = Grid2D(dx=dx, dy=dx, nx=nx, ny=nx, communicator=serialComm)

x, y = mesh.cellCenters
distanceVariable = DistanceVariable(
    name='level set variable',
    mesh=mesh,
    value=numerix.sqrt((x - L / 2.)**2 + (y - L / 2.)**2) - initialRadius,
    hasOld=1)

initialSurfactantValue = 1.

surfactantVariable = SurfactantVariable(value=initialSurfactantValue,
                                        distanceVar=distanceVariable)

velocity = CellVariable(
    name='velocity',
    mesh=mesh,
    value=1.,
)

advectionEquation = TransientTerm() + AdvectionTerm(velocity)
Exemple #36
0
#!/usr/bin/env python

## This script was derived from
## 'examples/phase/anisotropy/input.py'

if __name__ == "__main__":
    
    from fipy.tools.parser import parse

    numberOfElements = parse('--numberOfElements', action = 'store',
                          type = 'int', default = 40)
    from fipy.tools import numerix
    N = int(numerix.sqrt(numberOfElements))

    from benchmarker import Benchmarker
    bench = Benchmarker()

    bench.start()

    Length = N * 2.5 / 100.
    nx = N
    ny = N
    dx = Length / nx
    dy = Length / ny
    radius = Length / 4.
    seedCenter = (Length / 2., Length / 2.)
    initialTemperature = -0.4
    from fipy.meshes.grid2D import Grid2D
    mesh = Grid2D(dx=dx, dy=dy, nx=nx, ny=ny)

    bench.stop('mesh')
Exemple #37
0
            def stdParallel(a):
                N = self.mesh.globalNumberOfCells
                mean = self.sum(axis=axis).value / N
                sq_diff = (self - mean)**2

                return numerix.sqrt(sq_diff.sum(axis=axis).value / N)
Exemple #38
0
dx = L / nx
timeStepDuration = cfl * dx / velocity
steps = int(distanceToTravel / dx / cfl)

mesh = Grid2D(dx = dx, dy = dx, nx = nx, ny = nx)

distanceVariable = DistanceVariable(
    name = 'level set variable',
    mesh = mesh,
    value = 1.,
    hasOld = 1
    )

x, y = mesh.cellCenters
cellRadius = numerix.sqrt((x - L / 2.)**2 + (y - L / 2.)**2)
distanceVariable.setValue(cellRadius - initialRadius)

initialSurfactantValue =  1.

surfactantVariable = SurfactantVariable(
    value = initialSurfactantValue,
    distanceVar = distanceVariable
    )

advectionEquation = TransientTerm() + AdvectionTerm(velocity)

from fipy.variables.surfactantConvectionVariable import SurfactantConvectionVariable
surfactantEquation = TransientTerm() - \
    ExplicitUpwindConvectionTerm(SurfactantConvectionVariable(distanceVariable))
Exemple #39
0
dx = L / nx
timeStepDuration = cfl * dx / velocity
steps = int(distanceToTravel / dx / cfl)

mesh = Grid2D(dx = dx, dy = dx, nx = nx, ny = nx)

distanceVariable = DistanceVariable(
    name = 'level set variable',
    mesh = mesh,
    value = 1.,
    hasOld = 1
    )

x, y = mesh.cellCenters
cellRadius = numerix.sqrt((x - L / 2.)**2 + (y - L / 2.)**2)
distanceVariable.setValue(cellRadius - initialRadius)

initialSurfactantValue =  1.

surfactantVariable = SurfactantVariable(
    value = initialSurfactantValue,
    distanceVar = distanceVariable
    )

advectionEquation = TransientTerm() + AdvectionTerm(velocity)

from fipy.variables.surfactantConvectionVariable import SurfactantConvectionVariable
surfactantEquation = TransientTerm() - \
    ExplicitUpwindConvectionTerm(SurfactantConvectionVariable(distanceVariable))
Exemple #40
0
 def _calcTangent1(self):
     norm = self.normal
     mag = numerix.sqrt(norm[0] ** 2 + norm[1] ** 2)
     # 	tan1 = numerix.array((-norm[1],norm[0],0))
     tan1 = PhysicalField(value=(-norm[1], norm[0], 0))
     return tan1 / mag
Exemple #41
0
D = 1.0
U = 100.0
peclet = (U*L/D)
# This is the syntax needed to specify u_x
convCoeff= (1.0,)

# intial condition width (standard deviation)
sigma = 0.05*L

#Defining the variable
c = CellVariable(mesh=mesh, name=r"$c$")

# Setting initial conditions
x = mesh.cellCenters[0]
c.value=0.0
c.setValue(0.05*(1.0/(sigma*numerix.sqrt(2*numerix.pi)))*numerix.exp(-0.5*((x-1.0)/(sigma))**2.0))

# defining the equation
# We write three equations: pure convection, pure diffusion and convection-diffusion
eq = TransientTerm() + VanLeerConvectionTerm(coeff=convCoeff) == 0
# eq = TransientTerm() + ExponentialConvectionTerm(coeff=convCoeff) == 0
# eq = TransientTerm() - DiffusionTerm(coeff=(1/peclet)) == 0
# eq = TransientTerm() + VanLeerConvectionTerm(coeff=convCoeff) - DiffusionTerm(coeff=(1.0/peclet)) == 0


# The choice of dt and dx in a convection problem is a bit more complicated 
dt = 0.0001

# We might not want to see the output from every single timestep, so we define a stride parameter
time_stride = 200
timestep = 0
Exemple #42
0
 def _calcTangent2(self):
     norm = self.normal
     mag = numerix.sqrt(norm[0] ** 2 + norm[1] ** 2)
     # 	tan2 = numerix.array(norm[0] * norm[2], norm[1] * norm[2], -mag**2)
     tan2 = PhysicalField(value=(norm[0] * norm[2], norm[1] * norm[2], -mag ** 2))
     return tan2 / mag
Exemple #43
0
D = 1.0
U = 100.0
peclet = (U * L / D)
# This is the syntax needed to specify U
convCoeff = (1.0, )

# intial condition width (standard deviation)
sigma = 0.05 * L

#Defining the variable
c = CellVariable(mesh=mesh, name=r"$c$")

# Setting initial conditions
x = mesh.cellCenters[0]
c.value = 0.0
c.setValue(0.05 * (1.0 / (sigma * numerix.sqrt(2 * numerix.pi))) *
           numerix.exp(-0.5 * ((x - 1.0) / (sigma))**2.0))

# defining the equation
# We write three equations: pure convection, pure diffusion and convection-diffusion
# eq = TransientTerm() + VanLeerConvectionTerm(coeff=convCoeff) == 0
# eq = TransientTerm() - DiffusionTerm(coeff=(1/peclet)) == 0
eq = TransientTerm() + VanLeerConvectionTerm(coeff=convCoeff) - DiffusionTerm(
    coeff=(1.0 / peclet)) == 0

# The choice of dt and dx in a convection problem is a bit more complicated
dt = 0.001

# We might not want to see the output from every single timestep, so we define a stride parameter
time_stride = 10
timestep = 0
Exemple #44
0
            def stdParallel(a):
                N = self.mesh.globalNumberOfCells
                mean = self.sum(axis=axis).value / N
                sq_diff = (self - mean)**2

                return numerix.sqrt(sq_diff.sum(axis=axis).value / N)
nx = 256
cfl = 0.1
initialRadius = L / 4.
k = 1
dx = L / nx
steps = 10 * nx / 8

mesh = Grid2D(dx = dx, dy = dx, nx = nx, ny = nx)

error = CellVariable(mesh=mesh)


distanceVariable = DistanceVariable(
    name = 'level set variable',
    mesh = mesh,
    value = numerix.sqrt((mesh.getCellCenters()[:,0] - L / 2.)**2 + (mesh.getCellCenters()[:,1] - L / 2.)**2) - initialRadius,
    hasOld = 1)

initialSurfactantValue =  1.

surfactantVariable = SurfactantVariable(
    value = initialSurfactantValue,
    distanceVar = distanceVariable
    )

velocity = 1.

surfactantEquation = SurfactantEquation(
    distanceVar = distanceVariable)

Exemple #46
0
    def seed(self, profile, **kwargs):
        """
        Seed the value of the variable based on the profile and parameters

        Available profiles are:

            * "normal"
                * normal distribution of values from :data:`scipy.stats.norm`
                * `loc` and `scale` in units compatible with domain mesh
                * `coeff` to multiply the distribution with, in units compatible with that of
                  :attr:`.var`
                * the normal distribution is created to have unit height for different `loc` and
                  `scale` values

            * "linear"
                * uses :func:`~numpy.linspace` to fill the first dimension of :attr:`.var`
                * `start`: the start value given, else taken from constraint "top"
                * `stop`: the stop value given, else taken from constraint "bottom"

            * "lognormal"
                * lognormal distributuion from :data:`scipy.stats.lognorm`
                * `loc` and `scale` should be in units compatible with domain mesh
                * `shape` should be a float > 0
                * the distribution is normalized to have max value = 1

        Args:
            profile (str): The type of profile to use
            **kwargs: Parmeters for the profile

        Returns:
            None

        Raises:
            ValueError: if incompatible units encountered


        """
        PROFILES = ('linear', 'normal', 'lognormal')

        if profile not in PROFILES:
            raise ValueError('Unknown profile {!r} not in {}'.format(
                profile, PROFILES))

        if profile == 'normal':
            from scipy.stats import norm
            loc = kwargs['loc']
            scale = kwargs['scale']
            coeff = kwargs['coeff']

            C = 1.0 / numerix.sqrt(2 * numerix.pi)

            # loc and scale should be in units of the domain mesh
            if hasattr(loc, 'unit'):
                loc_ = loc.inUnitsOf(self.domain.depths.unit).value
            else:
                loc_ = loc

            if hasattr(scale, 'unit'):
                scale_ = scale.inUnitsOf(self.domain.depths.unit).value
            else:
                scale_ = scale

            if hasattr(coeff, 'unit'):
                # check if compatible with variable unit
                try:
                    c = coeff.inUnitsOf(self.var.unit)
                except TypeError:
                    self.logger.error(
                        'Coeff {!r} not compatible with variable unit {!r}'.
                        format(coeff, self.var.unit.name()))
                    raise ValueError('Incompatible unit of coefficient')

            self.logger.info(
                'Seeding with profile normal loc: {} scale: {} coeff: {}'.
                format(loc_, scale_, coeff))

            normrv = norm(loc=loc_, scale=scale_)
            rvpdf = normrv.pdf(self.domain.depths)
            rvpdf /= rvpdf.max()
            val = coeff * rvpdf

            self.var.value = val

        elif profile == 'lognormal':
            from scipy.stats import lognorm

            loc = kwargs['loc']
            scale = kwargs['scale']
            coeff = kwargs['coeff']
            lognorm_shape = kwargs.get('shape', 1.25)

            # loc and scale should be in units of the domain mesh
            if hasattr(loc, 'unit'):
                loc_ = loc.inUnitsOf(self.domain.depths.unit).value
            else:
                loc_ = loc

            if hasattr(scale, 'unit'):
                scale_ = scale.inUnitsOf(self.domain.depths.unit).value
            else:
                scale_ = scale

            if hasattr(coeff, 'unit'):
                # check if compatible with variable unit
                try:
                    c = coeff.inUnitsOf(self.var.unit)
                except TypeError:
                    self.logger.error(
                        'Coeff {!r} not compatible with variable unit {!r}'.
                        format(coeff, self.var.unit.name()))
                    raise ValueError('Incompatible unit of coefficient')

            self.logger.info(
                'Seeding with profile lognormal loc: {} scale: {} shape: {} '
                'coeff: {}'.format(loc_, scale_, lognorm_shape, coeff))

            rv = lognorm(lognorm_shape, loc=loc_, scale=scale_)
            rvpdf = rv.pdf(self.domain.depths)
            rvpdf = rvpdf / rvpdf.max()
            val = coeff * rvpdf

            self.var.value = val

        elif profile == 'linear':
            start = kwargs.get('start')
            stop = kwargs.get('stop')

            if start is None:
                start = self.constraints.get('top')
                if start is None:
                    raise ValueError(
                        'Seed linear has no "start" or "top" constraint')
                else:
                    start = PhysicalField(start, self.var.unit)
                    self.logger.info('Linear seed using start as top value: '
                                     '{}'.format(start))

            if stop is None:
                stop = self.constraints.get('bottom')
                if stop is None:
                    raise ValueError(
                        'Seed linear has no "stop" or "bottom" constraint')
                else:
                    stop = PhysicalField(stop, self.var.unit)
                    self.logger.info('Linear seed using stop as bottom value: '
                                     '{}'.format(stop))

            N = self.var.shape[0]

            if hasattr(start, 'unit'):
                start_ = start.inUnitsOf(self.var.unit).value
            else:
                start_ = start

            if hasattr(stop, 'unit'):
                stop_ = stop.inUnitsOf(self.var.unit).value
            else:
                stop_ = stop

            self.logger.info(
                'Seeding with profile linear: start: {} stop: {}'.format(
                    start_, stop_))

            val = numerix.linspace(start_, stop_, N)
            self.var.value = val

        self.logger.debug('Seeded {!r} with {} profile'.format(self, profile))
Exemple #47
0
from fipy.variables.cellVariable import CellVariable

L = 1.
nx = 50
cfl = 0.1
initialRadius = L / 4.
k = 1
dx = L / nx
steps = 20

mesh = Grid2D(dx = dx, dy = dx, nx = nx, ny = nx)

distanceVariable = DistanceVariable(
    name = 'level set variable',
    mesh = mesh,
    value = numerix.sqrt((mesh.getCellCenters()[:,0] - L / 2.)**2 + (mesh.getCellCenters()[:,1] - L / 2.)**2) - initialRadius,
    hasOld = 1)

initialSurfactantValue =  1.

surfactantVariable = SurfactantVariable(
    value = initialSurfactantValue,
    distanceVar = distanceVariable
    )

velocity = CellVariable(
    name = 'velocity',
    mesh = mesh,
    value = 1.,
    )
Exemple #48
0
    def _calcTrialValue(self, id, evaluatedFlag, extensionVariable):
        adjIDs = self.cellToCellIDs[...,id]
        adjEvaluatedFlag = numerix.take(evaluatedFlag, adjIDs)
        adjValues = numerix.take(self.value, adjIDs)
        adjValues = numerix.where(adjEvaluatedFlag, adjValues, 1e+10)
        try:
            indices = numerix.argsort(abs(adjValues))
        except TypeError:
            # numpy 1.1 raises a TypeError when using argsort function
            indices = abs(adjValues).argsort()
        sign = (self.value[id] > 0) * 2 - 1
        d0 = self.cellToCellDistances[indices[0], id]
        v0 = self.value[..., adjIDs[indices[0]]]
        e0 = extensionVariable[..., adjIDs[indices[0]]]

        N = numerix.sum(adjEvaluatedFlag)

        index0 = indices[0]
        index1 = indices[1]
        index2 = indices[self.mesh.getDim()]
        
        if N > 1:
            n0 = self.cellNormals[..., index0, id]
            n1 = self.cellNormals[..., index1, id]

            if self.mesh.getDim() == 2:
                cross = (n0[0] * n1[1] - n0[1] * n1[0])
            else:
                cross = 0.0
                
            if abs(cross) < 0.1:
                if N == 2:
                    N = 1
                elif N == 3:
                    index1 = index2

        if N == 0:
            raise Exception 
        elif N == 1:
            return v0 + sign * d0, e0
        else:
            d1 = self.cellToCellDistances[index1, id]
            n0 = self.cellNormals[..., index0, id]
            n1 = self.cellNormals[..., index1, id]
            v1 = self.value[..., adjIDs[index1]]
            
            crossProd = d0 * d1 * (n0[0] * n1[1] - n0[1] * n1[0])
            dotProd = d0 * d1 * numerix.dot(n0, n1)
            dsq = d0**2 + d1**2 - 2 * dotProd
            
            top = -v0 * (dotProd - d1**2) - v1 * (dotProd - d0**2)
            sqrt = crossProd**2 *(dsq - (v0 - v1)**2)
            sqrt = numerix.sqrt(max(sqrt, 0))



            dis = (top + sign * sqrt) / dsq

            ## extension variable

            e1 = extensionVariable[..., adjIDs[index1]]
            a0 = self.cellAreas[index0, id]
            a1 = self.cellAreas[index1, id]

            if self.value[id] > 0:
                phi = max(dis, 0)
            else:
                phi = min(dis, 0)

            n0grad = a0 * abs(v0 - phi) / d0
            n1grad = a1 * abs(v1 - phi) / d1
            
            return dis, (e0 * n0grad + e1 * n1grad) / (n0grad + n1grad)
Exemple #49
0
    charge.setValue(-1, where=mesh.physicalCells["Cathode"])

    potential = CellVariable(mesh=mesh, name=r"$\psi$")
    potential.constrain(0., where=mesh.physicalFaces["Ground"])

    eq = DiffusionTerm(coeff=1.) == -charge

    res0 = eq.sweep(var=potential)

    res = eq.justResidualVector(var=potential)

    res1 = numerix.L2norm(res)
    res1a = CellVariable(mesh=mesh, value=abs(res))

    res = CellVariable(mesh=mesh, name="residual", value=abs(res) / mesh.cellVolumes**(1./mesh.dim) / 1e-3)

    # want cells no bigger than 1 and no smaller than 0.001
    maxSize = 1.
    minSize = 0.001
    monitor = CellVariable(mesh=mesh, name="monitor", value= 1. / (res + maxSize) +  minSize)

    viewer = Viewer(vars=potential, xmin=3.5, xmax=4.5, ymin=3.5, ymax=4.5)
#     viewer = Viewer(vars=(potential, charge))
    viewer.plot()

#     resviewer = Viewer(vars=res1a, log=True, datamin=1e-6, datamax=1e-2, cmap=cm.gray)
#     monviewer = Viewer(vars=monitor, log=True, datamin=1e-3, datamax=1)

    raw_input("refinement %d, res0: %g, res: %g:%g, N: %d, min: %g, max: %g, avg: %g. Press <return> to proceed..." \
              % (refinement, res0, res1, res1a.cellVolumeAverage, mesh.numberOfCells, numerix.sqrt(min(mesh.cellVolumes)), numerix.sqrt(max(mesh.cellVolumes)), numerix.mean(numerix.sqrt(mesh.cellVolumes))))
Exemple #50
0
Fichier : mesh.py Projet : ghorn/Eg
    $ python setup.py efficiency_test
"""
__docformat__ = 'restructuredtext'

if __name__ == "__main__":

    from fipy.tools.parser import parse

    from benchmarker import Benchmarker
    bench = Benchmarker()

    numberOfElements = parse('--numberOfElements',
                             action='store',
                             type='int',
                             default=100)

    bench.start()

    from fipy.tools import numerix
    nx = int(numerix.sqrt(numberOfElements))
    ny = nx
    dx = 1.
    dy = 1.

    from fipy.meshes.grid2D import Grid2D
    mesh = Grid2D(nx=nx, ny=nx, dx=dx, dy=dy)

    bench.stop('mesh')

    print bench.report(numberOfElements=numberOfElements)
    def _plot(self):
        from scipy.interpolate import griddata

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

        xmin, ymin = mesh.extents['min']
        xmax, ymax = mesh.extents['max']

        N = 100
        X = numerix.linspace(xmin, xmax, N)
        Y = numerix.linspace(ymin, ymax, N)

        grid_x, grid_y = numerix.mgrid[xmin:xmax:N * 1j, ymin:ymax:N * 1j]

        if isinstance(var, FaceVariable):
            C = mesh.faceCenters
        elif isinstance(var, CellVariable):
            C = mesh.cellCenters

        U = griddata(C.value.T, var.value[0], (grid_x, grid_y), method='cubic')
        V = griddata(C.value.T, var.value[1], (grid_x, grid_y), method='cubic')

        lw = self.linewidth
        if isinstance(lw, (FaceVariable, CellVariable)):
            lw = griddata(C.value.T,
                          lw.value, (grid_x, grid_y),
                          method='cubic')

        color = self.color
        if isinstance(color, (FaceVariable, CellVariable)):
            color = griddata(C.value.T,
                             color.value, (grid_x, grid_y),
                             method='cubic',
                             fill_value=color.min())

        U = U.T
        V = V.T

        ang = numerix.arctan2(V, U)
        mag = numerix.sqrt(U**2 + V**2)

        datamin, datamax = self._autoscale(vars=(mag, ),
                                           datamin=self._getLimit('datamin'),
                                           datamax=self._getLimit('datamax'))

        mag = numerix.where(mag > datamax, numerix.nan, mag)
        mag = numerix.where(mag < datamin, numerix.nan, mag)

        if self.log:
            mag = numerix.log10(mag)

        U = mag * numerix.cos(ang)
        V = mag * numerix.sin(ang)

        #         if self._stream is not None:
        #             # the following doesn't work, nor does it help to `add_collection` first
        #             # self._stream.arrows.remove()
        #             self._stream.lines.remove()

        self.axes.cla()
        self._stream = self.axes.streamplot(X,
                                            Y,
                                            U,
                                            V,
                                            linewidth=lw,
                                            color=color,
                                            **self.kwargs)

        self.axes.set_xlim(xmin=self._getLimit('xmin'),
                           xmax=self._getLimit('xmax'))
        self.axes.set_ylim(ymin=self._getLimit('ymin'),
                           ymax=self._getLimit('ymax'))
Exemple #52
0
    
    TMView = TMVar / TMVar.getCellVolumeAverage()
    TMView.setName('TM')
    TMViewer = make(TMView, limits = {'datamax' : 2., 'datamin' : 0.}, title = '')

    for i in range(100):
        for var, eqn in eqs:
            var.updateOld()
        for var, eqn in eqs:
            eqn.solve(var, dt = 1.)

    x = mesh.getCellCenters()[:,0]
    y = mesh.getCellCenters()[:,1]

    from fipy.tools.numerix import sqrt
    RVar[:] = L / sqrt((x - L / 2)**2 + (y - 2 * L)**2)
    
    for i in range(100):
        for var, eqn in eqs:
            var.updateOld()
        for var, eqn in eqs:
            eqn.solve(var, dt = 1.)

        PNViewer.plot()
        KMViewer.plot()
        TMViewer.plot()

    raw_input("finished")