Beispiel #1
0
 def _getitemClass(self, index):
     if not isinstance(index, tuple):
         if isinstance(index, list):
             index = tuple(index)
         else:
             index = (index, )
     indexshape = numerix._indexShape(index=index, arrayShape=self.shape)
     if (len(indexshape) > 0 and indexshape[-1] == self.shape[-1]
             and numerix.obj2sctype(index[-1]) != numerix.obj2sctype(bool)):
         return self._OperatorVariableClass()
     else:
         return Variable._OperatorVariableClass(self, baseClass=Variable)
Beispiel #2
0
 def _getitemClass(self, index):
     if not isinstance(index, tuple):
         if isinstance(index, list):
             index = tuple(index)
         else:
             index = (index,)
     indexshape = numerix._indexShape(index=index, arrayShape=self.shape)
     if (len(indexshape) > 0
         and indexshape[-1] == self.shape[-1]
         and numerix.obj2sctype(index[-1]) != numerix.obj2sctype(bool)):
         return self._OperatorVariableClass()
     else:
         return Variable._OperatorVariableClass(self, baseClass=Variable)
Beispiel #3
0
 def _getGlobalValue(self, localIDs, globalIDs):
     localValue = self.getValue()
     if self.getMesh().communicator.Nproc > 1:
         if localValue.shape[-1] != 0:
             localValue = localValue[..., localIDs]
         globalIDs = numerix.concatenate(self.getMesh().communicator.allgather(globalIDs))
         
         globalValue = numerix.empty(localValue.shape[:-1] + (max(globalIDs) + 1,), 
                                     dtype=numerix.obj2sctype(localValue))
         globalValue[..., globalIDs] = numerix.concatenate(self.getMesh().communicator.allgather(localValue), axis=-1)
         
         return globalValue
     else:
         return localValue
Beispiel #4
0
    def _getGlobalValue(self, localIDs, globalIDs):
        localValue = self.value
        if self.mesh.communicator.Nproc > 1:
            if localValue.shape[-1] != 0:
                localValue = localValue[..., localIDs]
            globalIDs = numerix.concatenate(
                self.mesh.communicator.allgather(globalIDs))

            globalValue = numerix.empty(localValue.shape[:-1] +
                                        (max(globalIDs) + 1, ),
                                        dtype=numerix.obj2sctype(localValue))
            globalValue[..., globalIDs] = numerix.concatenate(
                self.mesh.communicator.allgather(localValue), axis=-1)

            return globalValue
        else:
            return localValue
Beispiel #5
0
 def _getGlobalValue(self, localIDs, globalIDs):
     from fipy.tools import parallel
     localValue = self.getValue()
     if parallel.Nproc > 1:
         from mpi4py import MPI
         comm = MPI.COMM_WORLD
         if localValue.shape[-1] != 0:
             localValue = localValue[..., localIDs]
         globalIDs = numerix.concatenate(comm.allgather(globalIDs))
         
         globalValue = numerix.empty(localValue.shape[:-1] + (max(globalIDs) + 1,), 
                                     dtype=numerix.obj2sctype(localValue))
         globalValue[..., globalIDs] = numerix.concatenate(comm.allgather(localValue), axis=-1)
         
         return globalValue
     else:
         return localValue
Beispiel #6
0
    def getsctype(self, default=None):
        """

        Returns the Numpy sctype of the underlying array.

            >>> Variable(1).getsctype() == numerix.NUMERIX.obj2sctype(numerix.array(1))
            True
            >>> Variable(1.).getsctype() == numerix.NUMERIX.obj2sctype(numerix.array(1.))
            True
            >>> Variable((1,1.)).getsctype() == numerix.NUMERIX.obj2sctype(numerix.array((1., 1.)))
            True
            
        """
        
        if not hasattr(self, 'typecode'):
            self.typecode = numerix.obj2sctype(rep=self.getNumericValue(), default=default)
        
        return self.typecode
Beispiel #7
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)
Beispiel #8
0
 def getsctype(self, default=None):
     if not hasattr(self, 'typecode'):
         self.typecode = numerix.obj2sctype(rep=self.numericValue,
                                            default=default)
     return self.typecode
Beispiel #9
0
    def _execInline(self, comment=None):
        """
        Gets the stack from _getCstring() which calls _getRepresentation()
        
            >>> (Variable((1,2,3,4)) * Variable((5,6,7,8)))._getCstring()
            '(var0[i] * var1[i])'
            >>> (Variable(((1,2),(3,4))) * Variable(((5,6),(7,8))))._getCstring()
            '(var0[i + j * ni] * var1[i + j * ni])'
            >>> (Variable((1,2)) * Variable((5,6)) * Variable((7,8)))._getCstring()
            '((var00[i] * var01[i]) * var1[i])'

        The following test was implemented due to a problem with
        contiguous arrays.  The `mesh.getCellCenters()[1]` command
        introduces a non-contiguous array into the `Variable` and this
        causes the inline routine to return senseless results.
        
            >>> from fipy import Grid2D, CellVariable
            >>> mesh = Grid2D(dx=1., dy=1., nx=2, ny=2)
            >>> var = CellVariable(mesh=mesh, value=0.)
            >>> Y =  mesh.getCellCenters()[1]
            >>> var.setValue(Y + 1.0)
            >>> print var - Y
            [ 1.  1.  1.  1.]
        """
    
        from fipy.tools import inline
        argDict = {}
        string = self._getCstring(argDict=argDict, freshen=True) + ';'
        
        try:
            shape = self.opShape
        except AttributeError:
            shape = self.shape

        dimensions = len(shape)
            
        if dimensions == 0:
            string = 'result[0] = ' + string
            dim = ()
        else:
            string = 'result' + self._getCIndexString(shape) + ' = ' + string
            ni = self.opShape[-1]
            argDict['ni'] = ni
            if dimensions == 1:
                dim = (ni)
            else:
                nj = self.opShape[-2]
                argDict['nj'] = nj
                if dimensions == 2:
                    dim =(nj,ni)
                elif dimensions == 3:
                    nk = self.opShape[-3]
                    dim = (nk,nj,ni)
                    argDict['nk'] = nk
                else:
                    raise DimensionError, 'Impossible Dimensions'

        ## Following section makes sure that the result array has a
        ## valid typecode. If self.value is None then a typecode is
        ## assigned to the Variable by running the calculation without
        ## inlining. The non-inlined result is thus used the first
        ## time through.

        
        if self.value is None and not hasattr(self, 'typecode'):
            self.canInline = False
            argDict['result'] = self.getValue()
            self.canInline = True
            self.typecode = numerix.obj2sctype(argDict['result'])
        else:
            if self.value is None:
                if self.getsctype() == numerix.bool_:
                    argDict['result'] = numerix.empty(dim, numerix.int8)
                else:
                    argDict['result'] = numerix.empty(dim, self.getsctype())
            else:
                argDict['result'] = self.value

            resultShape = argDict['result'].shape

            if resultShape == ():
                argDict['result'] = numerix.reshape(argDict['result'], (1,))

            inline._runInline(string, converters=None, comment=comment, **argDict)

            if resultShape == ():
                argDict['result'] = numerix.reshape(argDict['result'], resultShape)

        return argDict['result']
Beispiel #10
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)
Beispiel #11
0
 def getsctype(self, default=None):
     if not hasattr(self, 'typecode'):
         self.typecode = numerix.obj2sctype(rep=self.numericValue, default=default)        
     return self.typecode